
    !.d4                        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mZ ddlm	Z	m
Z
mZmZ ej        dk    rddlmZ n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        Z ej        d           G d d                      Z e            dededefd            Zdedeeef         fdZdededefdZ dedeee
e         f         fdZ!dededefdZ"dedeee
e         f         fdZ#dedeee
e         f         fdZ$dede
e         defdZ%dej&        deej'                 fd Z(d!e
ej&                 de
e         fd"Z) ej        d           G d# d$                      Z* G d% d&ej+                  Z, ej        d           G d' d(                      Z- G d) d*ej+                  Z.dS )+z)Functions to process IPython magics with.    N)	lru_cache)DictListOptionalTuple)   
   )	TypeGuard)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                   $    e Zd ZU eed<   eed<   dS )ReplacementmasksrcN)__name__
__module____qualname__str__annotations__     9lib/python3.11/site-packages/black/handle_ipynb_magics.pyr   r   4   s"         
III	HHHHHr&   r   verbosequietreturnc                 d    	 dd l }dd l}dS # t          $ r | s|sd}t          |           Y dS w xY w)Nr   Tz}Skipping .ipynb files as Jupyter dependencies are not installed.
You can fix this by running ``pip install "black[jupyter]"``F)IPythontokenize_rtModuleNotFoundErrorr   )r(   r)   r,   r-   msgs        r'   "jupyter_dependencies_are_installedr0   :   sn     t     	% 	O  HHHuus    //r   c                     ddl m}m}m}  ||           }d} ||          D ]/\  }}|j        t
          v r|j        dk    r|j        dk    r||= d} |s| 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-   r3   r4   r5   nameTOKENS_TO_IGNOREr   )r   r3   r4   r5   tokenstrailing_semicolonidxtokens           r'   remove_trailing_semicolonr>   K   s      MLLLLLLLLL]3F((00  
U:))):%)s"2"2s!% Ez=  $&&r&   has_trailing_semicolonc                    |s| S ddl m}m}m}  ||           } ||          D ]6\  }}|j        t
          v r|                    |j        dz             ||<    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   r2   r7   )r   z{INTERNAL ERROR: Was not able to reinstate trailing semicolon. Please report a bug on https://github.com/psf/black/issues.  N)
r-   r3   r4   r5   r8   r9   _replacer   AssertionErrorr#   )r   r?   r3   r4   r5   r:   r<   r=   s           r'   put_trailing_semicolon_backrC   k   s     " 
LLLLLLLLLL]3F((00 	 	
U:)))nnSn99sL
 
 	 }}V$$%%%r&   c                    g }	 t          j        |            | |fS # t          $ r Y nw xY wddlm}  |            }|                    |           }t          |          \  }}||z  }|                    |          }t          |          \  }}t          |	                                          t          | 	                                          k    rt          ||z  }||fS )zMask IPython magics so content becomes parseable Python code.

    For example,

        %matplotlib inline
        'foo'

    becomes

        "25716f358c32750e"
        'foo'

    The replacements are returned, along with the transformed code.
    r   )TransformerManager)astparseSyntaxErrorIPython.core.inputtransformer2rE   transform_cellreplace_cell_magicsreplace_magicslen
splitlinesr   )r   replacementsrE   transformer_managertransformedcell_magic_replacementsmagic_replacementss          r'   	mask_cellrT      s    ')L!	# L       BAAAAA,,..%44S99K+>{+K+K(K(++L%44[AAK&4[&A&A#K#
;!!##$$CNN,<,<(=(===&&L$$s    
))magicc                 8   |sJ t          t          |          dz  dz
  d          }t          |          }d}|| v r1t          |          }|dz  }|dk    rt          d|           d|| v 1t          |          dz   t          |          k     r| d}d| d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   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.")maxrM   	TOKEN_HEXrB   )r   rU   nbytesr=   counters        r'   	get_tokenr`      s     LLLUq1$a((FfEG
3,,&!!1S== 7/47 7  		 3,, 5zzA~E

""u<<<r&   c                 0   g }t          j        |           }t                      }|                    |           |j        | |fS |j        j        }t          | |          }|                    t          ||                     | 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   
)
rF   rG   CellMagicFindervisit
cell_magicheaderr`   appendr   body)r   rO   treecell_magic_finderrg   r   s         r'   rK   rK      s    " ')L9S>>D'))D!!!#+L  )0FS&!!D6:::;;;99'2799<GGr&   c                 L   g }t                      }|                    t          j        |                      g }t	          |                                 d          D ]\  }}||j        v r|j        |         }t          |          dk    rt          d| d          |d         j	        |d         j
        }}t          | |          }	|                    t          |	|                     |d|         |	z   }|                    |           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.
    rX   )startz#Expecting one magic per line, got: z<
Please report a bug on https://github.com/psf/black/issues.r   rb   Nrc   )MagicFinderre   rF   rG   	enumeraterN   magicsrM   rB   
col_offsetrU   r`   rh   r   join)
r   rO   magic_findernew_srcsilineoffsets_and_magicsrq   rU   r   s
             r'   rL   rL      sJ   $ L==Lsy~~&&&HS^^--Q777  4###!-!4Q!7%&&!++$R:L R R R  
 #1%0"1%+ J S%((D5 A A ABBB$t+D99X,,r&   rO   c                 P    |D ]"}|                      |j        |j                  } #| S )zRemove replacements from cell.

    For example

        "9b20"
        foo = bar

    becomes

        %%time
        foo = bar
    )replacer   r   )r   rO   replacements      r'   unmask_cellr{     s2     $ = =kk+*KO<<Jr&   nodec                     t          | t          j                  oWt          | j        t          j                  o8t          | 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)
isinstancerF   	AttributevalueCallfuncNameid)r|   s    r'   _is_ipython_magicr     s\     	4'' 	0tz38,,	0tz11	0 JO-/	r&   argsc                     g }| D ]8}t          |t          j                  sJ |                    |j                   9|S N)r   rF   Strrh   s)r   str_argsargs      r'   _get_str_argsr   .  sJ    H  #sw'''''Or&   c                   V    e Zd ZU eed<   ee         ed<   eed<   edefd            ZdS )	CellMagicr8   paramsri   r*   c                 H    | j         rd| j         d| j          S d| j         S )Nz%% )r   r8   selfs    r'   rg   zCellMagic.header<  s6    ; 	21	11DK111DIr&   N)r    r!   r"   r#   r$   r   propertyrg   r%   r&   r'   r   r   6  s]         
IIISM
III        X     r&   r   c                   J    e Zd ZdZddee         ddfdZdej        ddfdZ	dS )	rd   a^  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
foo()

    would have been transformed to

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

    and we look for instances of the latter.
    Nrf   r*   c                     || _         d S r   )rf   )r   rf   s     r'   __init__zCellMagicFinder.__init__V  s    $r&   r|   c                 N   t          |j        t          j                  rpt	          |j        j                  rW|j        j        j        dk    rBt          |j        j                  }t          |d         |d         |d                   | _
        |                     |           dS )z)Find cell magic, extract header and body.run_cell_magicr   rX   rW   )r8   r   ri   N)r   r   rF   r   r   r   attrr   r   r   rf   generic_visit)r   r|   r   s      r'   
visit_ExprzCellMagicFinder.visit_ExprY  s     tz38,,	T!$*/22	T 
$(888 11D'T!WT!W4PQ7SSSDO4     r&   r   )
r    r!   r"   __doc__r   r   r   rF   Exprr   r%   r&   r'   rd   rd   D  sn         "% %8I#6 %$ % % % %	!sx 	!D 	! 	! 	! 	! 	! 	!r&   rd   c                   $    e Zd ZU eed<   eed<   dS )OffsetAndMagicrq   rU   N)r    r!   r"   intr$   r#   r%   r&   r'   r   r   e  s"         OOOJJJJJr&   r   c                   N    e Zd ZdZddZdej        ddfdZdej        ddfdZ	dS )	rn   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                 B    t          j        t                    | _        d S r   )collectionsdefaultdictlistrp   r   s    r'   r   zMagicFinder.__init__  s    7B7Nt7T7Tr&   r|   c                 L   t          |j        t          j                  rt	          |j        j                  rt          |j        j                  }|j        j        j        dk    rd|d          }nZ|j        j        j        dk    r"d|d          }|d         r|d|d          z  }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%rX   r   zUnexpected IPython magic zC found. Please report a bug on https://github.com/psf/black/issues.N)r   r   rF   r   r   r   r   r   r   rB   rp   linenorh   r   rq   r   r   r|   r   r   s       r'   visit_AssignzMagicFinder.visit_Assign  s1    dj#(++ 	0A$*/0R0R 	 11Dz#{22#$q'mm%)999#$q'mm7 )=tAw==(C$R
0D R R R   K
)*11tz4c::   	4     r&   c                    t          |j        t          j                  r%t	          |j        j                  rt          |j        j                  }|j        j        j        dk    rR|d         dk    rd|d          }n|d         dk    rd|d          }nkd|d          }|d         r|d	|d          z  }nI|j        j        j        d
k    rd|d          }n(|j        j        j        dk    rd|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?rX   pinfo2z??r   r   systemr   r   z!!N)r   r   rF   r   r   r   r   r   r   r   rp   r   rh   r   rq   r   r   s       r'   r   zMagicFinder.visit_Expr  s`   & dj#(++ 	0A$*/0R0R 	 11Dz#'7777g%%'d1g--CC!W(((tAw..CC'd1g--CAw -}47}},%11#$q'mm%44$47nn$$K
)*11tz4c::   	4     r&   )r*   N)
r    r!   r"   r   r   rF   Assignr   r   r   r%   r&   r'   rn   rn   m  s         $U U U U! ! ! ! ! !B'!sx '!D '! '! '! '! '! '!r&   rn   )/r   rF   r   dataclassessecretssys	functoolsr   typingr   r   r   r   version_infor
   typing_extensionsblack.outputr   black.reportr   	frozensetTRANSFORMED_MAGICSr9   PYTHON_CELL_MAGICS	token_hexr]   	dataclassr   boolr0   r#   r>   rC   rT   r`   rK   rL   r{   exprr   r   r   r   NodeVisitorrd   r   rn   r%   r&   r'   <module>r      s5   / / 



          



       . . . . . . . . . . . .w       ++++++       ' ' ' ' ' 'Y   9
 
  Y
 
  	 d###       $#
 4       '3 '5d+; ' ' ' '@&S &$ &3 & & & &0%%3 %%5d;&7!78 %% %% %% %%P3 s s    4HS HU3[0A+A%B H H H H>&- &-c4+<&< = &- &- &- &-RS [(9 c    $CH 3=)A    SX 49     d###	  	  	  	  	  	  	  $#	 ! ! ! ! !co ! ! !B d###       $#^! ^! ^! ^! ^!#/ ^! ^! ^! ^! ^!r&   