zfc@sdZddlTddlmZdddZdZeedZd Zd Z d d Z d Z dZ edZ dZdefdYZdefdYZdS(sH 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. i(t*(t __version__s texeccCst|||tS(sn Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). (tcompilet PyCF_ONLY_AST(tsourcetfilenametmode((s/usr/lib64/python2.7/ast.pytparse scsvidd6td6td6t|tr?t|dd}nt|trZ|j}nfd|S(s 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, numbers, tuples, lists, dicts, booleans, and None. tNonetTruetFalseRtevalcst|tr|jSt|tr,|jSt|trQtt|jSt|t rvt t|jSt|t rt fdt |j|jDSt|tr|jkr|jSnt|trt|jttfrt|jtrt|jjtrt|jtrt|jjtttfr|jj}|jj}t|jtr||S||SntddS(Nc3s-|]#\}}||fVqdS(N((t.0tktv(t_convert(s/usr/lib64/python2.7/ast.pys >ssmalformed string(t isinstancetStrtstNumtntTuplettupletmapteltstListtlisttDicttdicttziptkeystvaluestNametidtBinOptoptAddtSubtrighttcomplextlefttinttlongtfloatt ValueError(tnodeR)R'(Rt _safe_names(s/usr/lib64/python2.7/ast.pyR4s4   N(R R R Rt basestringRt Expressiontbody(tnode_or_string((RR/s/usr/lib64/python2.7/ast.pyt literal_eval(s csGfdt|ts=td|jjn|S(s Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to True. csttrgtD]\}}||f^q}djjdjrhd|Dn d|Df}rjr||rdpd7}|djfdjD7}n|dSttrddjfd DStS( Ns%s(%ss, css|]}d|VqdS(s%s=%sN((R tfield((s/usr/lib64/python2.7/ast.pys `scss|]\}}|VqdS(N((R tatb((s/usr/lib64/python2.7/ast.pys bst c3s.|]$}d|t|fVqdS(s%s=%sN(tgetattr(R R6(t_formatR.(s/usr/lib64/python2.7/ast.pys fst)s[%s]c3s|]}|VqdS(N((R tx(R:(s/usr/lib64/python2.7/ast.pys js( RtASTt iter_fieldst __class__t__name__tjoint _attributesRtrepr(R.R6R7tfieldstrv(R:tannotate_fieldstinclude_attributes(R.s/usr/lib64/python2.7/ast.pyR:\s1!sexpected AST, got %r(RR=t TypeErrorR?R@(R.RFRG((R:RFRGs/usr/lib64/python2.7/ast.pytdumpSs cCs^xWdD]O}||jkr||jkrt||rt||t||qqW|S(s Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. tlinenot col_offset(RJRK(RBthasattrtsetattrR9(tnew_nodetold_nodetattr((s/usr/lib64/python2.7/ast.pyt copy_locationqs   cs#fd|dd|S(s{ 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|jkr6t|ds*||_q6|j}nd|jkrlt|ds`||_ql|j}nx$t|D]}|||qyWdS(NRJRK(RBRLRJRKtiter_child_nodes(R.RJRKtchild(t_fix(s/usr/lib64/python2.7/ast.pyRTs    ii((R.((RTs/usr/lib64/python2.7/ast.pytfix_missing_locations}s icCsFx?t|D]1}d|jkr t|dd||_q q W|S(s Increment the 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. RJi(twalkRBR9RJ(R.RRS((s/usr/lib64/python2.7/ast.pytincrement_linenos ccsDx=|jD]2}y|t||fVWq tk r;q Xq WdS(ss Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. N(t_fieldsR9tAttributeError(R.R5((s/usr/lib64/python2.7/ast.pyR>s  ccsrxkt|D]]\}}t|tr0|Vq t|tr x(|D]}t|trF|VqFqFWq q WdS(s 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>RR=R(R.tnameR5titem((s/usr/lib64/python2.7/ast.pyRRs cCst|tttfs1td|jjn|jrt|jdtrt|jdj t r|rddl }|j |jdj j S|jdj j SdS(s Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. s%r can't have docstringsiiN(Rt FunctionDeftClassDeftModuleRHR?R@R2tExprtvalueRtinspecttcleandocR(R.tcleanRa((s/usr/lib64/python2.7/ast.pyt get_docstrings ccsTddlm}||g}x.|rO|j}|jt||Vq"WdS(s 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. i(tdequeN(t collectionsRetpoplefttextendRR(R.Rettodo((s/usr/lib64/python2.7/ast.pyRVs   t NodeVisitorcBs eZdZdZdZRS(s< 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(s Visit a node.tvisit_(R?R@R9t generic_visit(tselfR.tmethodtvisitor((s/usr/lib64/python2.7/ast.pytvisitscCsx{t|D]m\}}t|tr[xO|D]%}t|tr/|j|q/q/Wq t|tr |j|q q WdS(s9Called if no explicit visitor function exists for a node.N(R>RRR=Rp(RmR.R5R`R[((s/usr/lib64/python2.7/ast.pyRls (R@t __module__t__doc__RpRl(((s/usr/lib64/python2.7/ast.pyRjs tNodeTransformercBseZdZdZRS(s\ 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 copy_location(Subscript( value=Name(id='data', ctx=Load()), slice=Index(value=Str(s=node.id)), ctx=node.ctx ), node) 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) cCsx t|D]\}}t||d}t|trg}xp|D]h}t|tr|j|}|dkr}qGqt|ts|j|qGqn|j|qGW||(q t|tr |j|}|dkrt ||q t |||q q W|S(N( R>R9R RRR=RpRhtappendtdelattrRM(RmR.R5t old_valuet new_valuesR`RN((s/usr/lib64/python2.7/ast.pyRl"s(      (R@RqRrRl(((s/usr/lib64/python2.7/ast.pyRss"N(Rrt_astRRR4R R RIRQRURWR>RRRdRVtobjectRjRs(((s/usr/lib64/python2.7/ast.pyts  +    %