U
    EZh5|                     @   s  d dl Z d dlZd dlZd dlZd dlmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZmZmZmZm Z m!Z! d d	lm"Z# d d
lm$Z$ d dl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? dd	l@m"Z" ddlAmBZB ejCdkZDdZEdZFdddddddeEeFdddd dd!ee. eeG eeG eGeeH eIeIeGeGeIeeI eIeeeHef  eGeeeJ eJee gef d"d#d$ZKeG d%d& d&ZLeG d'd( d(ZMeG d)d* d*ZNeG d+d, d,ZOG d-d. d.e6ZPG d/d0 d0ZQeRd1kreKdd2 d dlZedd3d4d5ZSedd3d6d7ZTdd8d9d:ZUeU  dS );    N)	dataclassfield)islice)walk_tb)
ModuleTypeTracebackType)
AnyCallableDictIterableListOptionalSequenceTupleTypeUnion)guess_lexer_for_filename)CommentKeywordNameNumberOperatorString)Text)Token)ClassNotFound   )pretty)	loop_last)Columns)ConsoleConsoleOptionsConsoleRenderableRenderResultgroup)	Constrain)RegexHighlighterReprHighlighter)Panel)render_scope)Style)Syntax)Themewin32
   P   d   X      FT )consolewidth
code_widthextra_linestheme	word_wrapshow_localslocals_max_lengthlocals_max_stringlocals_hide_dunderlocals_hide_sunderindent_guidessuppress
max_frames)r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   returnc                    s   | dkrt ddn| jr(dkr(dntt ttt dd 	
fddtddfdd	}zt }|| tj	W S  t
k
r   tj	}t_	| Y S X dS )
a  Install a rich traceback handler.

    Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.


    Args:
        console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
        width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
        code_width (Optional[int], optional): Code width (in characters) of traceback. Defaults to 88.
        extra_lines (int, optional): Extra lines of code. Defaults to 3.
        theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
            a theme appropriate for the platform.
        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
        show_locals (bool, optional): Enable display of local variables. Defaults to False.
        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
            Defaults to 10.
        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
        locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
        locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.

    Returns:
        Callable: The previous exception handler that was replaced.

    NT)stderr)type_value	tracebackrB   c                    s8    tj| || 
t	d d S )Nr5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   )print	Tracebackfrom_exceptionbool)rD   rE   rF   )r6   r7   r?   r=   r>   r;   r<   rA   r:   r@   r8   traceback_consoler5   r9   r3   >/tmp/pip-unpacked-wheel-36xvkur8/pip/_vendor/rich/traceback.py
excepthookb   s(    zinstall.<locals>.excepthook)iprB   c                    sb   i j  ttd d fdd}ddtttd dfdd_|_ fd	d
_d S )N)argskwargsrB   c                     s   | | | dS )zEwrap the default ip.showtraceback to store info for ip._showtracebackNr3   rP   rQ   )default_showtracebacktb_datar3   rM   ipy_show_traceback   s    zCinstall.<locals>.ipy_excepthook_closure.<locals>.ipy_show_tracebackF)	is_syntax)rP   rV   rQ   rB   c                    st     }| rdn|d }dd}d|r2dnd}t|D ]}|dkrP qX|j}q@ |d |d | i dS )z2Internally called traceback from ip._showtracebackN   Zrunning_compiled_codeF	tb_offsetr   r   )Z_get_exc_infogetrangetb_next)rV   rP   rQ   Z	exc_tupletbZcompiledrX   _)rN   rO   rT   r3   rM   ipy_display_traceback   s    zFinstall.<locals>.ipy_excepthook_closure.<locals>.ipy_display_tracebackc                     s    | ddi|S )NrV   Tr3   rR   )r^   r3   rM   <lambda>   s   z9install.<locals>.ipy_excepthook_closure.<locals>.<lambda>)Zshowtracebackr   rK   Z_showtracebackZshowsyntaxerror)rO   rU   )rN   )rS   rO   r^   rT   rM   ipy_excepthook_closure|   s      z'install.<locals>.ipy_excepthook_closure)r    Z
is_jupyterr   BaseExceptionr   r   r   Zget_ipythonsysrN   	Exception)r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   r`   rO   old_excepthookr3   )r6   rN   r7   r?   r=   r>   r;   r<   rA   r:   r@   r8   rL   r5   r9   rM   install/   s*    +*)re   c                   @   st   e Zd ZU eed< eed< eed< dZeed< dZee	ee
jf  ed< dZeeeeef eeef f  ed< dS )	Framefilenamelinenoname lineNlocalslast_instruction)__name__
__module____qualname__str__annotations__intrk   rl   r   r
   r   Noderm   r   r3   r3   r3   rM   rf      s   
rf   c                   @   s6   e Zd ZU eed< eed< eed< eed< eed< dS )_SyntaxErroroffsetrg   rk   rh   msgN)rn   ro   rp   rs   rr   rq   r3   r3   r3   rM   ru      s
   
ru   c                   @   sP   e Zd ZU eed< eed< dZee ed< dZe	ed< e
edZee ed< dS )	Stackexc_type	exc_valueNsyntax_errorFis_cause)default_factoryframes)rn   ro   rp   rq   rr   r{   r   ru   r|   rK   r   listr~   r   rf   r3   r3   r3   rM   rx      s
   
rx   c                   @   s   e Zd ZU ee ed< dS )TracestacksN)rn   ro   rp   r   rx   rr   r3   r3   r3   rM   r      s   
r   c                   @   s   e Zd ZdgZdS )PathHighlighterz(?P<dim>.*/)(?P<bold>.+)N)rn   ro   rp   Z
highlightsr3   r3   r3   rM   r      s   r   c                   @   s  e Zd ZdZddddddZd%dd	d
dddeeddddddee ee	 ee	 e	ee
 eee	e	eeeeee
ef  e	dddZedd	d
dddeeddddddee eee ee	 ee	 e	ee
 eee	e	eeeeee
ef  e	d dddZedeedddee eee ee	e	eeed	ddZeeedddZe eedddZee
e
e
dd d!Ze eed"d#d$Z dS )&rI   a  A Console renderable that renders a traceback.

    Args:
        trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
            the last exception.
        width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
        code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
        extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
        theme (str, optional): Override pygments theme used in traceback.
        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
        show_locals (bool, optional): Enable display of local variables. Defaults to False.
        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
            Defaults to 10.
        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
        locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
        locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
        max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

    textpythonZcythonZpyrex)rj   z.pyz.pxdz.pyxz.pxiNr0   r1   r2   FTr3   rG   )tracer5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   c                C   s  |d krHt  \}}}|d ks.|d ks.|d kr6td| j||||d}|| _|| _|| _|| _t	|pjd| _
|| _|| _|| _|| _|	| _|
| _|| _g | _|D ]Z}t|ts|jd k	st|dtj|j}n|}tjtj|}| j| q|dkrtd|nd| _d S )Nz9Value for 'trace' required if not called in except: blockr:   Z	ansi_darkz+ must be a module with '__file__' attributer      )rb   exc_info
ValueErrorextractr   r5   r6   r7   r+   Z	get_themer8   r9   r:   r?   r;   r<   r=   r>   r@   
isinstancerq   __file__AssertionErrorospathdirnamenormpathabspathappendmaxrA   )selfr   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   ry   rz   rF   Zsuppress_entityr   r3   r3   rM   __init__   sH       
zTraceback.__init__)ry   rz   rF   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   c                C   s>   | j ||||	|
|||d}| |||||||	||
|||||dS )a  Create a traceback from exception info

        Args:
            exc_type (Type[BaseException]): Exception type.
            exc_value (BaseException): Exception value.
            traceback (TracebackType): Python Traceback object.
            width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
            code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
            theme (str, optional): Override pygments theme used in traceback.
            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
            show_locals (bool, optional): Enable display of local variables. Defaults to False.
            indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
                Defaults to 10.
            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
            locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
            locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
            suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
            max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

        Returns:
            Traceback: A Traceback instance that may be printed.
        r:   r;   r<   r=   r>   )r5   r6   r7   r8   r9   r:   r?   r;   r<   r=   r>   r@   rA   )r   )clsry   rz   rF   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   Zrich_tracebackr3   r3   rM   rJ   *  s4    -zTraceback.from_exceptionr   )	ry   rz   rF   r:   r;   r<   r=   r>   rB   c             	      sV  g }	d}
ddl m} ttddd}t||j|||
d}t|trtt|j	pPd|j
pXd|jp`d|jphd	|jd
|_|	| |jj}ttttf  ttttf  d fdd}t|D ]*\}}|jj}d}tjdkrF|jd }tt|j ||d }|\}}}}|dk	rF|dk	rF|dk	rF|dk	rF||f||ff}|rt|dsttj |sttj!||}|j"#ddrqt$|pd||jj%|rfdd||j"& D nd|d}|| |j"#ddr|jdd= qt'|dd}|r|j(}|}|j)}d}
q$|j*}|rHt'|ddsH|j(}|}|j)}d}
q$qHq$t+|	d}|S )a  Extract traceback information.

        Args:
            exc_type (Type[BaseException]): Exception type.
            exc_value (BaseException): Exception value.
            traceback (TracebackType): Python Traceback object.
            show_locals (bool, optional): Enable display of local variables. Defaults to False.
            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
                Defaults to 10.
            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
            locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
            locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.

        Returns:
            Trace: A Trace instance which you can use to construct a `Traceback`.
        Fr   )_IMPORT_CWD)_objectrB   c                 S   s&   z
t | W S  tk
r    Y dS X dS )z1Don't allow exceptions from __str__ to propagate.z<exception str() failed>N)rq   rc   )r   r3   r3   rM   safe_str  s    
z#Traceback.extract.<locals>.safe_str)ry   rz   r|   ?rj   )rv   rg   rh   rk   rw   )iter_localsrB   c                 3   sR    ss| E dH  dS | D ]2\}} r2| dr2qrB| drBq||fV  qdS )z-Extract locals from an iterator of key pairs.N__r]   
startswith)r   keyrE   )r=   r>   r3   rM   
get_locals  s    
z%Traceback.extract.<locals>.get_localsN)r2      rW   r   <Z_rich_traceback_omitc                    s6   i | ].\}}t |st |s|tj| d qS ))
max_length
max_string)inspect
isfunctionisclassr   Ztraverse).0r   rE   )r;   r<   r3   rM   
<dictcomp>  s   
 
 z%Traceback.extract.<locals>.<dictcomp>)rg   rh   ri   rl   rm   _rich_traceback_guard	__cause__T__suppress_context__)r   ),Zpip._vendor.richr   r   rq   rx   rn   r   SyntaxErrorru   rv   rg   rh   r   rw   r{   r   r~   r   r   objectr   f_codeco_filenamerb   version_infof_lastinextr   Zco_positionsr   r   r   isabsjoinf_localsrY   rf   co_nameitemsgetattr	__class____traceback____context__r   )r   ry   rz   rF   r:   r;   r<   r=   r>   r   r|   r   r   stackr   r   frame_summaryZline_norg   rm   Zinstruction_indexZinstruction_positionZ
start_lineZend_lineZstart_columnZ
end_columnframecauser   r3   )r=   r>   r;   r<   rM   r   s  s    




zTraceback.extract)r4   optionsrB   c                 c   s  | j }| }|j}t|t|t|t|tj|t	|t
tdd |t|ttdd |t	|tj|tj|tj|tj|t|t|tjtdd ddd}t }tt| jjD ]$\}}	|	jrt| |	d|ddd	d
}
t|
| j}
|| |
V  W 5 Q R X |	jd k	r||. tt| |	j|ddd	| jd| jV  W 5 Q R X t|	j ddf||	jj V  n>|	j!rt|	j ddf||	j!V  nt|	j dfV  |s|	j"rt#dV  qt#dV  qd S )NT)Zdim)Zbold)r   pygments.textpygments.stringpygments.functionpygments.numberzrepr.indentzrepr.strz
repr.bracezrepr.numberzrepr.bool_truezrepr.bool_falsez	repr.nonezscope.borderzscope.equalsz	scope.keyzscope.key.specialF)Zinheritz7[traceback.title]Traceback [dim](most recent call last)ztraceback.border)r   r   )titlestyleborder_styleexpandpaddingztraceback.border.syntax_error)r   r   r   r   r5   z: ztraceback.exc_typezI
[i]The above exception was the direct cause of the following exception:
zH
[i]During handling of the above exception, another exception occurred:
)$r8   Zget_background_styleZget_style_for_tokenr,   	TextTokenr   r   r   ZFunctionr   r   r*   r   ConstantZ	Delimiterr   r'   r   reversedr   r   r~   r(   _render_stackr%   r5   Z	use_themer{   _render_syntax_errorr   assemblery   rw   rz   r|   from_markup)r   r4   r   r8   Zbackground_styleZtoken_styleZtraceback_themehighlighterlastr   Zstack_renderabler3   r3   rM   __rich_console__  s    

zTraceback.__rich_console__)r{   rB   c                 c   s   t  }t }|jdkrVtj|jrVtjd|j dfdt|j	dfdd}||V  ||j
 }d|_t|jd	 t|}|d
|| |tjdd|  d dd7 }|V  d S )Nz<stdin> r   :r   r   r   r   Tr   zbold underline
u   [traceback.offset]▲[/])r'   r   rg   r   r   existsr   r   rq   rh   rk   rstripZno_wrapminrv   lenZstylizer   )r   r{   r   path_highlighterr   Zsyntax_error_textrv   r3   r3   rM   r   _  s(    

zTraceback._render_syntax_error)rg   coderB   c                 C   s   t j|d }|sP|d}|dkr2|d | n|}|drPd| krPdS z| j|pht||j	W S  t
k
r   Y dS X d S )Nr   z#!r   r   )r   r   splitextindexr   lowerLEXERSrY   r   ri   r   )r   rg   r   extZnew_line_index
first_liner3   r3   rM   _guess_lexerv  s    
zTraceback._guess_lexer)r   rB   c                 #   s  t  }j}ttddd}ttt dfdd}d }jdkrbtjd t|j	jd  }d	}t
|j	D ]
\}}	|r||krd
}qp|r|d k	sttdt| ddddV  d	}|dk}
|	j t fddjD }tj|	jr(tj|t|	jdddt|	jdfd|	jdfdd}n$tjd|	jdfdt|	jdfdd}|	jdsf|
sfdV  |V  |	jdr||	E d H  qp|spzf||	j}|sW qp|	j|}t|||d
|	jj |	jj f|	jhjjjd	d
}dV  W n: tk
r. } ztd| dfV  W 5 d }~X Y qpX |	jd k	rX|	j\}}|jd||d
d |	j rvt!|f||	d d!n|V  qpd S )"N)rg   rB   c                 S   s   d t| S )zRead files, and cache results on filename.

            Args:
                filename (str): Filename to read

            Returns:
                str: Contents of file
            rj   )r   	linecachegetlines)rg   r3   r3   rM   	read_code  s    	z*Traceback._render_stack.<locals>.read_code)r   rB   c                 3   s&   | j r"t| j d j j jdV  d S )Nrl   )r   r?   r   r   )rl   r)   r?   r;   r<   )r   )r   r3   rM   render_locals  s    z.Traceback._render_stack.<locals>.render_localsr   rW   FTz
... z frames hidden ...centerztraceback.error)Zjustifyr   c                 3   s   | ]}  |V  qd S )Nr   )r   r   )frame_filenamer3   rM   	<genexpr>  s     z*Traceback._render_stack.<locals>.<genexpr>r   r   r   r   z in r   r   zin r   rj   )r8   Zline_numbersZ
line_rangeZhighlight_linesr9   r6   r?   dedentr   ztraceback.error_range)r   startendZstyle_beforer   )r   )"r   r8   rq   rf   r   r"   rA   rZ   r   r~   	enumerater   r   rg   anyr@   r   r   r   r   rh   ri   r   r   r+   r7   r9   r6   r?   rc   rm   Zstylize_rangerl   r   )r   r   r   r8   r   r   Zexclude_framesZexcludedZframe_indexr   firstZ
suppressedr   r   Z
lexer_namesyntaxerrorr   r   r3   )r   r   rM   r     s    

	




zTraceback._render_stack)N)!rn   ro   rp   __doc__r   LOCALS_MAX_LENGTHLOCALS_MAX_STRINGr   r   rs   rq   rK   r   r   r   r   classmethodr   r   ra   r   rJ   r   r    r!   r#   r   r$   ru   r   r   rx   r   r3   r3   r3   rM   rI      s   
 5H  NrI   __main__r   )arB   c                 C   s   d}t ||   d S )Nr   )rH   )r   Zoner3   r3   rM   bar  s    r   c                 C   s"   d}ddddhdd}t |  d S )NTzPaul AtreideszVladimir HarkonnenzThufir HawatzDuncan Idaho)NFT)
charactersZatomic_types)r   )r   r   Zzedr3   r3   rM   foo  s    	r  )rB   c                   C   s   t d d S )Nr   )r  r3   r3   r3   rM   r     s    r   )Vr   r   r   rb   Zdataclassesr   r   	itertoolsr   rF   r   typesr   r   typingr   r	   r
   r   r   r   r   r   r   r   Zpip._vendor.pygments.lexersr   Zpip._vendor.pygments.tokenr   r   r   r   r   r   r   r   r   Zpip._vendor.pygments.utilr   rj   r   Z_loopr   columnsr   r4   r    r!   r"   r#   r$   Z	constrainr%   r   r&   r'   Zpanelr(   Zscoper)   r   r*   r   r+   r   r8   r,   platformWINDOWSr   r   rs   rq   rK   ra   re   rf   ru   rx   r   r   rI   rn   r   r  r   r3   r3   r3   rM   <module>   s   0 
 	    1

