logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

ast.py (59572B)


  1. """
  2. ast
  3. ~~~
  4. The `ast` module helps Python applications to process trees of the Python
  5. abstract syntax grammar. The abstract syntax itself might change with
  6. each Python release; this module helps to find out programmatically what
  7. the current grammar looks like and allows modifications of it.
  8. An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
  9. a flag to the `compile()` builtin function or by using the `parse()`
  10. function from this module. The result will be a tree of objects whose
  11. classes all inherit from `ast.AST`.
  12. A modified abstract syntax tree can be compiled into a Python code object
  13. using the built-in `compile()` function.
  14. Additionally various helper functions are provided that make working with
  15. the trees simpler. The main intention of the helper functions and this
  16. module in general is to provide an easy to use interface for libraries
  17. that work tightly with the python syntax (template engines for example).
  18. :copyright: Copyright 2008 by Armin Ronacher.
  19. :license: Python License.
  20. """
  21. import sys
  22. from _ast import *
  23. from contextlib import contextmanager, nullcontext
  24. from enum import IntEnum, auto
  25. def parse(source, filename='<unknown>', mode='exec', *,
  26. type_comments=False, feature_version=None):
  27. """
  28. Parse the source into an AST node.
  29. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
  30. Pass type_comments=True to get back type comments where the syntax allows.
  31. """
  32. flags = PyCF_ONLY_AST
  33. if type_comments:
  34. flags |= PyCF_TYPE_COMMENTS
  35. if isinstance(feature_version, tuple):
  36. major, minor = feature_version # Should be a 2-tuple.
  37. assert major == 3
  38. feature_version = minor
  39. elif feature_version is None:
  40. feature_version = -1
  41. # Else it should be an int giving the minor version for 3.x.
  42. return compile(source, filename, mode, flags,
  43. _feature_version=feature_version)
  44. def literal_eval(node_or_string):
  45. """
  46. Safely evaluate an expression node or a string containing a Python
  47. expression. The string or node provided may only consist of the following
  48. Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
  49. sets, booleans, and None.
  50. """
  51. if isinstance(node_or_string, str):
  52. node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
  53. if isinstance(node_or_string, Expression):
  54. node_or_string = node_or_string.body
  55. def _raise_malformed_node(node):
  56. msg = "malformed node or string"
  57. if lno := getattr(node, 'lineno', None):
  58. msg += f' on line {lno}'
  59. raise ValueError(msg + f': {node!r}')
  60. def _convert_num(node):
  61. if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
  62. _raise_malformed_node(node)
  63. return node.value
  64. def _convert_signed_num(node):
  65. if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
  66. operand = _convert_num(node.operand)
  67. if isinstance(node.op, UAdd):
  68. return + operand
  69. else:
  70. return - operand
  71. return _convert_num(node)
  72. def _convert(node):
  73. if isinstance(node, Constant):
  74. return node.value
  75. elif isinstance(node, Tuple):
  76. return tuple(map(_convert, node.elts))
  77. elif isinstance(node, List):
  78. return list(map(_convert, node.elts))
  79. elif isinstance(node, Set):
  80. return set(map(_convert, node.elts))
  81. elif (isinstance(node, Call) and isinstance(node.func, Name) and
  82. node.func.id == 'set' and node.args == node.keywords == []):
  83. return set()
  84. elif isinstance(node, Dict):
  85. if len(node.keys) != len(node.values):
  86. _raise_malformed_node(node)
  87. return dict(zip(map(_convert, node.keys),
  88. map(_convert, node.values)))
  89. elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
  90. left = _convert_signed_num(node.left)
  91. right = _convert_num(node.right)
  92. if isinstance(left, (int, float)) and isinstance(right, complex):
  93. if isinstance(node.op, Add):
  94. return left + right
  95. else:
  96. return left - right
  97. return _convert_signed_num(node)
  98. return _convert(node_or_string)
  99. def dump(node, annotate_fields=True, include_attributes=False, *, indent=None):
  100. """
  101. Return a formatted dump of the tree in node. This is mainly useful for
  102. debugging purposes. If annotate_fields is true (by default),
  103. the returned string will show the names and the values for fields.
  104. If annotate_fields is false, the result string will be more compact by
  105. omitting unambiguous field names. Attributes such as line
  106. numbers and column offsets are not dumped by default. If this is wanted,
  107. include_attributes can be set to true. If indent is a non-negative
  108. integer or string, then the tree will be pretty-printed with that indent
  109. level. None (the default) selects the single line representation.
  110. """
  111. def _format(node, level=0):
  112. if indent is not None:
  113. level += 1
  114. prefix = '\n' + indent * level
  115. sep = ',\n' + indent * level
  116. else:
  117. prefix = ''
  118. sep = ', '
  119. if isinstance(node, AST):
  120. cls = type(node)
  121. args = []
  122. allsimple = True
  123. keywords = annotate_fields
  124. for name in node._fields:
  125. try:
  126. value = getattr(node, name)
  127. except AttributeError:
  128. keywords = True
  129. continue
  130. if value is None and getattr(cls, name, ...) is None:
  131. keywords = True
  132. continue
  133. value, simple = _format(value, level)
  134. allsimple = allsimple and simple
  135. if keywords:
  136. args.append('%s=%s' % (name, value))
  137. else:
  138. args.append(value)
  139. if include_attributes and node._attributes:
  140. for name in node._attributes:
  141. try:
  142. value = getattr(node, name)
  143. except AttributeError:
  144. continue
  145. if value is None and getattr(cls, name, ...) is None:
  146. continue
  147. value, simple = _format(value, level)
  148. allsimple = allsimple and simple
  149. args.append('%s=%s' % (name, value))
  150. if allsimple and len(args) <= 3:
  151. return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
  152. return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
  153. elif isinstance(node, list):
  154. if not node:
  155. return '[]', True
  156. return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
  157. return repr(node), True
  158. if not isinstance(node, AST):
  159. raise TypeError('expected AST, got %r' % node.__class__.__name__)
  160. if indent is not None and not isinstance(indent, str):
  161. indent = ' ' * indent
  162. return _format(node)[0]
  163. def copy_location(new_node, old_node):
  164. """
  165. Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
  166. attributes) from *old_node* to *new_node* if possible, and return *new_node*.
  167. """
  168. for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
  169. if attr in old_node._attributes and attr in new_node._attributes:
  170. value = getattr(old_node, attr, None)
  171. # end_lineno and end_col_offset are optional attributes, and they
  172. # should be copied whether the value is None or not.
  173. if value is not None or (
  174. hasattr(old_node, attr) and attr.startswith("end_")
  175. ):
  176. setattr(new_node, attr, value)
  177. return new_node
  178. def fix_missing_locations(node):
  179. """
  180. When you compile a node tree with compile(), the compiler expects lineno and
  181. col_offset attributes for every node that supports them. This is rather
  182. tedious to fill in for generated nodes, so this helper adds these attributes
  183. recursively where not already set, by setting them to the values of the
  184. parent node. It works recursively starting at *node*.
  185. """
  186. def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
  187. if 'lineno' in node._attributes:
  188. if not hasattr(node, 'lineno'):
  189. node.lineno = lineno
  190. else:
  191. lineno = node.lineno
  192. if 'end_lineno' in node._attributes:
  193. if getattr(node, 'end_lineno', None) is None:
  194. node.end_lineno = end_lineno
  195. else:
  196. end_lineno = node.end_lineno
  197. if 'col_offset' in node._attributes:
  198. if not hasattr(node, 'col_offset'):
  199. node.col_offset = col_offset
  200. else:
  201. col_offset = node.col_offset
  202. if 'end_col_offset' in node._attributes:
  203. if getattr(node, 'end_col_offset', None) is None:
  204. node.end_col_offset = end_col_offset
  205. else:
  206. end_col_offset = node.end_col_offset
  207. for child in iter_child_nodes(node):
  208. _fix(child, lineno, col_offset, end_lineno, end_col_offset)
  209. _fix(node, 1, 0, 1, 0)
  210. return node
  211. def increment_lineno(node, n=1):
  212. """
  213. Increment the line number and end line number of each node in the tree
  214. starting at *node* by *n*. This is useful to "move code" to a different
  215. location in a file.
  216. """
  217. for child in walk(node):
  218. if 'lineno' in child._attributes:
  219. child.lineno = getattr(child, 'lineno', 0) + n
  220. if (
  221. "end_lineno" in child._attributes
  222. and (end_lineno := getattr(child, "end_lineno", 0)) is not None
  223. ):
  224. child.end_lineno = end_lineno + n
  225. return node
  226. def iter_fields(node):
  227. """
  228. Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
  229. that is present on *node*.
  230. """
  231. for field in node._fields:
  232. try:
  233. yield field, getattr(node, field)
  234. except AttributeError:
  235. pass
  236. def iter_child_nodes(node):
  237. """
  238. Yield all direct child nodes of *node*, that is, all fields that are nodes
  239. and all items of fields that are lists of nodes.
  240. """
  241. for name, field in iter_fields(node):
  242. if isinstance(field, AST):
  243. yield field
  244. elif isinstance(field, list):
  245. for item in field:
  246. if isinstance(item, AST):
  247. yield item
  248. def get_docstring(node, clean=True):
  249. """
  250. Return the docstring for the given node or None if no docstring can
  251. be found. If the node provided does not have docstrings a TypeError
  252. will be raised.
  253. If *clean* is `True`, all tabs are expanded to spaces and any whitespace
  254. that can be uniformly removed from the second line onwards is removed.
  255. """
  256. if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
  257. raise TypeError("%r can't have docstrings" % node.__class__.__name__)
  258. if not(node.body and isinstance(node.body[0], Expr)):
  259. return None
  260. node = node.body[0].value
  261. if isinstance(node, Str):
  262. text = node.s
  263. elif isinstance(node, Constant) and isinstance(node.value, str):
  264. text = node.value
  265. else:
  266. return None
  267. if clean:
  268. import inspect
  269. text = inspect.cleandoc(text)
  270. return text
  271. def _splitlines_no_ff(source):
  272. """Split a string into lines ignoring form feed and other chars.
  273. This mimics how the Python parser splits source code.
  274. """
  275. idx = 0
  276. lines = []
  277. next_line = ''
  278. while idx < len(source):
  279. c = source[idx]
  280. next_line += c
  281. idx += 1
  282. # Keep \r\n together
  283. if c == '\r' and idx < len(source) and source[idx] == '\n':
  284. next_line += '\n'
  285. idx += 1
  286. if c in '\r\n':
  287. lines.append(next_line)
  288. next_line = ''
  289. if next_line:
  290. lines.append(next_line)
  291. return lines
  292. def _pad_whitespace(source):
  293. r"""Replace all chars except '\f\t' in a line with spaces."""
  294. result = ''
  295. for c in source:
  296. if c in '\f\t':
  297. result += c
  298. else:
  299. result += ' '
  300. return result
  301. def get_source_segment(source, node, *, padded=False):
  302. """Get source code segment of the *source* that generated *node*.
  303. If some location information (`lineno`, `end_lineno`, `col_offset`,
  304. or `end_col_offset`) is missing, return None.
  305. If *padded* is `True`, the first line of a multi-line statement will
  306. be padded with spaces to match its original position.
  307. """
  308. try:
  309. if node.end_lineno is None or node.end_col_offset is None:
  310. return None
  311. lineno = node.lineno - 1
  312. end_lineno = node.end_lineno - 1
  313. col_offset = node.col_offset
  314. end_col_offset = node.end_col_offset
  315. except AttributeError:
  316. return None
  317. lines = _splitlines_no_ff(source)
  318. if end_lineno == lineno:
  319. return lines[lineno].encode()[col_offset:end_col_offset].decode()
  320. if padded:
  321. padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
  322. else:
  323. padding = ''
  324. first = padding + lines[lineno].encode()[col_offset:].decode()
  325. last = lines[end_lineno].encode()[:end_col_offset].decode()
  326. lines = lines[lineno+1:end_lineno]
  327. lines.insert(0, first)
  328. lines.append(last)
  329. return ''.join(lines)
  330. def walk(node):
  331. """
  332. Recursively yield all descendant nodes in the tree starting at *node*
  333. (including *node* itself), in no specified order. This is useful if you
  334. only want to modify nodes in place and don't care about the context.
  335. """
  336. from collections import deque
  337. todo = deque([node])
  338. while todo:
  339. node = todo.popleft()
  340. todo.extend(iter_child_nodes(node))
  341. yield node
  342. class NodeVisitor(object):
  343. """
  344. A node visitor base class that walks the abstract syntax tree and calls a
  345. visitor function for every node found. This function may return a value
  346. which is forwarded by the `visit` method.
  347. This class is meant to be subclassed, with the subclass adding visitor
  348. methods.
  349. Per default the visitor functions for the nodes are ``'visit_'`` +
  350. class name of the node. So a `TryFinally` node visit function would
  351. be `visit_TryFinally`. This behavior can be changed by overriding
  352. the `visit` method. If no visitor function exists for a node
  353. (return value `None`) the `generic_visit` visitor is used instead.
  354. Don't use the `NodeVisitor` if you want to apply changes to nodes during
  355. traversing. For this a special visitor exists (`NodeTransformer`) that
  356. allows modifications.
  357. """
  358. def visit(self, node):
  359. """Visit a node."""
  360. method = 'visit_' + node.__class__.__name__
  361. visitor = getattr(self, method, self.generic_visit)
  362. return visitor(node)
  363. def generic_visit(self, node):
  364. """Called if no explicit visitor function exists for a node."""
  365. for field, value in iter_fields(node):
  366. if isinstance(value, list):
  367. for item in value:
  368. if isinstance(item, AST):
  369. self.visit(item)
  370. elif isinstance(value, AST):
  371. self.visit(value)
  372. def visit_Constant(self, node):
  373. value = node.value
  374. type_name = _const_node_type_names.get(type(value))
  375. if type_name is None:
  376. for cls, name in _const_node_type_names.items():
  377. if isinstance(value, cls):
  378. type_name = name
  379. break
  380. if type_name is not None:
  381. method = 'visit_' + type_name
  382. try:
  383. visitor = getattr(self, method)
  384. except AttributeError:
  385. pass
  386. else:
  387. import warnings
  388. warnings.warn(f"{method} is deprecated; add visit_Constant",
  389. DeprecationWarning, 2)
  390. return visitor(node)
  391. return self.generic_visit(node)
  392. class NodeTransformer(NodeVisitor):
  393. """
  394. A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
  395. allows modification of nodes.
  396. The `NodeTransformer` will walk the AST and use the return value of the
  397. visitor methods to replace or remove the old node. If the return value of
  398. the visitor method is ``None``, the node will be removed from its location,
  399. otherwise it is replaced with the return value. The return value may be the
  400. original node in which case no replacement takes place.
  401. Here is an example transformer that rewrites all occurrences of name lookups
  402. (``foo``) to ``data['foo']``::
  403. class RewriteName(NodeTransformer):
  404. def visit_Name(self, node):
  405. return Subscript(
  406. value=Name(id='data', ctx=Load()),
  407. slice=Constant(value=node.id),
  408. ctx=node.ctx
  409. )
  410. Keep in mind that if the node you're operating on has child nodes you must
  411. either transform the child nodes yourself or call the :meth:`generic_visit`
  412. method for the node first.
  413. For nodes that were part of a collection of statements (that applies to all
  414. statement nodes), the visitor may also return a list of nodes rather than
  415. just a single node.
  416. Usually you use the transformer like this::
  417. node = YourTransformer().visit(node)
  418. """
  419. def generic_visit(self, node):
  420. for field, old_value in iter_fields(node):
  421. if isinstance(old_value, list):
  422. new_values = []
  423. for value in old_value:
  424. if isinstance(value, AST):
  425. value = self.visit(value)
  426. if value is None:
  427. continue
  428. elif not isinstance(value, AST):
  429. new_values.extend(value)
  430. continue
  431. new_values.append(value)
  432. old_value[:] = new_values
  433. elif isinstance(old_value, AST):
  434. new_node = self.visit(old_value)
  435. if new_node is None:
  436. delattr(node, field)
  437. else:
  438. setattr(node, field, new_node)
  439. return node
  440. # If the ast module is loaded more than once, only add deprecated methods once
  441. if not hasattr(Constant, 'n'):
  442. # The following code is for backward compatibility.
  443. # It will be removed in future.
  444. def _getter(self):
  445. """Deprecated. Use value instead."""
  446. return self.value
  447. def _setter(self, value):
  448. self.value = value
  449. Constant.n = property(_getter, _setter)
  450. Constant.s = property(_getter, _setter)
  451. class _ABC(type):
  452. def __init__(cls, *args):
  453. cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
  454. def __instancecheck__(cls, inst):
  455. if not isinstance(inst, Constant):
  456. return False
  457. if cls in _const_types:
  458. try:
  459. value = inst.value
  460. except AttributeError:
  461. return False
  462. else:
  463. return (
  464. isinstance(value, _const_types[cls]) and
  465. not isinstance(value, _const_types_not.get(cls, ()))
  466. )
  467. return type.__instancecheck__(cls, inst)
  468. def _new(cls, *args, **kwargs):
  469. for key in kwargs:
  470. if key not in cls._fields:
  471. # arbitrary keyword arguments are accepted
  472. continue
  473. pos = cls._fields.index(key)
  474. if pos < len(args):
  475. raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
  476. if cls in _const_types:
  477. return Constant(*args, **kwargs)
  478. return Constant.__new__(cls, *args, **kwargs)
  479. class Num(Constant, metaclass=_ABC):
  480. _fields = ('n',)
  481. __new__ = _new
  482. class Str(Constant, metaclass=_ABC):
  483. _fields = ('s',)
  484. __new__ = _new
  485. class Bytes(Constant, metaclass=_ABC):
  486. _fields = ('s',)
  487. __new__ = _new
  488. class NameConstant(Constant, metaclass=_ABC):
  489. __new__ = _new
  490. class Ellipsis(Constant, metaclass=_ABC):
  491. _fields = ()
  492. def __new__(cls, *args, **kwargs):
  493. if cls is Ellipsis:
  494. return Constant(..., *args, **kwargs)
  495. return Constant.__new__(cls, *args, **kwargs)
  496. _const_types = {
  497. Num: (int, float, complex),
  498. Str: (str,),
  499. Bytes: (bytes,),
  500. NameConstant: (type(None), bool),
  501. Ellipsis: (type(...),),
  502. }
  503. _const_types_not = {
  504. Num: (bool,),
  505. }
  506. _const_node_type_names = {
  507. bool: 'NameConstant', # should be before int
  508. type(None): 'NameConstant',
  509. int: 'Num',
  510. float: 'Num',
  511. complex: 'Num',
  512. str: 'Str',
  513. bytes: 'Bytes',
  514. type(...): 'Ellipsis',
  515. }
  516. class slice(AST):
  517. """Deprecated AST node class."""
  518. class Index(slice):
  519. """Deprecated AST node class. Use the index value directly instead."""
  520. def __new__(cls, value, **kwargs):
  521. return value
  522. class ExtSlice(slice):
  523. """Deprecated AST node class. Use ast.Tuple instead."""
  524. def __new__(cls, dims=(), **kwargs):
  525. return Tuple(list(dims), Load(), **kwargs)
  526. # If the ast module is loaded more than once, only add deprecated methods once
  527. if not hasattr(Tuple, 'dims'):
  528. # The following code is for backward compatibility.
  529. # It will be removed in future.
  530. def _dims_getter(self):
  531. """Deprecated. Use elts instead."""
  532. return self.elts
  533. def _dims_setter(self, value):
  534. self.elts = value
  535. Tuple.dims = property(_dims_getter, _dims_setter)
  536. class Suite(mod):
  537. """Deprecated AST node class. Unused in Python 3."""
  538. class AugLoad(expr_context):
  539. """Deprecated AST node class. Unused in Python 3."""
  540. class AugStore(expr_context):
  541. """Deprecated AST node class. Unused in Python 3."""
  542. class Param(expr_context):
  543. """Deprecated AST node class. Unused in Python 3."""
  544. # Large float and imaginary literals get turned into infinities in the AST.
  545. # We unparse those infinities to INFSTR.
  546. _INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
  547. class _Precedence(IntEnum):
  548. """Precedence table that originated from python grammar."""
  549. TUPLE = auto()
  550. YIELD = auto() # 'yield', 'yield from'
  551. TEST = auto() # 'if'-'else', 'lambda'
  552. OR = auto() # 'or'
  553. AND = auto() # 'and'
  554. NOT = auto() # 'not'
  555. CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
  556. # 'in', 'not in', 'is', 'is not'
  557. EXPR = auto()
  558. BOR = EXPR # '|'
  559. BXOR = auto() # '^'
  560. BAND = auto() # '&'
  561. SHIFT = auto() # '<<', '>>'
  562. ARITH = auto() # '+', '-'
  563. TERM = auto() # '*', '@', '/', '%', '//'
  564. FACTOR = auto() # unary '+', '-', '~'
  565. POWER = auto() # '**'
  566. AWAIT = auto() # 'await'
  567. ATOM = auto()
  568. def next(self):
  569. try:
  570. return self.__class__(self + 1)
  571. except ValueError:
  572. return self
  573. _SINGLE_QUOTES = ("'", '"')
  574. _MULTI_QUOTES = ('"""', "'''")
  575. _ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
  576. class _Unparser(NodeVisitor):
  577. """Methods in this class recursively traverse an AST and
  578. output source code for the abstract syntax; original formatting
  579. is disregarded."""
  580. def __init__(self, *, _avoid_backslashes=False):
  581. self._source = []
  582. self._buffer = []
  583. self._precedences = {}
  584. self._type_ignores = {}
  585. self._indent = 0
  586. self._avoid_backslashes = _avoid_backslashes
  587. def interleave(self, inter, f, seq):
  588. """Call f on each item in seq, calling inter() in between."""
  589. seq = iter(seq)
  590. try:
  591. f(next(seq))
  592. except StopIteration:
  593. pass
  594. else:
  595. for x in seq:
  596. inter()
  597. f(x)
  598. def items_view(self, traverser, items):
  599. """Traverse and separate the given *items* with a comma and append it to
  600. the buffer. If *items* is a single item sequence, a trailing comma
  601. will be added."""
  602. if len(items) == 1:
  603. traverser(items[0])
  604. self.write(",")
  605. else:
  606. self.interleave(lambda: self.write(", "), traverser, items)
  607. def maybe_newline(self):
  608. """Adds a newline if it isn't the start of generated source"""
  609. if self._source:
  610. self.write("\n")
  611. def fill(self, text=""):
  612. """Indent a piece of text and append it, according to the current
  613. indentation level"""
  614. self.maybe_newline()
  615. self.write(" " * self._indent + text)
  616. def write(self, text):
  617. """Append a piece of text"""
  618. self._source.append(text)
  619. def buffer_writer(self, text):
  620. self._buffer.append(text)
  621. @property
  622. def buffer(self):
  623. value = "".join(self._buffer)
  624. self._buffer.clear()
  625. return value
  626. @contextmanager
  627. def block(self, *, extra = None):
  628. """A context manager for preparing the source for blocks. It adds
  629. the character':', increases the indentation on enter and decreases
  630. the indentation on exit. If *extra* is given, it will be directly
  631. appended after the colon character.
  632. """
  633. self.write(":")
  634. if extra:
  635. self.write(extra)
  636. self._indent += 1
  637. yield
  638. self._indent -= 1
  639. @contextmanager
  640. def delimit(self, start, end):
  641. """A context manager for preparing the source for expressions. It adds
  642. *start* to the buffer and enters, after exit it adds *end*."""
  643. self.write(start)
  644. yield
  645. self.write(end)
  646. def delimit_if(self, start, end, condition):
  647. if condition:
  648. return self.delimit(start, end)
  649. else:
  650. return nullcontext()
  651. def require_parens(self, precedence, node):
  652. """Shortcut to adding precedence related parens"""
  653. return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
  654. def get_precedence(self, node):
  655. return self._precedences.get(node, _Precedence.TEST)
  656. def set_precedence(self, precedence, *nodes):
  657. for node in nodes:
  658. self._precedences[node] = precedence
  659. def get_raw_docstring(self, node):
  660. """If a docstring node is found in the body of the *node* parameter,
  661. return that docstring node, None otherwise.
  662. Logic mirrored from ``_PyAST_GetDocString``."""
  663. if not isinstance(
  664. node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)
  665. ) or len(node.body) < 1:
  666. return None
  667. node = node.body[0]
  668. if not isinstance(node, Expr):
  669. return None
  670. node = node.value
  671. if isinstance(node, Constant) and isinstance(node.value, str):
  672. return node
  673. def get_type_comment(self, node):
  674. comment = self._type_ignores.get(node.lineno) or node.type_comment
  675. if comment is not None:
  676. return f" # type: {comment}"
  677. def traverse(self, node):
  678. if isinstance(node, list):
  679. for item in node:
  680. self.traverse(item)
  681. else:
  682. super().visit(node)
  683. # Note: as visit() resets the output text, do NOT rely on
  684. # NodeVisitor.generic_visit to handle any nodes (as it calls back in to
  685. # the subclass visit() method, which resets self._source to an empty list)
  686. def visit(self, node):
  687. """Outputs a source code string that, if converted back to an ast
  688. (using ast.parse) will generate an AST equivalent to *node*"""
  689. self._source = []
  690. self.traverse(node)
  691. return "".join(self._source)
  692. def _write_docstring_and_traverse_body(self, node):
  693. if (docstring := self.get_raw_docstring(node)):
  694. self._write_docstring(docstring)
  695. self.traverse(node.body[1:])
  696. else:
  697. self.traverse(node.body)
  698. def visit_Module(self, node):
  699. self._type_ignores = {
  700. ignore.lineno: f"ignore{ignore.tag}"
  701. for ignore in node.type_ignores
  702. }
  703. self._write_docstring_and_traverse_body(node)
  704. self._type_ignores.clear()
  705. def visit_FunctionType(self, node):
  706. with self.delimit("(", ")"):
  707. self.interleave(
  708. lambda: self.write(", "), self.traverse, node.argtypes
  709. )
  710. self.write(" -> ")
  711. self.traverse(node.returns)
  712. def visit_Expr(self, node):
  713. self.fill()
  714. self.set_precedence(_Precedence.YIELD, node.value)
  715. self.traverse(node.value)
  716. def visit_NamedExpr(self, node):
  717. with self.require_parens(_Precedence.TUPLE, node):
  718. self.set_precedence(_Precedence.ATOM, node.target, node.value)
  719. self.traverse(node.target)
  720. self.write(" := ")
  721. self.traverse(node.value)
  722. def visit_Import(self, node):
  723. self.fill("import ")
  724. self.interleave(lambda: self.write(", "), self.traverse, node.names)
  725. def visit_ImportFrom(self, node):
  726. self.fill("from ")
  727. self.write("." * node.level)
  728. if node.module:
  729. self.write(node.module)
  730. self.write(" import ")
  731. self.interleave(lambda: self.write(", "), self.traverse, node.names)
  732. def visit_Assign(self, node):
  733. self.fill()
  734. for target in node.targets:
  735. self.traverse(target)
  736. self.write(" = ")
  737. self.traverse(node.value)
  738. if type_comment := self.get_type_comment(node):
  739. self.write(type_comment)
  740. def visit_AugAssign(self, node):
  741. self.fill()
  742. self.traverse(node.target)
  743. self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
  744. self.traverse(node.value)
  745. def visit_AnnAssign(self, node):
  746. self.fill()
  747. with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)):
  748. self.traverse(node.target)
  749. self.write(": ")
  750. self.traverse(node.annotation)
  751. if node.value:
  752. self.write(" = ")
  753. self.traverse(node.value)
  754. def visit_Return(self, node):
  755. self.fill("return")
  756. if node.value:
  757. self.write(" ")
  758. self.traverse(node.value)
  759. def visit_Pass(self, node):
  760. self.fill("pass")
  761. def visit_Break(self, node):
  762. self.fill("break")
  763. def visit_Continue(self, node):
  764. self.fill("continue")
  765. def visit_Delete(self, node):
  766. self.fill("del ")
  767. self.interleave(lambda: self.write(", "), self.traverse, node.targets)
  768. def visit_Assert(self, node):
  769. self.fill("assert ")
  770. self.traverse(node.test)
  771. if node.msg:
  772. self.write(", ")
  773. self.traverse(node.msg)
  774. def visit_Global(self, node):
  775. self.fill("global ")
  776. self.interleave(lambda: self.write(", "), self.write, node.names)
  777. def visit_Nonlocal(self, node):
  778. self.fill("nonlocal ")
  779. self.interleave(lambda: self.write(", "), self.write, node.names)
  780. def visit_Await(self, node):
  781. with self.require_parens(_Precedence.AWAIT, node):
  782. self.write("await")
  783. if node.value:
  784. self.write(" ")
  785. self.set_precedence(_Precedence.ATOM, node.value)
  786. self.traverse(node.value)
  787. def visit_Yield(self, node):
  788. with self.require_parens(_Precedence.YIELD, node):
  789. self.write("yield")
  790. if node.value:
  791. self.write(" ")
  792. self.set_precedence(_Precedence.ATOM, node.value)
  793. self.traverse(node.value)
  794. def visit_YieldFrom(self, node):
  795. with self.require_parens(_Precedence.YIELD, node):
  796. self.write("yield from ")
  797. if not node.value:
  798. raise ValueError("Node can't be used without a value attribute.")
  799. self.set_precedence(_Precedence.ATOM, node.value)
  800. self.traverse(node.value)
  801. def visit_Raise(self, node):
  802. self.fill("raise")
  803. if not node.exc:
  804. if node.cause:
  805. raise ValueError(f"Node can't use cause without an exception.")
  806. return
  807. self.write(" ")
  808. self.traverse(node.exc)
  809. if node.cause:
  810. self.write(" from ")
  811. self.traverse(node.cause)
  812. def visit_Try(self, node):
  813. self.fill("try")
  814. with self.block():
  815. self.traverse(node.body)
  816. for ex in node.handlers:
  817. self.traverse(ex)
  818. if node.orelse:
  819. self.fill("else")
  820. with self.block():
  821. self.traverse(node.orelse)
  822. if node.finalbody:
  823. self.fill("finally")
  824. with self.block():
  825. self.traverse(node.finalbody)
  826. def visit_ExceptHandler(self, node):
  827. self.fill("except")
  828. if node.type:
  829. self.write(" ")
  830. self.traverse(node.type)
  831. if node.name:
  832. self.write(" as ")
  833. self.write(node.name)
  834. with self.block():
  835. self.traverse(node.body)
  836. def visit_ClassDef(self, node):
  837. self.maybe_newline()
  838. for deco in node.decorator_list:
  839. self.fill("@")
  840. self.traverse(deco)
  841. self.fill("class " + node.name)
  842. with self.delimit_if("(", ")", condition = node.bases or node.keywords):
  843. comma = False
  844. for e in node.bases:
  845. if comma:
  846. self.write(", ")
  847. else:
  848. comma = True
  849. self.traverse(e)
  850. for e in node.keywords:
  851. if comma:
  852. self.write(", ")
  853. else:
  854. comma = True
  855. self.traverse(e)
  856. with self.block():
  857. self._write_docstring_and_traverse_body(node)
  858. def visit_FunctionDef(self, node):
  859. self._function_helper(node, "def")
  860. def visit_AsyncFunctionDef(self, node):
  861. self._function_helper(node, "async def")
  862. def _function_helper(self, node, fill_suffix):
  863. self.maybe_newline()
  864. for deco in node.decorator_list:
  865. self.fill("@")
  866. self.traverse(deco)
  867. def_str = fill_suffix + " " + node.name
  868. self.fill(def_str)
  869. with self.delimit("(", ")"):
  870. self.traverse(node.args)
  871. if node.returns:
  872. self.write(" -> ")
  873. self.traverse(node.returns)
  874. with self.block(extra=self.get_type_comment(node)):
  875. self._write_docstring_and_traverse_body(node)
  876. def visit_For(self, node):
  877. self._for_helper("for ", node)
  878. def visit_AsyncFor(self, node):
  879. self._for_helper("async for ", node)
  880. def _for_helper(self, fill, node):
  881. self.fill(fill)
  882. self.traverse(node.target)
  883. self.write(" in ")
  884. self.traverse(node.iter)
  885. with self.block(extra=self.get_type_comment(node)):
  886. self.traverse(node.body)
  887. if node.orelse:
  888. self.fill("else")
  889. with self.block():
  890. self.traverse(node.orelse)
  891. def visit_If(self, node):
  892. self.fill("if ")
  893. self.traverse(node.test)
  894. with self.block():
  895. self.traverse(node.body)
  896. # collapse nested ifs into equivalent elifs.
  897. while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):
  898. node = node.orelse[0]
  899. self.fill("elif ")
  900. self.traverse(node.test)
  901. with self.block():
  902. self.traverse(node.body)
  903. # final else
  904. if node.orelse:
  905. self.fill("else")
  906. with self.block():
  907. self.traverse(node.orelse)
  908. def visit_While(self, node):
  909. self.fill("while ")
  910. self.traverse(node.test)
  911. with self.block():
  912. self.traverse(node.body)
  913. if node.orelse:
  914. self.fill("else")
  915. with self.block():
  916. self.traverse(node.orelse)
  917. def visit_With(self, node):
  918. self.fill("with ")
  919. self.interleave(lambda: self.write(", "), self.traverse, node.items)
  920. with self.block(extra=self.get_type_comment(node)):
  921. self.traverse(node.body)
  922. def visit_AsyncWith(self, node):
  923. self.fill("async with ")
  924. self.interleave(lambda: self.write(", "), self.traverse, node.items)
  925. with self.block(extra=self.get_type_comment(node)):
  926. self.traverse(node.body)
  927. def _str_literal_helper(
  928. self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
  929. ):
  930. """Helper for writing string literals, minimizing escapes.
  931. Returns the tuple (string literal to write, possible quote types).
  932. """
  933. def escape_char(c):
  934. # \n and \t are non-printable, but we only escape them if
  935. # escape_special_whitespace is True
  936. if not escape_special_whitespace and c in "\n\t":
  937. return c
  938. # Always escape backslashes and other non-printable characters
  939. if c == "\\" or not c.isprintable():
  940. return c.encode("unicode_escape").decode("ascii")
  941. return c
  942. escaped_string = "".join(map(escape_char, string))
  943. possible_quotes = quote_types
  944. if "\n" in escaped_string:
  945. possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
  946. possible_quotes = [q for q in possible_quotes if q not in escaped_string]
  947. if not possible_quotes:
  948. # If there aren't any possible_quotes, fallback to using repr
  949. # on the original string. Try to use a quote from quote_types,
  950. # e.g., so that we use triple quotes for docstrings.
  951. string = repr(string)
  952. quote = next((q for q in quote_types if string[0] in q), string[0])
  953. return string[1:-1], [quote]
  954. if escaped_string:
  955. # Sort so that we prefer '''"''' over """\""""
  956. possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
  957. # If we're using triple quotes and we'd need to escape a final
  958. # quote, escape it
  959. if possible_quotes[0][0] == escaped_string[-1]:
  960. assert len(possible_quotes[0]) == 3
  961. escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
  962. return escaped_string, possible_quotes
  963. def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):
  964. """Write string literal value with a best effort attempt to avoid backslashes."""
  965. string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
  966. quote_type = quote_types[0]
  967. self.write(f"{quote_type}{string}{quote_type}")
  968. def visit_JoinedStr(self, node):
  969. self.write("f")
  970. if self._avoid_backslashes:
  971. self._fstring_JoinedStr(node, self.buffer_writer)
  972. self._write_str_avoiding_backslashes(self.buffer)
  973. return
  974. # If we don't need to avoid backslashes globally (i.e., we only need
  975. # to avoid them inside FormattedValues), it's cosmetically preferred
  976. # to use escaped whitespace. That is, it's preferred to use backslashes
  977. # for cases like: f"{x}\n". To accomplish this, we keep track of what
  978. # in our buffer corresponds to FormattedValues and what corresponds to
  979. # Constant parts of the f-string, and allow escapes accordingly.
  980. buffer = []
  981. for value in node.values:
  982. meth = getattr(self, "_fstring_" + type(value).__name__)
  983. meth(value, self.buffer_writer)
  984. buffer.append((self.buffer, isinstance(value, Constant)))
  985. new_buffer = []
  986. quote_types = _ALL_QUOTES
  987. for value, is_constant in buffer:
  988. # Repeatedly narrow down the list of possible quote_types
  989. value, quote_types = self._str_literal_helper(
  990. value, quote_types=quote_types,
  991. escape_special_whitespace=is_constant
  992. )
  993. new_buffer.append(value)
  994. value = "".join(new_buffer)
  995. quote_type = quote_types[0]
  996. self.write(f"{quote_type}{value}{quote_type}")
  997. def visit_FormattedValue(self, node):
  998. self.write("f")
  999. self._fstring_FormattedValue(node, self.buffer_writer)
  1000. self._write_str_avoiding_backslashes(self.buffer)
  1001. def _fstring_JoinedStr(self, node, write):
  1002. for value in node.values:
  1003. meth = getattr(self, "_fstring_" + type(value).__name__)
  1004. meth(value, write)
  1005. def _fstring_Constant(self, node, write):
  1006. if not isinstance(node.value, str):
  1007. raise ValueError("Constants inside JoinedStr should be a string.")
  1008. value = node.value.replace("{", "{{").replace("}", "}}")
  1009. write(value)
  1010. def _fstring_FormattedValue(self, node, write):
  1011. write("{")
  1012. unparser = type(self)(_avoid_backslashes=True)
  1013. unparser.set_precedence(_Precedence.TEST.next(), node.value)
  1014. expr = unparser.visit(node.value)
  1015. if expr.startswith("{"):
  1016. write(" ") # Separate pair of opening brackets as "{ {"
  1017. if "\\" in expr:
  1018. raise ValueError("Unable to avoid backslash in f-string expression part")
  1019. write(expr)
  1020. if node.conversion != -1:
  1021. conversion = chr(node.conversion)
  1022. if conversion not in "sra":
  1023. raise ValueError("Unknown f-string conversion.")
  1024. write(f"!{conversion}")
  1025. if node.format_spec:
  1026. write(":")
  1027. meth = getattr(self, "_fstring_" + type(node.format_spec).__name__)
  1028. meth(node.format_spec, write)
  1029. write("}")
  1030. def visit_Name(self, node):
  1031. self.write(node.id)
  1032. def _write_docstring(self, node):
  1033. self.fill()
  1034. if node.kind == "u":
  1035. self.write("u")
  1036. self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
  1037. def _write_constant(self, value):
  1038. if isinstance(value, (float, complex)):
  1039. # Substitute overflowing decimal literal for AST infinities,
  1040. # and inf - inf for NaNs.
  1041. self.write(
  1042. repr(value)
  1043. .replace("inf", _INFSTR)
  1044. .replace("nan", f"({_INFSTR}-{_INFSTR})")
  1045. )
  1046. elif self._avoid_backslashes and isinstance(value, str):
  1047. self._write_str_avoiding_backslashes(value)
  1048. else:
  1049. self.write(repr(value))
  1050. def visit_Constant(self, node):
  1051. value = node.value
  1052. if isinstance(value, tuple):
  1053. with self.delimit("(", ")"):
  1054. self.items_view(self._write_constant, value)
  1055. elif value is ...:
  1056. self.write("...")
  1057. else:
  1058. if node.kind == "u":
  1059. self.write("u")
  1060. self._write_constant(node.value)
  1061. def visit_List(self, node):
  1062. with self.delimit("[", "]"):
  1063. self.interleave(lambda: self.write(", "), self.traverse, node.elts)
  1064. def visit_ListComp(self, node):
  1065. with self.delimit("[", "]"):
  1066. self.traverse(node.elt)
  1067. for gen in node.generators:
  1068. self.traverse(gen)
  1069. def visit_GeneratorExp(self, node):
  1070. with self.delimit("(", ")"):
  1071. self.traverse(node.elt)
  1072. for gen in node.generators:
  1073. self.traverse(gen)
  1074. def visit_SetComp(self, node):
  1075. with self.delimit("{", "}"):
  1076. self.traverse(node.elt)
  1077. for gen in node.generators:
  1078. self.traverse(gen)
  1079. def visit_DictComp(self, node):
  1080. with self.delimit("{", "}"):
  1081. self.traverse(node.key)
  1082. self.write(": ")
  1083. self.traverse(node.value)
  1084. for gen in node.generators:
  1085. self.traverse(gen)
  1086. def visit_comprehension(self, node):
  1087. if node.is_async:
  1088. self.write(" async for ")
  1089. else:
  1090. self.write(" for ")
  1091. self.set_precedence(_Precedence.TUPLE, node.target)
  1092. self.traverse(node.target)
  1093. self.write(" in ")
  1094. self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)
  1095. self.traverse(node.iter)
  1096. for if_clause in node.ifs:
  1097. self.write(" if ")
  1098. self.traverse(if_clause)
  1099. def visit_IfExp(self, node):
  1100. with self.require_parens(_Precedence.TEST, node):
  1101. self.set_precedence(_Precedence.TEST.next(), node.body, node.test)
  1102. self.traverse(node.body)
  1103. self.write(" if ")
  1104. self.traverse(node.test)
  1105. self.write(" else ")
  1106. self.set_precedence(_Precedence.TEST, node.orelse)
  1107. self.traverse(node.orelse)
  1108. def visit_Set(self, node):
  1109. if node.elts:
  1110. with self.delimit("{", "}"):
  1111. self.interleave(lambda: self.write(", "), self.traverse, node.elts)
  1112. else:
  1113. # `{}` would be interpreted as a dictionary literal, and
  1114. # `set` might be shadowed. Thus:
  1115. self.write('{*()}')
  1116. def visit_Dict(self, node):
  1117. def write_key_value_pair(k, v):
  1118. self.traverse(k)
  1119. self.write(": ")
  1120. self.traverse(v)
  1121. def write_item(item):
  1122. k, v = item
  1123. if k is None:
  1124. # for dictionary unpacking operator in dicts {**{'y': 2}}
  1125. # see PEP 448 for details
  1126. self.write("**")
  1127. self.set_precedence(_Precedence.EXPR, v)
  1128. self.traverse(v)
  1129. else:
  1130. write_key_value_pair(k, v)
  1131. with self.delimit("{", "}"):
  1132. self.interleave(
  1133. lambda: self.write(", "), write_item, zip(node.keys, node.values)
  1134. )
  1135. def visit_Tuple(self, node):
  1136. with self.delimit("(", ")"):
  1137. self.items_view(self.traverse, node.elts)
  1138. unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
  1139. unop_precedence = {
  1140. "not": _Precedence.NOT,
  1141. "~": _Precedence.FACTOR,
  1142. "+": _Precedence.FACTOR,
  1143. "-": _Precedence.FACTOR,
  1144. }
  1145. def visit_UnaryOp(self, node):
  1146. operator = self.unop[node.op.__class__.__name__]
  1147. operator_precedence = self.unop_precedence[operator]
  1148. with self.require_parens(operator_precedence, node):
  1149. self.write(operator)
  1150. # factor prefixes (+, -, ~) shouldn't be seperated
  1151. # from the value they belong, (e.g: +1 instead of + 1)
  1152. if operator_precedence is not _Precedence.FACTOR:
  1153. self.write(" ")
  1154. self.set_precedence(operator_precedence, node.operand)
  1155. self.traverse(node.operand)
  1156. binop = {
  1157. "Add": "+",
  1158. "Sub": "-",
  1159. "Mult": "*",
  1160. "MatMult": "@",
  1161. "Div": "/",
  1162. "Mod": "%",
  1163. "LShift": "<<",
  1164. "RShift": ">>",
  1165. "BitOr": "|",
  1166. "BitXor": "^",
  1167. "BitAnd": "&",
  1168. "FloorDiv": "//",
  1169. "Pow": "**",
  1170. }
  1171. binop_precedence = {
  1172. "+": _Precedence.ARITH,
  1173. "-": _Precedence.ARITH,
  1174. "*": _Precedence.TERM,
  1175. "@": _Precedence.TERM,
  1176. "/": _Precedence.TERM,
  1177. "%": _Precedence.TERM,
  1178. "<<": _Precedence.SHIFT,
  1179. ">>": _Precedence.SHIFT,
  1180. "|": _Precedence.BOR,
  1181. "^": _Precedence.BXOR,
  1182. "&": _Precedence.BAND,
  1183. "//": _Precedence.TERM,
  1184. "**": _Precedence.POWER,
  1185. }
  1186. binop_rassoc = frozenset(("**",))
  1187. def visit_BinOp(self, node):
  1188. operator = self.binop[node.op.__class__.__name__]
  1189. operator_precedence = self.binop_precedence[operator]
  1190. with self.require_parens(operator_precedence, node):
  1191. if operator in self.binop_rassoc:
  1192. left_precedence = operator_precedence.next()
  1193. right_precedence = operator_precedence
  1194. else:
  1195. left_precedence = operator_precedence
  1196. right_precedence = operator_precedence.next()
  1197. self.set_precedence(left_precedence, node.left)
  1198. self.traverse(node.left)
  1199. self.write(f" {operator} ")
  1200. self.set_precedence(right_precedence, node.right)
  1201. self.traverse(node.right)
  1202. cmpops = {
  1203. "Eq": "==",
  1204. "NotEq": "!=",
  1205. "Lt": "<",
  1206. "LtE": "<=",
  1207. "Gt": ">",
  1208. "GtE": ">=",
  1209. "Is": "is",
  1210. "IsNot": "is not",
  1211. "In": "in",
  1212. "NotIn": "not in",
  1213. }
  1214. def visit_Compare(self, node):
  1215. with self.require_parens(_Precedence.CMP, node):
  1216. self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)
  1217. self.traverse(node.left)
  1218. for o, e in zip(node.ops, node.comparators):
  1219. self.write(" " + self.cmpops[o.__class__.__name__] + " ")
  1220. self.traverse(e)
  1221. boolops = {"And": "and", "Or": "or"}
  1222. boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
  1223. def visit_BoolOp(self, node):
  1224. operator = self.boolops[node.op.__class__.__name__]
  1225. operator_precedence = self.boolop_precedence[operator]
  1226. def increasing_level_traverse(node):
  1227. nonlocal operator_precedence
  1228. operator_precedence = operator_precedence.next()
  1229. self.set_precedence(operator_precedence, node)
  1230. self.traverse(node)
  1231. with self.require_parens(operator_precedence, node):
  1232. s = f" {operator} "
  1233. self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
  1234. def visit_Attribute(self, node):
  1235. self.set_precedence(_Precedence.ATOM, node.value)
  1236. self.traverse(node.value)
  1237. # Special case: 3.__abs__() is a syntax error, so if node.value
  1238. # is an integer literal then we need to either parenthesize
  1239. # it or add an extra space to get 3 .__abs__().
  1240. if isinstance(node.value, Constant) and isinstance(node.value.value, int):
  1241. self.write(" ")
  1242. self.write(".")
  1243. self.write(node.attr)
  1244. def visit_Call(self, node):
  1245. self.set_precedence(_Precedence.ATOM, node.func)
  1246. self.traverse(node.func)
  1247. with self.delimit("(", ")"):
  1248. comma = False
  1249. for e in node.args:
  1250. if comma:
  1251. self.write(", ")
  1252. else:
  1253. comma = True
  1254. self.traverse(e)
  1255. for e in node.keywords:
  1256. if comma:
  1257. self.write(", ")
  1258. else:
  1259. comma = True
  1260. self.traverse(e)
  1261. def visit_Subscript(self, node):
  1262. def is_simple_tuple(slice_value):
  1263. # when unparsing a non-empty tuple, the parentheses can be safely
  1264. # omitted if there aren't any elements that explicitly requires
  1265. # parentheses (such as starred expressions).
  1266. return (
  1267. isinstance(slice_value, Tuple)
  1268. and slice_value.elts
  1269. and not any(isinstance(elt, Starred) for elt in slice_value.elts)
  1270. )
  1271. self.set_precedence(_Precedence.ATOM, node.value)
  1272. self.traverse(node.value)
  1273. with self.delimit("[", "]"):
  1274. if is_simple_tuple(node.slice):
  1275. self.items_view(self.traverse, node.slice.elts)
  1276. else:
  1277. self.traverse(node.slice)
  1278. def visit_Starred(self, node):
  1279. self.write("*")
  1280. self.set_precedence(_Precedence.EXPR, node.value)
  1281. self.traverse(node.value)
  1282. def visit_Ellipsis(self, node):
  1283. self.write("...")
  1284. def visit_Slice(self, node):
  1285. if node.lower:
  1286. self.traverse(node.lower)
  1287. self.write(":")
  1288. if node.upper:
  1289. self.traverse(node.upper)
  1290. if node.step:
  1291. self.write(":")
  1292. self.traverse(node.step)
  1293. def visit_Match(self, node):
  1294. self.fill("match ")
  1295. self.traverse(node.subject)
  1296. with self.block():
  1297. for case in node.cases:
  1298. self.traverse(case)
  1299. def visit_arg(self, node):
  1300. self.write(node.arg)
  1301. if node.annotation:
  1302. self.write(": ")
  1303. self.traverse(node.annotation)
  1304. def visit_arguments(self, node):
  1305. first = True
  1306. # normal arguments
  1307. all_args = node.posonlyargs + node.args
  1308. defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
  1309. for index, elements in enumerate(zip(all_args, defaults), 1):
  1310. a, d = elements
  1311. if first:
  1312. first = False
  1313. else:
  1314. self.write(", ")
  1315. self.traverse(a)
  1316. if d:
  1317. self.write("=")
  1318. self.traverse(d)
  1319. if index == len(node.posonlyargs):
  1320. self.write(", /")
  1321. # varargs, or bare '*' if no varargs but keyword-only arguments present
  1322. if node.vararg or node.kwonlyargs:
  1323. if first:
  1324. first = False
  1325. else:
  1326. self.write(", ")
  1327. self.write("*")
  1328. if node.vararg:
  1329. self.write(node.vararg.arg)
  1330. if node.vararg.annotation:
  1331. self.write(": ")
  1332. self.traverse(node.vararg.annotation)
  1333. # keyword-only arguments
  1334. if node.kwonlyargs:
  1335. for a, d in zip(node.kwonlyargs, node.kw_defaults):
  1336. self.write(", ")
  1337. self.traverse(a)
  1338. if d:
  1339. self.write("=")
  1340. self.traverse(d)
  1341. # kwargs
  1342. if node.kwarg:
  1343. if first:
  1344. first = False
  1345. else:
  1346. self.write(", ")
  1347. self.write("**" + node.kwarg.arg)
  1348. if node.kwarg.annotation:
  1349. self.write(": ")
  1350. self.traverse(node.kwarg.annotation)
  1351. def visit_keyword(self, node):
  1352. if node.arg is None:
  1353. self.write("**")
  1354. else:
  1355. self.write(node.arg)
  1356. self.write("=")
  1357. self.traverse(node.value)
  1358. def visit_Lambda(self, node):
  1359. with self.require_parens(_Precedence.TEST, node):
  1360. self.write("lambda ")
  1361. self.traverse(node.args)
  1362. self.write(": ")
  1363. self.set_precedence(_Precedence.TEST, node.body)
  1364. self.traverse(node.body)
  1365. def visit_alias(self, node):
  1366. self.write(node.name)
  1367. if node.asname:
  1368. self.write(" as " + node.asname)
  1369. def visit_withitem(self, node):
  1370. self.traverse(node.context_expr)
  1371. if node.optional_vars:
  1372. self.write(" as ")
  1373. self.traverse(node.optional_vars)
  1374. def visit_match_case(self, node):
  1375. self.fill("case ")
  1376. self.traverse(node.pattern)
  1377. if node.guard:
  1378. self.write(" if ")
  1379. self.traverse(node.guard)
  1380. with self.block():
  1381. self.traverse(node.body)
  1382. def visit_MatchValue(self, node):
  1383. self.traverse(node.value)
  1384. def visit_MatchSingleton(self, node):
  1385. self._write_constant(node.value)
  1386. def visit_MatchSequence(self, node):
  1387. with self.delimit("[", "]"):
  1388. self.interleave(
  1389. lambda: self.write(", "), self.traverse, node.patterns
  1390. )
  1391. def visit_MatchStar(self, node):
  1392. name = node.name
  1393. if name is None:
  1394. name = "_"
  1395. self.write(f"*{name}")
  1396. def visit_MatchMapping(self, node):
  1397. def write_key_pattern_pair(pair):
  1398. k, p = pair
  1399. self.traverse(k)
  1400. self.write(": ")
  1401. self.traverse(p)
  1402. with self.delimit("{", "}"):
  1403. keys = node.keys
  1404. self.interleave(
  1405. lambda: self.write(", "),
  1406. write_key_pattern_pair,
  1407. zip(keys, node.patterns, strict=True),
  1408. )
  1409. rest = node.rest
  1410. if rest is not None:
  1411. if keys:
  1412. self.write(", ")
  1413. self.write(f"**{rest}")
  1414. def visit_MatchClass(self, node):
  1415. self.set_precedence(_Precedence.ATOM, node.cls)
  1416. self.traverse(node.cls)
  1417. with self.delimit("(", ")"):
  1418. patterns = node.patterns
  1419. self.interleave(
  1420. lambda: self.write(", "), self.traverse, patterns
  1421. )
  1422. attrs = node.kwd_attrs
  1423. if attrs:
  1424. def write_attr_pattern(pair):
  1425. attr, pattern = pair
  1426. self.write(f"{attr}=")
  1427. self.traverse(pattern)
  1428. if patterns:
  1429. self.write(", ")
  1430. self.interleave(
  1431. lambda: self.write(", "),
  1432. write_attr_pattern,
  1433. zip(attrs, node.kwd_patterns, strict=True),
  1434. )
  1435. def visit_MatchAs(self, node):
  1436. name = node.name
  1437. pattern = node.pattern
  1438. if name is None:
  1439. self.write("_")
  1440. elif pattern is None:
  1441. self.write(node.name)
  1442. else:
  1443. with self.require_parens(_Precedence.TEST, node):
  1444. self.set_precedence(_Precedence.BOR, node.pattern)
  1445. self.traverse(node.pattern)
  1446. self.write(f" as {node.name}")
  1447. def visit_MatchOr(self, node):
  1448. with self.require_parens(_Precedence.BOR, node):
  1449. self.set_precedence(_Precedence.BOR.next(), *node.patterns)
  1450. self.interleave(lambda: self.write(" | "), self.traverse, node.patterns)
  1451. def unparse(ast_obj):
  1452. unparser = _Unparser()
  1453. return unparser.visit(ast_obj)
  1454. def main():
  1455. import argparse
  1456. parser = argparse.ArgumentParser(prog='python -m ast')
  1457. parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
  1458. default='-',
  1459. help='the file to parse; defaults to stdin')
  1460. parser.add_argument('-m', '--mode', default='exec',
  1461. choices=('exec', 'single', 'eval', 'func_type'),
  1462. help='specify what kind of code must be parsed')
  1463. parser.add_argument('--no-type-comments', default=True, action='store_false',
  1464. help="don't add information about type comments")
  1465. parser.add_argument('-a', '--include-attributes', action='store_true',
  1466. help='include attributes such as line numbers and '
  1467. 'column offsets')
  1468. parser.add_argument('-i', '--indent', type=int, default=3,
  1469. help='indentation of nodes (number of spaces)')
  1470. args = parser.parse_args()
  1471. with args.infile as infile:
  1472. source = infile.read()
  1473. tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
  1474. print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
  1475. if __name__ == '__main__':
  1476. main()