a DOg@sdZddlZddlTddlmZmZddlmZmZd`ddd d d Z d d Z daddddZ ddZ ddZ dbddZddZddZdcddZdd Zd!d"Zdd#d$d%Zd&d'ZGd(d)d)eZGd*d+d+eZeed,s d-d.Zd/d0Zeeee_eeee_Gd1d2d2e Z!d3d4Z"Gd5d6d6ee!d7Z#Gd8d9d9ee!d7Z$Gd:d;d;ee!d7Z%Gdd?d?ee!d7Z'e#e(e)e*fe$e+fe%e,fe&e de-fe'e d@fiZ.e#e-fiZ/e-d=e dd=e(d6e)d6e*d6e+d9e,d;e d@d?iZ0GdAdBdBe1Z2GdCdDdDe2Z3GdEdFdFe2Z4ee5dGsFdHdIZ6dJdKZ7ee6e7e5_8GdLdMdMe9Z:GdNdOdOe;ZdTe?ej@jAdZBGdUdVdVeZCdWZDdXZEgeDeERZFGdYdZdZeZGd[d\ZHd]d^ZIeJd_kreIdS)daH ast ~~~ The `ast` module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like and allows modifications of it. An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as a flag to the `compile()` builtin function or by using the `parse()` function from this module. The result will be a tree of objects whose classes all inherit from `ast.AST`. A modified abstract syntax tree can be compiled into a Python code object using the built-in `compile()` function. Additionally various helper functions are provided that make working with the trees simpler. The main intention of the helper functions and this module in general is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example). :copyright: Copyright 2008 by Armin Ronacher. :license: Python License. N)*)contextmanager nullcontext)IntEnumauto execF) type_commentsfeature_versioncCsRt}|r|tO}t|tr4|\}}|dks.J|}n |dur@d}t|||||dS)z Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). Pass type_comments=True to get back type comments where the syntax allows. N)_feature_version)Z PyCF_ONLY_ASTZPyCF_TYPE_COMMENTS isinstancetuplecompile)sourcefilenamemoder r flagsmajorminorr(/opt/alt/python39/lib64/python3.9/ast.pyparse!s   rcs`t|trt|dd}t|tr&|j}ddfddfddfd d |S) aT Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. Caution: A complex expression can overflow the C stack and cause a crash. evalrcSstd|dS)Nzmalformed node or string: ) ValueErrornoderrr_raise_malformed_nodeCsz+literal_eval.._raise_malformed_nodecs,t|trt|jtttfvr&||jSN)rConstanttypevalueintfloatcomplexr)rrr _convert_numEsz"literal_eval.._convert_numcsDt|tr._convert_signed_numcsZt|tr|jSt|tr*tt|jSt|trDtt|jSt|t r^t t|jSt|t rt|j t r|j jdkr|j|jkrgkrnnt St|trt|jt|jkrȈ|ttt|jt|jSt|trRt|jttfrR|j}|j}t|ttfrRt|trRt|jtrJ||S||S|S)Nset) rr!r#TuplermapeltsListlistSetr-ZCallfuncNameidargskeywordsDictlenkeysvaluesdictzipZBinOpr(AddSubleftrightr$r%r&)rrArB_convertr'r,rrrrDQs<          zliteral_eval.._convert)rstrrZ Expressionbody)Znode_or_stringrrCr literal_eval6s     rGT)indentcsTdfdd t|ts.td|jjdurHttsHd|dS)a Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true. If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. None (the default) selects the single line representation. rc sdur*d7d}d}nd}d}t|trt|}g}d}}|jD]}zt||} Wntyd}YqXYn0| durt||ddurd}qX| \} } |o| }|r|d|| fqX|| qXrh|jrh|jD]t}zt||} WntyYqYn0| durz(dump.._format..)rASTr"_fieldsgetattrAttributeErrorappend _attributesr: __class____name__joinr2repr) rrQprefixsepclsr7Z allsimpler8namer#simplerPannotate_fieldsinclude_attributesrH)rQrrPzsX          &zdump.._formatzexpected AST, got %rN )r)rrT TypeErrorrZr[rE)rrdrerHrrcrdumpns 0 rhcCsVdD]L}||jvr||jvrt||d}|dusDt||r|drt|||q|S)z Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. )lineno col_offset end_linenoend_col_offsetNZend_)rYrVhasattr startswithsetattr)new_nodeZold_nodeattrr#rrr copy_locations rrcs fdd|dddd|S)a{ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. csd|jvr"t|ds||_n|j}d|jvrJt|dddurD||_n|j}d|jvrlt|dsf||_n|j}d|jvrt|dddur||_n|j}t|D]}|||||qdS)Nrirkrjrl)rYrmrirVrkrjrliter_child_nodes)rrirjrkrlchild_fixrrrvs$       z#fix_missing_locations.._fixrIrrrrrurfix_missing_locationss rwrIcCsVt|D]H}d|jvr(t|dd||_d|jvrt|dd}dur|||_q|S)z Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. rirrkN)walkrYrVrirk)rnrtrkrrrincrement_linenos   rzc cs8|jD],}z|t||fVWqty0Yq0qdS)zs Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. N)rUrVrW)rfieldrrr iter_fieldss   r|ccsLt|D]>\}}t|tr"|Vqt|tr|D]}t|tr0|Vq0qdS)z Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. N)r|rrTr2)rrar{itemrrrrss   rscCst|ttttfs"td|jj|jr8t|jdt s|jdus|jdurWdS|jd}|jd}|j}|j}WntyRYdS0t|}||kr|||||S|rt||d|}nd}||||d} ||d|} ||d|}| d| | | d |S)aBGet source code segment of the *source* that generated *node*. If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return None. If *padded* is `True`, the first line of a multi-line statement will be padded with spaces to match its original position. NrIrKr) rkrlrirjrWrencodedecoderinsertrXr\) rrrrirkrjrlrZpaddingfirstZlastrrrget_source_segmentNs*       rccs<ddlm}||g}|r8|}|t||VqdS)z Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. r)dequeN) collectionsrpopleftextendrs)rrZtodorrrrxss   rxc@s(eZdZdZddZddZddZdS) NodeVisitora< A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default the visitor functions for the nodes are ``'visit_'`` + class name of the node. So a `TryFinally` node visit function would be `visit_TryFinally`. This behavior can be changed by overriding the `visit` method. If no visitor function exists for a node (return value `None`) the `generic_visit` visitor is used instead. Don't use the `NodeVisitor` if you want to apply changes to nodes during traversing. For this a special visitor exists (`NodeTransformer`) that allows modifications. cCs"d|jj}t|||j}||S)z Visit a node.visit_)rZr[rV generic_visit)selfrmethodvisitorrrrvisits zNodeVisitor.visitcCsTt|D]F\}}t|tr:|D]}t|tr||qqt|tr||qdS)z9Called if no explicit visitor function exists for a node.N)r|rr2rTr)rrr{r#r}rrrrs   zNodeVisitor.generic_visitc Cs|j}tt|}|dur@tD]\}}t||r$|}q@q$|durd|}zt||}WntypYn&0ddl}| |dt d||S| |S)Nrrz" is deprecated; add visit_Constant) r#_const_node_type_namesgetr"itemsrrVrWwarningswarnDeprecationWarningr) rrr#Z type_namer`rarrrrrrvisit_Constants&   zNodeVisitor.visit_ConstantN)r[ __module__ __qualname____doc__rrrrrrrrs rc@seZdZdZddZdS)NodeTransformeraC A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place. Here is an example transformer that rewrites all occurrences of name lookups (``foo``) to ``data['foo']``:: class RewriteName(NodeTransformer): def visit_Name(self, node): return Subscript( value=Name(id='data', ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx ) Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the :meth:`generic_visit` method for the node first. For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node. Usually you use the transformer like this:: node = YourTransformer().visit(node) cCst|D]\}}t|trvg}|D]D}t|tr\||}|durFq"nt|ts\||q"||q"||dd<qt|tr||}|durt||qt|||q|Sr ) r|rr2rTrrrXdelattrro)rrr{ old_valueZ new_valuesr#rprrrrs&         zNodeTransformer.generic_visitN)r[rrrrrrrrrs#rrycCs|jS)zDeprecated. Use value instead.r#rrrr_gettersrcCs ||_dSr rrr#rrr_settersrc@seZdZddZddZdS)_ABCcGs d|_dS)Nz3Deprecated AST node class. Use ast.Constant instead)r)r`r7rrr__init__sz _ABC.__init__cCsdt|tsdS|tvrXz |j}Wnty4YdS0t|t|oVt|t|d St||S)NFr) rr! _const_typesr#rW_const_types_notrr"__instancecheck__)r`instr#rrrr s   z_ABC.__instancecheck__N)r[rrrrrrrrrsrcOsp|D]<}||jvrq|j|}|t|krt|jd|q|tvrXt|i|Stj|g|Ri|S)Nz" got multiple values for argument )rUindexr:rgr[rr!__new__)r`r7kwargskeyposrrr_news   rc@seZdZdZeZdS)Num)ryNr[rrrUrrrrrrr%sr) metaclassc@seZdZdZeZdS)rrNrrrrrr)src@seZdZdZeZdS)BytesrNrrrrrr-src@seZdZeZdS) NameConstantN)r[rrrrrrrrr1src@seZdZdZddZdS)EllipsisrcOs6|turtdg|Ri|Stj|g|Ri|S)N.)rr!r)r`r7rrrrr7szEllipsis.__new__N)r[rrrUrrrrrr4sr.c@seZdZdZdS)slicezDeprecated AST node class.Nr[rrrrrrrrRsrc@seZdZdZddZdS)Indexz@Deprecated AST node class. Use the index value directly instead.cKs|Sr r)r`r#rrrrrWsz Index.__new__Nr[rrrrrrrrrUsrc@seZdZdZdddZdS)ExtSlicez1Deprecated AST node class. Use ast.Tuple instead.rcKstt|tfi|Sr )r.r2ZLoad)r`dimsrrrrr\szExtSlice.__new__N)rrrrrrrZsrrcCs|jS)zDeprecated. Use elts instead.r0rrrr _dims_getterdsrcCs ||_dSr rrrrr _dims_setterhsrc@seZdZdZdS)Suite/Deprecated AST node class. Unused in Python 3.Nrrrrrrmsrc@seZdZdZdS)AugLoadrNrrrrrrpsrc@seZdZdZdS)AugStorerNrrrrrrssrc@seZdZdZdS)ParamrNrrrrrrvsrZ1ec@seZdZdZeZeZeZeZeZ eZ eZ eZ e Z eZeZeZeZeZeZeZeZeZddZdS) _Precedencez5Precedence table that originated from python grammar.cCs,z||dWSty&|YS0dSNrI)rZrrrrrnexts z_Precedence.nextN)r[rrrrTUPLEYIELDTESTORANDNOTCMPEXPRBORBXORBANDSHIFTARITHTERMFACTORPOWERAWAITATOMrrrrrr~s(r)'")z"""z'''cseZdZdZddddZddZdd Zd d Zdd dZddZ ddZ e ddZ e ddddZe ddZddZddZdd Zd!d"Zd#d$Zd%d&Zfd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:Zd;d<Z d=d>Z!d?d@Z"dAdBZ#dCdDZ$dEdFZ%dGdHZ&dIdJZ'dKdLZ(dMdNZ)dOdPZ*dQdRZ+dSdTZ,dUdVZ-dWdXZ.dYdZZ/d[d\Z0d]d^Z1d_d`Z2dadbZ3dcddZ4dedfZ5dgdhZ6didjZ7dkdlZ8dmdnZ9dodpZ:e;ddqdrdsZdydzZ?d{d|Z@d}d~ZAddZBddZCddZDddZEddZFddZGddZHddZIddZJddZKddZLddZMddZNddZOddZPdddddZQeRjSeRjTeRjTeRjTdZUddZVdddddddddddddd ZWeRjXeRjXeRjYeRjYeRjYeRjYeRjZeRjZeRj[eRj\eRj]eRjYeRj^d Z_e`dZaddZbddddddddddd ZcddZddddĜZeeRjfeRjgdŜZhddDŽZiddɄZjdd˄Zkdd̈́ZlddτZmddфZnddӄZoddՄZpddׄZqddلZrddۄZsdd݄Ztdd߄ZuZvS) _UnparserzMethods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.F_avoid_backslashescCs(g|_g|_i|_i|_d|_||_dS)Nr)_source_buffer _precedences _type_ignores_indentr)rrrrrrs z_Unparser.__init__cCsHt|}z|t|Wnty*Yn0|D]}|||q0dS)z7Call f on each item in seq, calling inter() in between.N)iterr StopIteration)rZinterfseqrOrrr interleaves z_Unparser.interleavecs>t|dkr$||ddnfdd||dS)zTraverse and separate the given *items* with a comma and append it to the buffer. If *items* is a single item sequence, a trailing comma will be added.rIr,cs dSNrLwriterrrrrSz&_Unparser.items_view..N)r:rr)rZ traverserrrrr items_views   z_Unparser.items_viewcCs|jr|ddS)z8Adds a newline if it isn't the start of generated sourcerJN)rrrrrr maybe_newlinesz_Unparser.maybe_newlinerKcCs ||d|j|dS)zXIndent a piece of text and append it, according to the current indentation levelz N)rrrrrrrrfillsz_Unparser.fillcCs|j|dS)zAppend a piece of textN)rrXrrrrrsz_Unparser.writecCs|j|dSr )rrXrrrr buffer_writersz_Unparser.buffer_writercCsd|j}|j|S)NrK)r\rclearrrrrbuffers  z_Unparser.bufferNextraccs>|d|r|||jd7_dV|jd8_dS)aA context manager for preparing the source for blocks. It adds the character':', increases the indentation on enter and decreases the indentation on exit. If *extra* is given, it will be directly appended after the colon character. :rIN)rr)rrrrrblocks   z_Unparser.blockccs||dV||dS)zA context manager for preparing the source for expressions. It adds *start* to the buffer and enters, after exit it adds *end*.Nr)rstartendrrrdelimits z_Unparser.delimitcCs|r|||StSdSr )r r)rrr  conditionrrr delimit_ifs z_Unparser.delimit_ifcCs|dd|||kS)z,Shortcut to adding precedence related parens())r get_precedence)r precedencerrrrrequire_parenssz_Unparser.require_parenscCs|j|tjSr )rrrrrrrrrrsz_Unparser.get_precedencecGs|D]}||j|<qdSr )r)rrZnodesrrrrset_precedencesz_Unparser.set_precedencecCs`t|ttttfr t|jdkr$dS|jd}t|ts||}r.||||jddn ||jdSr)r_write_docstringrrF)rrZ docstringrrr"_write_docstring_and_traverse_body&s z,_Unparser._write_docstring_and_traverse_bodycCs*dd|jD|_|||jdS)NcSsi|]}|jd|jqS)ignore)ritag)rNrrrr .sz*_Unparser.visit_Module..) type_ignoresrrrrrrr visit_Module-s  z_Unparser.visit_Modulecs`dd*fddj|jWdn1s<0Yd|jdS)Nr rcs dSrrrrrrr8rSz._Unparser.visit_FunctionType.. -> )r rrargtypesrreturnsrrrrvisit_FunctionType5s " z_Unparser.visit_FunctionTypecCs(||tj|j||jdSr )rrrrr#rrrrr visit_Expr>sz_Unparser.visit_ExprcCsh|tj|F|tj|j|j||j|d||jWdn1sZ0YdS)Nz := ) rrrrrtargetr#rrrrrrvisit_NamedExprCs   z_Unparser.visit_NamedExprcs(dfddj|jdS)Nzimport cs dSrrrrrrrLrSz(_Unparser.visit_Import..)rrrnamesrrrr visit_ImportJs z_Unparser.visit_ImportcsTdd|j|jr,|jdfddj|jdS)Nzfrom .z import cs dSrrrrrrrTrSz,_Unparser.visit_ImportFrom..)rrrQmodulerrr(rrrrvisit_ImportFromNs    z_Unparser.visit_ImportFromcCsP||jD]}|||dq||j||}rL||dS)N = )rtargetsrrr#r)rrr&rrrr visit_AssignVs    z_Unparser.visit_AssigncCsB|||j|d|j|jjjd||jdS)Nrfz= ) rrr&rbinopr(rZr[r#rrrrvisit_AugAssign_s z_Unparser.visit_AugAssigncCs||dd|j o"t|jt||jWdn1sH0Y|d||j|j r|d||j dS)Nr r: r-) rr rbrr&r5rr annotationr#rrrrvisit_AnnAssignes *   z_Unparser.visit_AnnAssigncCs*|d|jr&|d||jdS)Nreturnrf)rr#rrrrrr visit_Returnos  z_Unparser.visit_ReturncCs|ddS)Npassrrrrr visit_Passusz_Unparser.visit_PasscCs|ddS)Nbreakr8rrrr visit_Breakxsz_Unparser.visit_BreakcCs|ddS)Ncontinuer8rrrrvisit_Continue{sz_Unparser.visit_Continuecs(dfddj|jdS)Nzdel cs dSrrrrrrrrSz(_Unparser.visit_Delete..)rrrr.rrrr visit_Delete~s z_Unparser.visit_DeletecCs6|d||j|jr2|d||jdS)Nzassert rL)rrtestmsgrrrrr visit_Asserts    z_Unparser.visit_Assertcs(dfddj|jdS)Nzglobal cs dSrrrrrrrrSz(_Unparser.visit_Global..rrrr(rrrr visit_Globals z_Unparser.visit_Globalcs(dfddj|jdS)Nz nonlocal cs dSrrrrrrrrSz*_Unparser.visit_Nonlocal..rBrrrrvisit_Nonlocals z_Unparser.visit_NonlocalcCsh|tj|F|d|jrF|d|tj|j||jWdn1sZ0YdS)Nawaitrf)rrrrr#rrrrrrr visit_Awaits   z_Unparser.visit_AwaitcCsh|tj|F|d|jrF|d|tj|j||jWdn1sZ0YdS)Nyieldrf)rrrrr#rrrrrrr visit_Yields   z_Unparser.visit_YieldcCsf|tj|D|d|js(td|tj|j||jWdn1sX0YdS)Nz yield from z-Node can't be used without a value attribute.) rrrrr#rrrrrrrrvisit_YieldFroms  z_Unparser.visit_YieldFromcCsX|d|js"|jrtddS|d||j|jrT|d||jdS)Nraisez*Node can't use cause without an exception.rfz from )rexccauserrrrrrr visit_Raises    z_Unparser.visit_RaisecCs|d|||jWdn1s40Y|jD]}||qD|jr|d|||jWdn1s0Y|jr|d|||jWdn1s0YdS)Ntryelsefinally)rrrrFhandlersorelse finalbody)rrZexrrr visit_Trys  *    *  z_Unparser.visit_TrycCsz|d|jr&|d||j|jrB|d||j|||jWdn1sl0YdS)Nexceptrf as )rr"rrrarrFrrrrvisit_ExceptHandlers      z_Unparser.visit_ExceptHandlercCs||jD]}|d||q|d|j|jdd|jpJ|jdhd}|jD]"}|rp|dnd}||q\|jD]"}|r|dnd}||qWdn1s0Y| | |Wdn1s0YdS) N@zclass r r)r FrLT) rdecorator_listrrrar basesr8rrr)rrdecocommaerrrvisit_ClassDefs&        * z_Unparser.visit_ClassDefcCs||ddS)Ndef_function_helperrrrrvisit_FunctionDefsz_Unparser.visit_FunctionDefcCs||ddS)Nz async defr`rrrrvisit_AsyncFunctionDefsz _Unparser.visit_AsyncFunctionDefcCs||jD]}|d||q|d|j}|||dd||jWdn1sn0Y|jr|d||j|j | |d| |Wdn1s0YdS)NrXrfr rr!r) rrYrrrar r7r#rrrr)rrZ fill_suffixr[Zdef_strrrrras    *  z_Unparser._function_helpercCs|d|dS)Nzfor  _for_helperrrrr visit_Forsz_Unparser.visit_ForcCs|d|dS)Nz async for rdrrrrvisit_AsyncForsz_Unparser.visit_AsyncForcCs||||j|d||j|j||d||jWdn1s`0Y|jr|d|||jWdn1s0YdS)N in rrO) rrr&rrrrrFrR)rrrrrrres    *  z_Unparser._for_helpercCs|d||j|||jWdn1s@0Y|jrt|jdkrt|jdtr|jd}|d||j|||jWdqJ1s0YqJ|jr |d|||jWdn1s0YdS)Nzif rIrzelif rO) rrr?rrFrRr:rZIfrrrrvisit_Ifs   *$    ,  z_Unparser.visit_IfcCs|d||j|||jWdn1s@0Y|jr|d|||jWdn1s0YdS)Nzwhile rO)rrr?rrFrRrrrr visit_While s   *  z_Unparser.visit_Whilecsfdfddj|jj|d|jWdn1sX0YdS)Nzwith cs dSrrrrrrr,rSz&_Unparser.visit_With..rrrrrrrrFrrrr visit_With*s z_Unparser.visit_Withcsfdfddj|jj|d|jWdn1sX0YdS)Nz async with cs dSrrrrrrr2rSz+_Unparser.visit_AsyncWith..rrkrrrrvisit_AsyncWith0s z_Unparser.visit_AsyncWith quote_typesescape_special_whitespacecsfdd}dt||}dvr6dd|D}fdd|D}|sttfdd |Dd }d d |gfSr|jfd dd|d d d krt|d dksJdd dd |fS)zHelper for writing string literals, minimizing escapes. Returns the tuple (string literal to write, possible quote types). cs4s|dvr|S|dks |s0|ddS|S)Nz \Zunicode_escapeascii) isprintablerr)r)rprr escape_char<s  z2_Unparser._str_literal_helper..escape_charrKrJcSsg|]}|tvr|qSr) _MULTI_QUOTESrNqrrr IrSz1_Unparser._str_literal_helper..csg|]}|vr|qSrrrvescaped_stringrrrxJrSc3s|]}d|vr|VqdSrMrrv)stringrrrRPrSz0_Unparser._str_literal_helper..rrIr cs|ddkS)Nrr r)rwryrrrTrSz/_Unparser._str_literal_helper..)rr Nrq)r\r/r]rsortr:)rr{rorprtZpossible_quotesZquoter)rprzr{r_str_literal_helper6s  z_Unparser._str_literal_helperrocCs4|j||d\}}|d}||||dS)zKWrite string literal value with a best effort attempt to avoid backslashes.r~rN)r}r)rr{ro quote_typerrr_write_str_avoiding_backslashes\sz)_Unparser._write_str_avoiding_backslashesc Cs|d|jr.|||j||jdSg}|jD]:}t|dt|j }|||j| |jt |t fq8g}t }|D]&\}}|j|||d\}}| |qd|}|d}||||dS)Nr _fstring_rnrKr)rr_fstring_JoinedStrrrrr<rVr"r[rXrr! _ALL_QUOTESr}r\) rrrr#methZ new_bufferroZ is_constantrrrrvisit_JoinedStrbs*        z_Unparser.visit_JoinedStrcCs(|d|||j||jdS)Nr)r_fstring_FormattedValuerrrrrrrvisit_FormattedValues z_Unparser.visit_FormattedValuecCs.|jD]"}t|dt|j}|||qdS)Nr)r<rVr"r[)rrrr#rrrrrs z_Unparser._fstring_JoinedStrcCs6t|jtstd|jdddd}||dS)Nz.Constants inside JoinedStr should be a string.{z{{}z}})rr#rErreplace)rrrr#rrr_fstring_Constants z_Unparser._fstring_ConstantcCs|dt|dd}|tj|j||j}|drH|dd|vrXtd|||j dkrt |j }|dvrtd |d ||j r|d t |d t|j j }||j ||d dS)NrTrrfrqz5Unable to avoid backslash in f-string expression partr ZsrazUnknown f-string conversion.!rrr)r"rrrrr#rrnr conversionchr format_specrVr[)rrrunparserexprrrrrrrs&     z!_Unparser._fstring_FormattedValuecCs||jdSr )rr6rrrr visit_Namesz_Unparser.visit_NamecCs0||jdkr|d|j|jtddS)Nur~)rkindrrr#rurrrrrs  z_Unparser._write_docstringc Csjt|ttfr<|t|dtddtdtdn*|jrXt|trX| |n|t|dS)Ninfnanr -r) rr%r&rr]r_INFSTRrrErrrrr_write_constants z_Unparser._write_constantcCs|j}t|trL|dd||j|Wdq1s@0Yn4|dur`|dn |jdkrt|d||jdS)Nr r....r)r#rrr rrrr)rrr#rrrrs .   z_Unparser.visit_ConstantcsJdd*fddj|jWdn1s<0YdS)N[]cs dSrrrrrrrrSz&_Unparser.visit_List..)r rrr0rrrr visit_Listsz_Unparser.visit_ListcCsR|dd2||j|jD]}||q Wdn1sD0YdS)Nrrr relt generatorsrrgenrrrvisit_ListComps  z_Unparser.visit_ListCompcCsR|dd2||j|jD]}||q Wdn1sD0YdSNr rrrrrrvisit_GeneratorExps  z_Unparser.visit_GeneratorExpcCsR|dd2||j|jD]}||q Wdn1sD0YdS)Nrrrrrrr visit_SetComps  z_Unparser.visit_SetCompcCsh|ddH||j|d||j|jD]}||q6Wdn1sZ0YdS)Nrrr2)r rrrr#rrrrrvisit_DictComps     z_Unparser.visit_DictCompcCs|jr|dn |d|tj|j||j|d|jtj|j g|j R||j |j D]}|d||qrdS)Nz async for z for rh if ) is_asyncrrrrr&rrrrifs)rrZ if_clauserrrvisit_comprehensions       z_Unparser.visit_comprehensioncCs|tj|p|tj|j|j||j|d||j|d|tj|j ||j Wdn1s0YdS)Nrz else ) rrrrrrFr?rrrRrrrr visit_IfExps    z_Unparser.visit_IfExpcs\|jrNdd*fddj|jWdqX1sB0Yn ddS)Nrrcs dSrrrrrrrrSz%_Unparser.visit_Set..z{*()})r0r rrrrrrr visit_Sets:z_Unparser.visit_Setcsjfddfdd}dd0fdd|t|j|jWdn1s\0YdS) Ncs"|d|dSNr2)rr)kvrrrwrite_key_value_pair s  z2_Unparser.visit_Dict..write_key_value_paircsB|\}}|dur4dtj||n ||dS)N**)rrrrr)r}rrrrrr write_items   z(_Unparser.visit_Dict..write_itemrrcs dSrrrrrrrrSz&_Unparser.visit_Dict..)r rr>r;r<)rrrrrr visit_Dicts   z_Unparser.visit_DictcCs@|dd ||j|jWdn1s20YdSr)r rrr0rrrr visit_Tuplesz_Unparser.visit_Tuple~not+r)ZInvertZNotr)r*)rrrrcCs|j|jjj}|j|}|||H|||tjurF|d| ||j | |j Wdn1st0YdSNrf) unopr(rZr[unop_precedencerrrrrr+r)rroperatoroperator_precedencerrr visit_UnaryOp*s    z_Unparser.visit_UnaryOprrX/%<<>>|^&//r) r?r@ZMultZMatMultZDivZModZLShiftZRShiftZBitOrZBitXorZBitAndZFloorDivZPow) rrrrXrrrrrrrrr)rcCs|j|jjj}|j|}|||z||jvr@|}|}n |}|}|||j | |j | d|d|||j | |j Wdn1s0YdSr) r0r(rZr[binop_precedencer binop_rassocrrrArrrB)rrrrZleft_precedenceZright_precedencerrr visit_BinOpWs   z_Unparser.visit_BinOpz==z!=z>=iszis notinznot in) ZEqZNotEqZLtZLtEZGtZGtEZIsZIsNotZInZNotIncCs|tj|x|jtj|jg|jR||jt|j |jD].\}}| d|j |j j d||qHWdn1s0YdSr)rrrrrrA comparatorsrr>opsrcmpopsrZr[)rror]rrr visit_Compareus  z_Unparser.visit_Compareandor)ZAndZOr)rrcs~j|jjj}j|fdd}|6d|dfdd||jWdn1sp0YdS)Ncs"||dSr )rrrr)rrrrincreasing_level_traverses z9_Unparser.visit_BoolOp..increasing_level_traverserfcs Sr rr)rrrrrrSz(_Unparser.visit_BoolOp..)boolopsr(rZr[boolop_precedencerrr<)rrrrr)rrrr visit_BoolOps   z_Unparser.visit_BoolOpcCsZ|tj|j||jt|jtr@t|jjtr@|d|d||j dS)Nrfr*) rrrr#rrr!r$rrqrrrrvisit_Attributes    z_Unparser.visit_AttributecCs|tj|j||j|ddhd}|jD]"}|rH|dnd}||q4|jD]"}|rr|dnd}||q^Wdn1s0YdS)Nr rFrLT) rrrr4rr r7rr8)rrr\r]rrr visit_Calls      z_Unparser.visit_CallcCs~dd}|tj|j||j|dd:||jrP||j|jjn ||jWdn1sp0YdS)NcSs&t|to$|jo$tdd|jD S)Ncss|]}t|tVqdSr )rZStarred)rNrrrrrRrSzE_Unparser.visit_Subscript..is_simple_tuple..)rr.r0any)Z slice_valuerrris_simple_tuples  z2_Unparser.visit_Subscript..is_simple_tuplerr) rrrr#rr rrr0)rrrrrrvisit_Subscripts   z_Unparser.visit_SubscriptcCs*|d|tj|j||jdS)Nr)rrrrr#rrrrr visit_Starreds z_Unparser.visit_StarredcCs|ddS)Nrrrrrrvisit_Ellipsissz_Unparser.visit_EllipsiscCsN|jr||j|d|jr.||j|jrJ|d||jdS)Nr)lowerrruppersteprrrr visit_Slices    z_Unparser.visit_SlicecCs,||j|jr(|d||jdSr)rargr3rrrrr visit_args  z_Unparser.visit_argc Csd}|j|j}dgt|t|j|j}tt||dD]^\}}|\}}|rXd}n |d|||r|d|||t|jkr>|dq>|js|j r|rd}n |d|d|jr||jj |jj r|d||jj |j rLt|j |j D]8\}}|d|||r|d||q|j r|r`d}n |d|d |j j |j j r|d||j j dS) NTrIFrL=z, /rr2r) posonlyargsr7r:defaults enumerater>rrvararg kwonlyargsrr3 kw_defaultskwarg) rrrZall_argsrrelementsadrrrvisit_argumentssN                z_Unparser.visit_argumentscCs<|jdur|dn||j|d||jdS)Nrr)rrrr#rrrr visit_keyword s     z_Unparser.visit_keywordcCsn|tj|L|d||j|d|tj|j||jWdn1s`0YdS)Nzlambda r2)rrrrrr7rrFrrrr visit_Lambdas    z_Unparser.visit_LambdacCs&||j|jr"|d|jdSNrV)rraasnamerrrr visit_aliass z_Unparser.visit_aliascCs,||j|jr(|d||jdSr)r context_expr optional_varsrrrrrvisit_withitems  z_Unparser.visit_withitem)rK)wr[rrrrrrrrrrpropertyrrrr r rrrrrrrrr r$r%r'r)r,r/r1r4r6r9r;r=r>rArCrDrFrHrIrMrTrWr^rbrcrarfrgrerirjrlrmrr}rrrrrrrrrrrrrrrrrrrrrrrrrrr0rrrrrrrr frozensetrrrrrrrrrrrrrrrrrrrrr __classcell__rrrrrs               &        3rcCst}||Sr )rr)Zast_objrrrrunparse$srcCsddl}|jdd}|jd|jddddd d |jd d d ddd|jddddd|jddddd|jddtddd|}|j}|}Wdn1s0Yt||jj |j |j d }t t ||j|jd!dS)"Nrz python -m ast)proginfilerbr?rz$the file to parse; defaults to stdin)r"nargsdefaulthelpz-mz--moder)rZsinglerZ func_typez(specify what kind of code must be parsed)rchoicesrz--no-type-commentsTZ store_falsez)don't add information about type comments)ractionrz-az--include-attributes store_truez:include attributes such as line numbers and column offsets)rrz-iz--indentr z'indentation of nodes (number of spaces))r"rr)r )rerH)argparseArgumentParser add_argumentZFileTyper$ parse_argsrreadrrarZno_type_commentsprintrhrerH)r parserr7rrZtreerrrmain)s0     &r__main__)rr)TF)rI)T)KrsysZ_ast contextlibrrenumrrrrGrhrrrwrzr|rsrrrrrxobjectrrrmr!rrrryrr"rrrrrrrr$r%r&rEbytesboolrrrrTrrrr.rrrmodrZ expr_contextrrrr] float_info max_10_exprrZ_SINGLE_QUOTESrurrrrr[rrrrs 8C#    %:<