a Z^@sdZddlZddlTddlmZmZddlmZmZd\ddd d d Z d d Z d]ddddZ ddZ ddZ d^ddZddZddZd_ddZdd Zd!d"Zdd#d$d%Zd&d'ZGd(d)d)eZGd*d+d+eZd,d-Zd.d/Zeeee_eeee_Gd0d1d1eZ d2d3Z!Gd4d5d5ee d6Z"Gd7d8d8ee d6Z#Gd9d:d:ee d6Z$Gd;d<dd>ee d6Z&e"e'e(e)fe#e*fe$e+fe%ede,fe&ed?fiZ-e"e,fiZ.e,diZ/Gd@dAdAe0Z1GdBdCdCe1Z2GdDdEdEe1Z3dFdGZ4dHdIZ5ee4e5e6_7GdJdKdKe8Z9GdLdMdMe:Z;GdNdOdOe:Zej?j@dZAGdSdTdTeZBGdUdVdVeZCdWdXZDdYdZZEeFd[kreEdS)`aH 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/usr/lib64/python3.9/ast.pyparse!s   rcs`t|trt|dd}t|tr&|j}ddfddfddfd d |S) a Safely evaluate an expression node or a string containing 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. evalrcSstd|dS)Nzmalformed node or string: ) ValueErrornoderrr_raise_malformed_nodeAsz+literal_eval.._raise_malformed_nodecs,t|trt|jtttfvr&||jSN)rConstanttypevalueintfloatcomplexr)rrr _convert_numCsz"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,rrrrDOs<          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) rrPprefixsepclsr7Z allsimpler8namer#simplerOannotate_fieldsinclude_attributesrH)rPrrOxsX          &zdump.._formatzexpected AST, got %rN )r)rrS TypeErrorrYrZrE)rrcrdrHrrbrdumpls 0 rgcCsBdD]8}||jvr||jvrt||d}|durt|||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_offsetN)rXrUsetattr)new_nodeZold_nodeattrr#rrr copy_locations  rocs 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)Nrhrjrirk)rXhasattrrhrUrjrirkiter_child_nodes)rrhrirjrkchild_fixrrrts$       z#fix_missing_locations.._fixrIrrrrrsrfix_missing_locationss rurIcCsJt|D]<}d|jvr(t|dd||_d|jvrt|dd||_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. rhrrj)walkrXrUrhrj)rnrrrrrincrement_linenos    rxc cs8|jD],}z|t||fVWqty0Yq0qdS)zs Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. N)rTrUrV)rfieldrrr iter_fieldss   rzccsLt|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)rzrrSr2)rr`ryitemrrrrqs   rqcCst|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) rjrkrhrirVrencodedecoderinsertrWr[) rrrrhrjrirkrZpaddingfirstZlastrrrget_source_segmentEs*       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) collectionsrpopleftextendrq)rrZtodorrrrvjs   rvc@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_)rYrZrU 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)rzrr2rSr)rrryr#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"itemsrrUrVwarningswarnDeprecationWarningr) rrr# type_namer_r`rrrrrrvisit_Constants&   zNodeVisitor.visit_ConstantN)rZ __module__ __qualname____doc__rrrrrrrrxs 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 ) rzrr2rSrrrWdelattrrl)rrry old_valueZ new_valuesr#rmrrrrs&         zNodeTransformer.generic_visitN)rZrrrrrrrrrs#rcCs|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#rV_const_types_notrr"__instancecheck__)r_instr#rrrrs   z_ABC.__instancecheck__N)rZrrrrrrrrrsrcOsp|D]<}||jvrq|j|}|t|krt|jd|q|tvrXt|i|Stj|g|Ri|S)Nz" got multiple values for argument )rTindexr:rfrZrr!__new__)r_r7kwargskeyposrrr_news   rc@seZdZdZeZdS)Num)rwNrZrrrTrrrrrrrsr) metaclassc@seZdZdZeZdS)rrNrrrrrrsrc@seZdZdZeZdS)BytesrNrrrrrr"src@seZdZeZdS) NameConstantN)rZrrrrrrrrr&src@seZdZdZddZdS)EllipsisrcOs6|turtdg|Ri|Stj|g|Ri|S)N.)rr!r)r_r7rrrrr,szEllipsis.__new__N)rZrrrTrrrrrr)sr.c@seZdZdZdS)slicezDeprecated AST node class.NrZrrrrrrrrGsrc@seZdZdZddZdS)Indexz@Deprecated AST node class. Use the index value directly instead.cKs|Sr r)r_r#rrrrrLsz Index.__new__NrZrrrrrrrrrJsrc@seZdZdZdddZdS)ExtSlicez1Deprecated AST node class. Use ast.Tuple instead.rcKstt|tfi|Sr )r.r2ZLoad)r_dimsrrrrrQszExtSlice.__new__N)rrrrrrrOsrcCs|jS)zDeprecated. Use elts instead.r0rrrr _dims_getterTsrcCs ||_dSr rrrrr _dims_setterXsrc@seZdZdZdS)Suite/Deprecated AST node class. Unused in Python 3.Nrrrrrr]src@seZdZdZdS)AugLoadrNrrrrrr`src@seZdZdZdS)AugStorerNrrrrrrcsrc@seZdZdZdS)ParamrNrrrrrrfsrZ1ec@seZdZdZeZeZeZeZeZ eZ eZ eZ e Z eZeZeZeZeZeZeZeZeZddZdS) _Precedencez5Precedence table that originated from python grammar.cCs,z||dWSty&|YS0dSNrI)rYrrrrrnexts z_Precedence.nextN)rZrrrrTUPLEYIELDTESTORANDNOTCMPEXPRBORBXORBANDSHIFTARITHTERMFACTORPOWERAWAITATOMrrrrrrns(rcseZdZdZddZddZddZdd Zdd d Zd dZ ddZ e ddZ e ddddZe ddZddZddZddZdd Zd!d"Zd#d$Zfd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:Z d;d<Z!d=d>Z"d?d@Z#dAdBZ$dCdDZ%dEdFZ&dGdHZ'dIdJZ(dKdLZ)dMdNZ*dOdPZ+dQdRZ,dSdTZ-dUdVZ.dWdXZ/dYdZZ0d[d\Z1d]d^Z2d_d`Z3dadbZ4dcddZ5dedfZ6dgdhZ7didjZ8dkdlZ9dmdnZ:dodpZ;dqdrZdwdxZ?dydzZ@d{d|ZAd}d~ZBddZCddZDddZEddZFddZGddZHddZIddZJddZKddZLddZMdddddZNeOjPeOjQeOjQeOjQdZRddZSdddddddddddddd ZTeOjUeOjUeOjVeOjVeOjVeOjVeOjWeOjWeOjXeOjYeOjZeOjVeOj[d Z\e]dZ^ddZ_ddddddddddd Z`ddZadddZbeOjceOjddZeddZfddZgddÄZhddńZiddDŽZjddɄZkdd˄Zldd̈́ZmddτZnddфZoddӄZpddՄZqddׄZrZsS) _UnparserzMethods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.cCs"g|_g|_i|_i|_d|_dS)Nr)_source_buffer _precedences _type_ignores_indentrrrrrs z_Unparser.__init__cCsHt|}z|t|Wnty*Yn0|D]}|||q0dS)z7Call f on each item in seq, calling inter() in between.N)iterr StopIteration)rZinterfseqrNrrr 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 dSNrLwriterrrrrRz&_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)rrWrrrrrsz_Unparser.writecCs|j|dSr )rrWrrrr 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 )rr)rrr conditionrrr delimit_ifs z_Unparser.delimit_ifcCs|dd|||kS)z,Shortcut to adding precedence related parens())rget_precedence)r precedencerrrrrequire_parenssz_Unparser.require_parenscCs|j|tjSr )rrrrrrrrrr sz_Unparser.get_precedencecGs|D]}||j|<qdSr )r)rr Znodesrrrrset_precedencesz_Unparser.set_precedencecCs`t|ttttfr t|jdkr$dS|jd}t|ts||}r.||||jddn ||jdSr)r_write_docstringrrF)rrZ docstringrrr"_write_docstring_and_traverse_bodys z,_Unparser._write_docstring_and_traverse_bodycCs*dd|jD|_|||jdS)NcSsi|]}|jd|jqS)ignore)rhtag)rMrrrr sz*_Unparser.visit_Module..) type_ignoresrrrr rrr visit_Modules  z_Unparser.visit_Modulecs`dd*fddj|jWdn1s<0Yd|jdS)Nrr cs dSrrrrrrr"rRz._Unparser.visit_FunctionType.. -> )rrrargtypesrreturnsr rrrvisit_FunctionTypes " z_Unparser.visit_FunctionTypecCs(||tj|j||jdSr )rrrrr#rr rrr visit_Expr(sz_Unparser.visit_ExprcCsh|tj|F|tj|j|j||j|d||jWdn1sZ0YdS)Nz := ) r rrrrtargetr#rrr rrrvisit_NamedExpr-s   z_Unparser.visit_NamedExprcs(dfddj|jdS)Nzimport cs dSrrrrrrr6rRz(_Unparser.visit_Import..)rrrnamesr rrr visit_Import4s z_Unparser.visit_ImportcsTdd|j|jr,|jdfddj|jdS)Nzfrom .z import cs dSrrrrrrr>rRz,_Unparser.visit_ImportFrom..)rrrPmodulerrr#r rrrvisit_ImportFrom8s    z_Unparser.visit_ImportFromcCsP||jD]}|||dq||j||}rL||dS)N = )rtargetsrrr#r)rrr!rrrr visit_Assign@s    z_Unparser.visit_AssigncCsB|||j|d|j|jjjd||jdS)Nrez= ) rrr!rbinopr(rYrZr#r rrrvisit_AugAssignIs z_Unparser.visit_AugAssigncCs||dd|j o"t|jt||jWdn1sH0Y|d||j|j r|d||j dS)Nrr : r() rrrarr!r5rr annotationr#r rrrvisit_AnnAssignOs *   z_Unparser.visit_AnnAssigncCs*|d|jr&|d||jdS)Nreturnre)rr#rrr rrr visit_ReturnYs  z_Unparser.visit_ReturncCs|ddS)Npassrr rrr visit_Pass_sz_Unparser.visit_PasscCs|ddS)Nbreakr3r rrr visit_Breakbsz_Unparser.visit_BreakcCs|ddS)Ncontinuer3r rrrvisit_Continueesz_Unparser.visit_Continuecs(dfddj|jdS)Nzdel cs dSrrrrrrrjrRz(_Unparser.visit_Delete..)rrrr)r rrr visit_Deletehs z_Unparser.visit_DeletecCs6|d||j|jr2|d||jdS)Nzassert rL)rrtestmsgrr rrr visit_Assertls    z_Unparser.visit_Assertcs(dfddj|jdS)Nzglobal cs dSrrrrrrrurRz(_Unparser.visit_Global..rrrr#r rrr visit_Globalss z_Unparser.visit_Globalcs(dfddj|jdS)Nz nonlocal cs dSrrrrrrryrRz*_Unparser.visit_Nonlocal..r=r rrrvisit_Nonlocalws z_Unparser.visit_NonlocalcCsh|tj|F|d|jrF|d|tj|j||jWdn1sZ0YdS)Nawaitre)r rrrr#rrrr rrr visit_Await{s   z_Unparser.visit_AwaitcCsh|tj|F|d|jrF|d|tj|j||jWdn1sZ0YdS)Nyieldre)r rrrr#rrrr rrr 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.) r rrrr#rrrrr rrrvisit_YieldFroms  z_Unparser.visit_YieldFromcCsX|d|js"|jrtddS|d||j|jrT|d||jdS)Nraisez*Node can't use cause without an exception.rez from )rexccauserrrr rrr visit_Raises    z_Unparser.visit_RaisecCs|d|||jWdn1s40Y|jD]}||qD|jr|d|||jWdn1s0Y|jr|d|||jWdn1s0YdS)Ntryelsefinally)rrrrFhandlersorelse finalbody)rrexrrr visit_Trys  *    *  z_Unparser.visit_TrycCsz|d|jr&|d||j|jrB|d||j|||jWdn1sl0YdS)Nexceptre as )rr"rrr`rrFr rrrvisit_ExceptHandlers      z_Unparser.visit_ExceptHandlercCs||jD]}|d||q|d|j|jdd|jpJ|jdhd}|jD]"}|rp|dnd}||q\|jD]"}|r|dnd}||qWdn1s0Y| | |Wdn1s0YdS) N@zclass rr )rFrLT) rdecorator_listrrr`rbasesr8rrr)rrdecocommaerrrvisit_ClassDefs&        * z_Unparser.visit_ClassDefcCs||ddS)Ndef_function_helperr rrrvisit_FunctionDefsz_Unparser.visit_FunctionDefcCs||ddS)Nz async defr\r rrrvisit_AsyncFunctionDefsz _Unparser.visit_AsyncFunctionDefcCs||jD]}|d||q|d|j}|||dd||jWdn1sn0Y|jr|d||j|j | |d| |Wdn1s0YdS)NrTrerr rr) rrUrrr`rr7rrrrr)rrZ fill_suffixrWZdef_strrrrr]s    *  z_Unparser._function_helpercCs|d|dS)Nzfor  _for_helperr rrr visit_Forsz_Unparser.visit_ForcCs|d|dS)Nz async for r`r rrrvisit_AsyncForsz_Unparser.visit_AsyncForcCs||||j|d||j|j||d||jWdn1s`0Y|jr|d|||jWdn1s0YdS)N in rrJ) rrr!rrrrrFrM)rrrrrrras    *  z_Unparser._for_helpercCs|d||j|||jWdn1s@0Y|jrt|jdkrt|jdtr|jd}|d||j|||jWdqJ1s0YqJ|jr |d|||jWdn1s0YdS)Nzif rIrzelif rJ) rrr:rrFrMr:rZIfr rrrvisit_Ifs   *$    ,  z_Unparser.visit_IfcCs|d||j|||jWdn1s@0Y|jr|d|||jWdn1s0YdS)Nzwhile rJ)rrr:rrFrMr rrr visit_While s   *  z_Unparser.visit_Whilecsfdfddj|jj|d|jWdn1sX0YdS)Nzwith cs dSrrrrrrrrRz&_Unparser.visit_With..rrrrrrrrFr rrr visit_Withs z_Unparser.visit_Withcsfdfddj|jj|d|jWdn1sX0YdS)Nz async with cs dSrrrrrrrrRz+_Unparser.visit_AsyncWith..rrgr rrrvisit_AsyncWiths z_Unparser.visit_AsyncWithcCs,|d|||j|t|jdSNr)r_fstring_JoinedStrrr\rr rrrvisit_JoinedStr s z_Unparser.visit_JoinedStrcCs,|d|||j|t|jdSrj)r_fstring_FormattedValuerr\rr rrrvisit_FormattedValue%s z_Unparser.visit_FormattedValuecCs.|jD]"}t|dt|j}|||qdS)N _fstring_)r<rUr"rZ)rrrr#methrrrrk*s z_Unparser._fstring_JoinedStrcCs6t|jtstd|jdddd}||dS)Nz.Constants inside JoinedStr should be a string.{z{{}z}})rr#rErreplace)rrrr#rrr_fstring_Constant/s z_Unparser._fstring_ConstantcCs|dt|}|tj|j||j}|drD|d|||jdkr~t |j}|dvrpt d|d||j r|dt |dt|j j }||j ||d dS) Nrqrer ZsrazUnknown f-string conversion.!rrorr)r"rrrrr#r startswith conversionchrr format_specrUrZ)rrrunparserexprrwrprrrrm5s"      z!_Unparser._fstring_FormattedValuecCs||jdSr )rr6r rrr visit_NameHsz_Unparser.visit_NamecCszdd}||jdkr$|d|j}|rddt||}|ddkrX|ddd}|dd }|d|ddS) NcSs|dvr |S|ddS)N)rJ Zunicode_escapeascii)rr)rrrresc_charLsz,_Unparser._write_docstring..esc_charurKr "z\"z"""z""\")rkindrr#r[r/rs)rrrr#rrrrKs     z_Unparser._write_docstringcCs8t|ttfr&|t|dtn|t|dS)Ninf)rr%r&rr\rs_INFSTRrrrr_write_constantcsz_Unparser._write_constantcCs|j}t|trL|dd||j|Wdq1s@0Yn4|dur`|dn |jdkrt|d||jdS)Nrr ....r)r#rrrrrrr)rrr#rrrrjs .   z_Unparser.visit_ConstantcsJdd*fddj|jWdn1s<0YdS)N[]cs dSrrrrrrrxrRz&_Unparser.visit_List..)rrrr0r rrr visit_Listvsz_Unparser.visit_ListcCsR|dd2||j|jD]}||q Wdn1sD0YdS)Nrrrrelt generatorsrrgenrrrvisit_ListCompzs  z_Unparser.visit_ListCompcCsR|dd2||j|jD]}||q Wdn1sD0YdSNrr rrrrrvisit_GeneratorExps  z_Unparser.visit_GeneratorExpcCsR|dd2||j|jD]}||q Wdn1sD0YdS)Nrqrrrrrrr visit_SetComps  z_Unparser.visit_SetCompcCsh|ddH||j|d||j|jD]}||q6Wdn1sZ0YdS)Nrqrrr-)rrrrr#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 rd 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 ) r rrrrrFr:rrrMr rrr visit_IfExps    z_Unparser.visit_IfExpcsX|jstddd*fddj|jWdn1sJ0YdS)Nz&Set node should have at least one itemrqrrcs dSrrrrrrrrRz%_Unparser.visit_Set..)r0rrrrr rrr visit_Setsz_Unparser.visit_Setcsjfddfdd}dd0fdd|t|j|jWdn1s\0YdS) Ncs"|d|dSNr-)rr)kvrrrwrite_key_value_pairs  z2_Unparser.visit_Dict..write_key_value_paircsB|\}}|dur4dtj||n ||dS)N**)rrrrr)r{rrrrrr write_items   z(_Unparser.visit_Dict..write_itemrqrrcs dSrrrrrrrrRz&_Unparser.visit_Dict..)rrr>r;r<)rrrrrr visit_Dicts   z_Unparser.visit_DictcCs@|dd ||j|jWdn1s20YdSr)rrrr0r rrr visit_Tuplesz_Unparser.visit_Tuple~not+-)ZInvertZNotr)r*)rrrrcCs|j|jjj}|j|}|||H|||tjurF|d| ||j | |j Wdn1st0YdSNre) unopr(rYrZunop_precedencer rrrrr+r)rroperatoroperator_precedencerrr visit_UnaryOps    z_Unparser.visit_UnaryOprrT/%<<>>|^&//r) r?r@ZMultZMatMultZDivZModZLShiftZRShiftZBitOrZBitXorZBitAndZFloorDivZPow) rrrrTrrrrrrrrr)rcCs|j|jjj}|j|}|||z||jvr@|}|}n |}|}|||j | |j | d|d|||j | |j Wdn1s0YdSr) r+r(rYrZbinop_precedencer  binop_rassocrrrArrrB)rrrrZleft_precedenceZright_precedencerrr visit_BinOps   z_Unparser.visit_BinOpz==z!=z>=iszis notinznot in) ZEqZNotEqZLtZLtEZGtZGtEZIsZIsNotZInZNotIncCs|tj|x|jtj|jg|jR||jt|j |jD].\}}| d|j |j j d||qHWdn1s0YdSr)r rrrrrA comparatorsrr>opsrcmpopsrYrZ)rrorYrrr visit_Compares  z_Unparser.visit_Compareandor)ZAndZOr)rrcs~j|jjj}j|fdd}|6d|dfdd||jWdn1sp0YdS)Ncs"||dSr )rrrr)rrrrincreasing_level_traverse.s z9_Unparser.visit_BoolOp..increasing_level_traverserecs Sr rr)rrrrr6rRz(_Unparser.visit_BoolOp..)boolopsr(rYrZboolop_precedencer rr<)rrrrr)rrrr visit_BoolOp*s   z_Unparser.visit_BoolOpcCsZ|tj|j||jt|jtr@t|jjtr@|d|d||j dS)Nrer%) rrrr#rrr!r$rrnr rrrvisit_Attribute8s    z_Unparser.visit_AttributecCs|tj|j||j|ddhd}|jD]"}|rH|dnd}||q4|jD]"}|rr|dnd}||q^Wdn1s0YdS)Nrr FrLT) rrrr4rrr7rr8)rrrXrYrrr visit_CallCs      z_Unparser.visit_CallcCs~dd}|tj|j||j|dd:||jrP||j|jjn ||jWdn1sp0YdS)NcSs&t|to$|jo$tdd|jD S)Ncss|]}t|tVqdSr )rZStarred)rMrrrrrQ]rRzE_Unparser.visit_Subscript..is_simple_tuple..)rr.r0any)Z slice_valuerrris_simple_tupleVs  z2_Unparser.visit_Subscript..is_simple_tuplerr) rrrr#rrrrr0)rrrrrrvisit_SubscriptUs   z_Unparser.visit_SubscriptcCs*|d|tj|j||jdS)Nr)rrrrr#rr rrr visit_Starredhs z_Unparser.visit_StarredcCs|ddS)Nrrr rrrvisit_Ellipsismsz_Unparser.visit_EllipsiscCsN|jr||j|d|jr.||j|jrJ|d||jdS)Nr)lowerrrupperstepr rrr visit_Sliceps    z_Unparser.visit_SlicecCs,||j|jr(|d||jdSr)rargr.rr rrr visit_argzs  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, /rr-r) posonlyargsr7r:defaults enumerater>rrvararg kwonlyargsrr. kw_defaultskwarg) rrrZall_argsrrelementsadrrrvisit_argumentssN                z_Unparser.visit_argumentscCs<|jdur|dn||j|d||jdS)Nrr)rrrr#r rrr visit_keywords     z_Unparser.visit_keywordcCsn|tj|L|d||j|d|tj|j||jWdn1s`0YdS)Nzlambda r-)r rrrrr7rrFr rrr visit_Lambdas    z_Unparser.visit_LambdacCs&||j|jr"|d|jdSNrR)rr`asnamer rrr visit_aliass z_Unparser.visit_aliascCs,||j|jr(|d||jdSr)r context_expr optional_varsrr rrrvisit_withitems  z_Unparser.visit_withitem)rK)trZrrrrrrrrrrpropertyrrrrrr r rrrrrrrrr r"r$r'r*r,r/r1r4r6r8r9r<r>r?rArCrDrHrPrSrZr^r_r]rbrcrarerfrhrirlrnrkrtrmr|rrrrrrrrrrrrrrrrrrrr+rrrrrrrr frozensetrrrrrrrrrrrrrrrrrrrrr __classcell__rrrrrs                     3rcCst}||Sr )rr)Zast_objrzrrrunparsesrcCsddl}|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-commentsT 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 )rdrH)argparseArgumentParser add_argumentFileTyper$ parse_argsrreadrr`rZno_type_commentsprintrgrdrH)rparserr7rrZtreerrrmains0     &r__main__)rr)TF)rI)T)GrsysZ_ast contextlibrrenumrrrrGrgrorurxrzrqrrrrrvobjectrrrrrr!rwrr"rrrrrrrr$r%r&rEbytesboolrrrrSrrrrrr.rmodrZ expr_contextrrrr\ float_info max_10_exprrrrrrZrrrrs 6C #    %:>        I