
    }e'                         d Z dZddlmZmZmZmZmZmZm	Z	 ddlZddl
Z
ddlmZmZ d Z G d de      Z G d	 d
e      Zy)a  
This module contains utility function and classes to inject simple ast
transformations based on code strings into IPython. While it is already possible
with ast-transformers it is not easy to directly manipulate ast.


IPython has pre-code and post-code hooks, but are ran from within the IPython
machinery so may be inappropriate, for example for performance mesurement.

This module give you tools to simplify this, and expose 2 classes:

- `ReplaceCodeTransformer` which is a simple ast transformer based on code
  template,

and for advance case:

- `Mangler` which is a simple ast transformer that mangle names in the ast.


Example, let's try to make a simple version of the ``timeit`` magic, that run a
code snippet 10 times and print the average time taken.

Basically we want to run :

.. code-block:: python

    from time import perf_counter
    now = perf_counter()
    for i in range(10):
        __code__ # our code
    print(f"Time taken: {(perf_counter() - now)/10}")
    __ret__ # the result of the last statement

Where ``__code__`` is the code snippet we want to run, and ``__ret__`` is the
result, so that if we for example run `dataframe.head()` IPython still display
the head of dataframe instead of nothing.

Here is a complete example of a file `timit2.py` that define such a magic:

.. code-block:: python

    from IPython.core.magic import (
        Magics,
        magics_class,
        line_cell_magic,
    )
    from IPython.core.magics.ast_mod import ReplaceCodeTransformer
    from textwrap import dedent
    import ast

    template = template = dedent('''
        from time import perf_counter
        now = perf_counter()
        for i in range(10):
            __code__
        print(f"Time taken: {(perf_counter() - now)/10}")
        __ret__
    '''
    )


    @magics_class
    class AstM(Magics):
        @line_cell_magic
        def t2(self, line, cell):
            transformer = ReplaceCodeTransformer.from_string(template)
            transformer.debug = True
            transformer.mangler.debug = True
            new_code = transformer.visit(ast.parse(cell))
            return exec(compile(new_code, "<ast>", "exec"))


    def load_ipython_extension(ip):
        ip.register_magics(AstM)



.. code-block:: python

    In [1]: %load_ext timit2

    In [2]: %%t2
       ...: import time
       ...: time.sleep(0.05)
       ...:
       ...:
    Time taken: 0.05435649999999441


If you wish to ran all the code enter in IPython in an ast transformer, you can
do so as well:

.. code-block:: python

    In [1]: from IPython.core.magics.ast_mod import ReplaceCodeTransformer
       ...:
       ...: template = '''
       ...: from time import perf_counter
       ...: now = perf_counter()
       ...: __code__
       ...: print(f"Code ran in {perf_counter()-now}")
       ...: __ret__'''
       ...:
       ...: get_ipython().ast_transformers.append(ReplaceCodeTransformer.from_string(template))

    In [2]: 1+1
    Code ran in 3.40410006174352e-05
    Out[2]: 2



Hygiene and Mangling
--------------------

The ast transformer above is not hygienic, it may not work if the user code use
the same variable names as the ones used in the template. For example.

To help with this by default the `ReplaceCodeTransformer` will mangle all names
staring with 3 underscores. This is a simple heuristic that should work in most
case, but can be cumbersome in some case. We provide a `Mangler` class that can
be overridden to change the mangling heuristic, or simply use the `mangle_all`
utility function. It will _try_ to mangle all names (except `__ret__` and
`__code__`), but this include builtins (``print``, ``range``, ``type``) and
replace those by invalid identifiers py prepending ``mangle-``:
``mangle-print``, ``mangle-range``, ``mangle-type`` etc. This is not a problem
as currently Python AST support invalid identifiers, but it may not be the case
in the future.

You can set `ReplaceCodeTransformer.debug=True` and
`ReplaceCodeTransformer.mangler.debug=True` to see the code after mangling and
transforming:

.. code-block:: python


    In [1]: from IPython.core.magics.ast_mod import ReplaceCodeTransformer, mangle_all
       ...:
       ...: template = '''
       ...: from builtins import type, print
       ...: from time import perf_counter
       ...: now = perf_counter()
       ...: __code__
       ...: print(f"Code ran in {perf_counter()-now}")
       ...: __ret__'''
       ...:
       ...: transformer = ReplaceCodeTransformer.from_string(template, mangling_predicate=mangle_all)


    In [2]: transformer.debug = True
       ...: transformer.mangler.debug = True
       ...: get_ipython().ast_transformers.append(transformer)

    In [3]: 1+1
    Mangling Alias mangle-type
    Mangling Alias mangle-print
    Mangling Alias mangle-perf_counter
    Mangling now
    Mangling perf_counter
    Not mangling __code__
    Mangling print
    Mangling perf_counter
    Mangling now
    Not mangling __ret__
    ---- Transformed code ----
    from builtins import type as mangle-type, print as mangle-print
    from time import perf_counter as mangle-perf_counter
    mangle-now = mangle-perf_counter()
    ret-tmp = 1 + 1
    mangle-print(f'Code ran in {mangle-perf_counter() - mangle-now}')
    ret-tmp
    ---- ---------------- ----
    Code ran in 0.00013654199938173406
    Out[3]: 2


T    )NodeTransformerStoreLoadNameExprAssignModuleN)DictOptionalc                     | dv rdS dS )N)__ret____code__FT names    =/usr/lib/python3/dist-packages/IPython/core/magics/ast_mod.py<lambda>r      s    4+B#B%      c                   Z    e Zd ZU dZdZeed<   dZeed<   d ZddZ	d	 Z
d
 Zd Zd Zd Zy)Manglerzb
    Mangle given names in and ast tree to make sure they do not conflict with
    user code.
    TenabledFdebugc                 4    | j                   rt        |i | y y N)r   print)selfargskwargss      r   logzMangler.log   s    ::4"6" r   Nc                     |d }|| _         y )Nc                 $    | j                  d      S )N___)
startswithr   s    r   r   z"Mangler.__init__.<locals>.<lambda>   s    T__U%; r   	predicate)r   r%   s     r   __init__zMangler.__init__   s    ;I"r   c                     | j                  |j                        r2| j                  d|j                         d|j                  z   |_        |S | j                  d|j                         |S )NManglingmangle-Not mangling)r%   idr   r   nodes     r   
visit_NamezMangler.visit_Name   sV    >>$''"HHZ)  $'')DG  HH^TWW-r   c                    | j                  |j                        r1| j                  d|j                         d|j                  z   |_        n| j                  d|j                         |j                  j                  D ]j  }| j                  |j                        r1| j                  d|j                         d|j                  z   |_        O| j                  d|j                         l | j                  |      S )Nr(   r)   r*   zMangling function argzNot mangling function arg)r%   r   r   r   arggeneric_visit)r   r-   r0   s      r   visit_FunctionDefzMangler.visit_FunctionDef   s    >>$))$HHZ+!DII-DIHH^TYY/99>> 	?C~~cgg&0#'':#cgg-4cgg>	? !!$''r   c                 $    | j                  |      S r   _visit_Import_and_ImportFromr,   s     r   visit_ImportFromzMangler.visit_ImportFrom       0066r   c                 $    | j                  |      S r   r4   r,   s     r   visit_ImportzMangler.visit_Import   r7   r   c                    |j                   D ]r  }|j                  |j                  n|j                  }| j                  |      rd|z   }| j	                  d|       ||_        W| j	                  d|j                         t |S )Nr)   zMangling AliaszNot mangling Alias)namesasnamer   r%   r   )r   r-   aliasr<   new_names        r   r5   z$Mangler._visit_Import_and_ImportFrom   ss    ZZ 	=E#(<<#7UZZU\\F~~f% )F 2)84'-u||<	= r   r   )__name__
__module____qualname____doc__r   bool__annotations__r   r   r&   r.   r2   r6   r9   r5   r   r   r   r   r      s@    
 GTE4##
(77	r   r   c                   ~    e Zd ZU dZeed<   dZeed<   eed<   	 ddede	e
   fd	Ze	 ddede	e
   fd
       Zd Zd Zy)ReplaceCodeTransformerTr   Fr   manglerNtemplatemappingc                    t        |t        t        d       f      sJ t        |t        d       t        d       f      sJ t        |t        j                        sJ || _        t        |      | _        |i }|| _        y )Nc                       y r   r   r   r   r   r   z1ReplaceCodeTransformer.__init__.<locals>.<lambda>  s    r   r$   )	
isinstancedicttypeastr	   rH   r   rG   rI   )r   rH   rI   mangling_predicates       r   r&   zReplaceCodeTransformer.__init__  su     'D$t*#5666,tDz4;M.NOOO(CJJ/// );<?Gr   c                 >     | t        j                  |      ||      S )N)rI   rP   )rO   parse)clsrH   rI   rP   s       r   from_stringz"ReplaceCodeTransformer.from_string  s"     IIhEW
 	
r   c           	         | j                   s|S |j                  d   }t        |t              r|j                  j	                          |j                  j                  t        t        dt                     g|j                               t        j                  |       t        t        dt                           }t        j                  |      }|| j                  d<   n/t        j                  d      j                  d   | j                  d<   |j                  | j                  d<   t        j                  | j                        }t!        j"                  |      }| j$                  j'                  |      }| j)                  |      }t        j                  |      }| j*                  r4t-        d	       t-        t        j.                  |             t-        d
       |S )Nzret-tmp)ctx)valuer   Noner   r   z---- Transformed code ----z---- ---------------- ----)r   bodyrL   r   popappendr   r   r   rX   rO   fix_missing_locationsr   rI   rR   rH   copydeepcopyrG   visitr1   r   r   unparse)r   codelastrettpltxr-   node_2s           r   visit_Modulez#ReplaceCodeTransformer.visit_Module  sU   ||K yy}dD!IIMMOIIVT)%A$B$**UV%%d+T)89C++C0C&)DLL#&)ii&7&<&<Q&?DLL##'99Z ''6]]3\\#!!"%**40::./#++f%&./r   c                 N   t        |j                  t              r{|j                  j                  | j                  v rY| j                  |j                  j                     6t        j                  | j                  |j                  j                           S | j                  |      S r   )rL   rX   r   r+   rI   r^   r_   r1   )r   exprs     r   
visit_Exprz!ReplaceCodeTransformer.visit_Expr<  sk    djj$'DJJMMT\\,I||DJJMM*6}}T\\$**--%@AA!!$''r   )NN)r?   r@   rA   r   rC   rD   r   r   r	   r   r
   r&   classmethodstrrT   rh   rk   r   r   r   rF   rF      sr    GTE4 TX

)1$
 OS

%-d^
 
N(r   rF   )rB   __skip_doctest__rO   r   r   r   r   r   r   r	   r^   typingr
   r   
mangle_allr   rF   r   r   r   <module>rq      sL   ob   I H H 
  ! M
:o :zD(_ D(r   