o
    ^i<                     @   sn  d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ejdkr8ddlmZ nddlmZ ddlmZ dd	lmZ dd
lmZ edZedZedZejddG dd dZededefddZdededdfddZdede eef fddZ!dededefddZ"dede ee#e f fdd Z$d!e%defd"d#Z&ded$edefd%d&Z'dede ee#e f fd'd(Z(dede ee#e f fd)d*Z)ded+e#e defd,d-Z*dedefd.d/Z+d0ej,deej- fd1d2Z.d3e#ej, de#e fd4d5Z/ejddG d6d7 d7Z0G d8d9 d9ej1Z2ejddG d:d; d;Z3G d<d= d=ej1Z4dS )>z)Functions to process IPython magics with.    N)	lru_cache)	find_spec)Optional)   
   )	TypeGuard)Mode)out)NothingChanged)zget_ipython().run_cell_magiczget_ipython().systemzget_ipython().getoutputzget_ipython().run_line_magic)	ENDMARKERNLNEWLINECOMMENTDEDENTUNIMPORTANT_WS
ESCAPED_NL)captureprunpypypythonpython3timetimeitT)frozenc                   @   s   e Zd ZU eed< eed< dS )ReplacementmasksrcN)__name__
__module____qualname__str__annotations__ r"   r"   ^/var/www/html/stock_analysis/be/venv/lib/python3.10/site-packages/black/handle_ipynb_magics.pyr   0      
 r   warnreturnc                 C   s0   t dd uot dd u}|s| rd}t| |S )Ntokenize_rtIPythonz}Skipping .ipynb files as Jupyter dependencies are not installed.
You can fix this by running ``pip install "black[jupyter]"``)r   r	   )r%   	installedmsgr"   r"   r#   "jupyter_dependencies_are_installed6   s   r+   r   modec                    sZ   t  fddtD rtt }|dr)|jddd dd t|jB vr+tdS dS )	a  Check that cell does not already contain TransformerManager transformations,
    or non-Python cell magics, which might cause tokenizer_rt to break because of
    indentations.

    If a cell contains ``!ls``, then it'll be transformed to
    ``get_ipython().system('ls')``. However, if the cell originally contained
    ``get_ipython().system('ls')``, then it would get transformed in the same way:

        >>> TransformerManager().transform_cell("get_ipython().system('ls')")
        "get_ipython().system('ls')\n"
        >>> TransformerManager().transform_cell("!ls")
        "get_ipython().system('ls')\n"

    Due to the impossibility of safely roundtripping in such situations, cells
    containing transformed magics will be ignored.
    c                 3   s    | ]}| v V  qd S Nr"   ).0transformed_magicr   r"   r#   	<genexpr>U   s    z validate_cell.<locals>.<genexpr>%%   )maxsplitr      N)anyTRANSFORMED_MAGICSr
   _get_code_start
startswithsplitPYTHON_CELL_MAGICSpython_cell_magics)r   r,   liner"   r0   r#   validate_cellD   s   
r>   c                 C   st   ddl m}m}m} || }d}||D ]\}}|jtv rq|jdkr-|jdkr-||= d} |s4| dfS ||dfS )a  Remove trailing semicolon from Jupyter notebook cell.

    For example,

        fig, ax = plt.subplots()
        ax.plot(x_data, y_data);  # plot data

    would become

        fig, ax = plt.subplots()
        ax.plot(x_data, y_data)  # plot data

    Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses
    ``tokenize_rt`` so that round-tripping works fine.
    r   reversed_enumeratesrc_to_tokenstokens_to_srcFOP;T)r'   r@   rA   rB   nameTOKENS_TO_IGNOREr   )r   r@   rA   rB   tokenstrailing_semicolonidxtokenr"   r"   r#   remove_trailing_semicolon`   s   
rK   has_trailing_semicolonc                 C   sp   |s| S ddl m}m}m} || }||D ]\}}|jtv r q|j|jd d||<  ntddt	||S )zPut trailing semicolon back if cell originally had it.

    Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses
    ``tokenize_rt`` so that round-tripping works fine.
    r   r?   rD   r0   z{INTERNAL ERROR: Was not able to reinstate trailing semicolon. Please report a bug on https://github.com/psf/black/issues.  N)
r'   r@   rA   rB   rE   rF   _replacer   AssertionErrorr    )r   rL   r@   rA   rB   rG   rI   rJ   r"   r"   r#   put_trailing_semicolon_back   s   
rO   c                 C   s   g }z
t |  W | |fS  ty   Y nw ddlm} | }|| }t|\}}||7 }||}t|\}}t|	 
 t| 	 
 krKt||7 }||fS )zMask IPython magics so content becomes parseable Python code.

    For example,

        %matplotlib inline
        'foo'

    becomes

        b"25716f358c32750"
        'foo'

    The replacements are returned, along with the transformed code.
    r   )TransformerManager)astparseSyntaxErrorIPython.core.inputtransformer2rP   transform_cellreplace_cell_magicsreplace_magicslenstrip
splitlinesr
   )r   replacementsrP   transformer_managertransformedcell_magic_replacementsmagic_replacementsr"   r"   r#   	mask_cell   s$   

 r`   n_charsc                 C   sP   | dksJ t | d d d}t|}t|d | kr"|dd }d| dS )	zBCreate a randomly generated token that is n_chars characters long.r   r5   r3   r   Nzb"")maxsecrets	token_hexrX   )ra   n_bytesrJ   r"   r"   r#   create_token   s   
rh   magicc                 C   sX   |sJ t |}t|}d}|| v r*t|}|d7 }|dkr&td| d|| v s|S )aD  Return randomly generated token to mask IPython magic with.

    For example, if 'magic' was `%matplotlib inline`, then a possible
    token to mask it with would be `"43fdd17f7e5ddc83"`. The token
    will be the same length as the magic, and we make sure that it was
    not already present anywhere else in the cell.
    r   r3   d   zINTERNAL ERROR: Black was not able to replace IPython magic. Please report a bug on https://github.com/psf/black/issues.  The magic might be helpful: N)rX   rh   rN   )r   ri   ra   rJ   counterr"   r"   r#   	get_token   s"   	rl   c                 C   sj   g }t | }t }|| |jdu r| |fS |jj}t| |}|t||d | d|jj	 |fS )aN  Replace cell magic with token.

    Note that 'src' will already have been processed by IPython's
    TransformerManager().transform_cell.

    Example,

        get_ipython().run_cell_magic('t', '-n1', 'ls =!ls\n')

    becomes

        "a794."
        ls =!ls

    The replacement, along with the transformed code, is returned.
    Nr   r   
)
rQ   rR   CellMagicFindervisit
cell_magicheaderrl   appendr   body)r   r[   treecell_magic_finderrr   r   r"   r"   r#   rV      s   



rV   c           
      C   s   g }t  }|t|  g }t| dddD ]B\}}||jv rU|j| }t|dkr4td| d|d j	|d j
}}t| |}	|t|	|d |d| |	 }|| qd||fS )	ao  Replace magics within body of cell.

    Note that 'src' will already have been processed by IPython's
    TransformerManager().transform_cell.

    Example, this

        get_ipython().run_line_magic('matplotlib', 'inline')
        'foo'

    becomes

        "5e67db56d490fd39"
        'foo'

    The replacement, along with the transformed code, are returned.
    rn   r3   )startz#Expecting one magic per line, got: z<
Please report a bug on https://github.com/psf/black/issues.r   rm   N)MagicFinderrp   rQ   rR   	enumerater:   magicsrX   rN   
col_offsetri   rl   rs   r   join)
r   r[   magic_findernew_srcsir=   offsets_and_magicsr{   ri   r   r"   r"   r#   rW     s&   



rW   r[   c                 C   s   |D ]
}|  |j|j} q| S )zRemove replacements from cell.

    For example

        "9b20"
        foo = bar

    becomes

        %%time
        foo = bar
    )replacer   r   )r   r[   replacementr"   r"   r#   unmask_cell.  s   r   c                 C   s:   t d| D ]}|d }|r|ds|  S qdS )a0  Provides the first line where the code starts.

    Iterates over lines of code until it finds the first line that doesn't
    contain only empty spaces and comments. It removes any empty spaces at the
    start of the line and returns it. If such line doesn't exist, it returns an
    empty string.
    z.+r   # )refinditergrouplstripr9   )r   matchr=   r"   r"   r#   r8   @  s   r8   nodec                 C   s8   t | tjot | jtjot | jjtjo| jjjdkS )zCheck if attribute is IPython magic.

    Note that the source of the abstract syntax tree
    will already have been processed by IPython's
    TransformerManager().transform_cell.
    get_ipython)
isinstancerQ   	AttributevalueCallfuncNameid)r   r"   r"   r#   _is_ipython_magicO  s   r   argsc                 C   s:   g }| D ]}t |tjrt |jtsJ ||j q|S r-   )r   rQ   Constantr   r    rs   )r   str_argsargr"   r"   r#   _get_str_args^  s
   r   c                   @   s<   e Zd ZU eed< ee ed< eed< edefddZdS )	CellMagicrE   paramsrt   r&   c                 C   s&   | j rd| j d| j  S d| j S )Nr2    )r   rE   selfr"   r"   r#   rr   l  s   zCellMagic.headerN)r   r   r   r    r!   r   propertyrr   r"   r"   r"   r#   r   f  s   
 r   c                   @   s<   e Zd ZdZd
dee ddfddZdejddfdd	Z	dS )ro   ah  Find cell magics.

    Note that the source of the abstract syntax tree
    will already have been processed by IPython's
    TransformerManager().transform_cell.

    For example,

        %%time\n
        foo()

    would have been transformed to

        get_ipython().run_cell_magic('time', '', 'foo()\n')

    and we look for instances of the latter.
    Nrq   r&   c                 C   s
   || _ d S r-   )rq   )r   rq   r"   r"   r#   __init__  s   
zCellMagicFinder.__init__r   c                 C   s^   t |jtjr(t|jjr(|jjjdkr(t|jj}t	|d |d |d d| _
| | dS )z)Find cell magic, extract header and body.run_cell_magicr   r3   r5   )rE   r   rt   N)r   r   rQ   r   r   r   attrr   r   r   rq   generic_visit)r   r   r   r"   r"   r#   
visit_Expr  s   
zCellMagicFinder.visit_Exprr-   )
r   r   r   __doc__r   r   r   rQ   Exprr   r"   r"   r"   r#   ro   t  s    ro   c                   @   s   e Zd ZU eed< eed< dS )OffsetAndMagicr{   ri   N)r   r   r   intr!   r    r"   r"   r"   r#   r     r$   r   c                   @   sB   e Zd ZdZdddZdejddfddZdejddfd	d
Z	dS )rx   a  Visit cell to look for get_ipython calls.

    Note that the source of the abstract syntax tree
    will already have been processed by IPython's
    TransformerManager().transform_cell.

    For example,

        %matplotlib inline

    would have been transformed to

        get_ipython().run_line_magic('matplotlib', 'inline')

    and we look for instances of the latter (and likewise for other
    types of magics).
    r&   Nc                 C   s   t t| _d S r-   )collectionsdefaultdictlistrz   r   r"   r"   r#   r     s   zMagicFinder.__init__r   c                 C   s   t |jtjrYt|jjrYt|jj}|jjjdkr"d|d  }n(|jjjdkr>d|d  }|d r=|d|d  7 }nt	d|jjjd	d
| j
|jj t|jj| | | d
S )a{  Look for system assign magics.

        For example,

            black_version = !black --version
            env = %env var

        would have been (respectively) transformed to

            black_version = get_ipython().getoutput('black --version')
            env = get_ipython().run_line_magic('env', 'var')

        and we look for instances of any of the latter.
        	getoutput!r   run_line_magic%r3   r   zUnexpected IPython magic zC found. Please report a bug on https://github.com/psf/black/issues.N)r   r   rQ   r   r   r   r   r   r   rN   rz   linenors   r   r{   r   r   r   r   r   r"   r"   r#   visit_Assign  s$   zMagicFinder.visit_Assignc                 C   s  t |jtjrzt|jjrzt|jj}|jjjdkrK|d dkr(d|d  }nC|d dkr6d|d  }n5d|d  }|d rJ|d	|d  7 }n |jjjd
krZd|d  }n|jjjdkrid|d  }nt	| j
|jj t|jj| | | dS )a  Look for magics in body of cell.

        For examples,

            !ls
            !!ls
            ?ls
            ??ls

        would (respectively) get transformed to

            get_ipython().system('ls')
            get_ipython().getoutput('ls')
            get_ipython().run_line_magic('pinfo', 'ls')
            get_ipython().run_line_magic('pinfo2', 'ls')

        and we look for instances of any of the latter.
        r   r   pinfo?r3   pinfo2z??r   r   systemr   r   z!!N)r   r   rQ   r   r   r   r   r   r   r
   rz   r   rs   r   r{   r   r   r"   r"   r#   r     s(   zMagicFinder.visit_Expr)r&   N)
r   r   r   r   r   rQ   Assignr   r   r   r"   r"   r"   r#   rx     s
    
!rx   )5r   rQ   r   dataclassesr   re   sys	functoolsr   importlib.utilr   typingr   version_infor   typing_extensions
black.moder   black.outputr	   black.reportr
   	frozensetr7   rF   r;   	dataclassr   boolr+   r    r>   tuplerK   rO   r   r`   r   rh   rl   rV   rW   r   r8   exprr   r   r   r   NodeVisitorro   r   rx   r"   r"   r"   r#   <module>   sR    
	
 *)

"