ast.py 59 KB

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