U
    P|jøY  ã                   @  sb  d Z ddlm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 ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ ededef d�ZdadZG dd„ deƒZd,dd„ZdZG dd„ deƒZdd„ Z G dd„ dƒZ!G dd„ dƒZ"G dd„ dƒZ#g Z$dddœd d!„Z%G d"d#„ d#e&ƒZ'd$d%„ Z(d&Z)dddd'e'j*fd(d)„Z+d*d+„ Z,dS )-z9
Asynchronous-friendly error mechanism.

See L{Failure}.
é    )ÚannotationsN)Úpartial)Úgetmro)ÚStringIO)ÚCallableÚNoReturnÚTypeVar)ÚVersion)Úreflect)ÚdeprecatedPropertyÚ_T_Callable.)Úboundé   c                   @  s   e Zd ZdS )ÚDefaultExceptionN)Ú__name__Ú
__module__Ú__qualname__© r   r   ú:/tmp/pip-unpacked-wheel-audpp6lv/twisted/python/failure.pyr   &   s   r   Údefaultc              	   C  sv  |dkrt d|f ƒ‚|}|dkrT| D ](\}}}}}||› d|› d|› d�ƒ q&�n|dkr¦| D ]B\}}}}}|d|› d|› d	|› d�ƒ |d
t ||¡ ¡  ƒ q`nÌ|dkrÞ| D ] \}}}}}|d|||f ƒ q²|dƒ n”|dk�rr| D ]„\}}}}}|d|||f ƒ |dƒ |D ]$\}	}
|d|	› dt|
ƒ› d�ƒ �q|dƒ |D ]$\}	}
|d|	› dt|
ƒ› d�ƒ �qJqìdS )a˜  
    Format and write frames.

    @param frames: is a list of frames as used by Failure.frames, with
        each frame being a list of
        (funcName, fileName, lineNumber, locals.items(), globals.items())
    @type frames: list
    @param write: this will be called with formatted strings.
    @type write: callable
    @param detail: Four detail levels are available:
        default, brief, verbose, and verbose-vars-not-captured.
        C{Failure.printDetailedTraceback} uses the latter when the caller asks
        for verbose, but no vars were captured, so that an explicit warning
        about the missing data is shown.
    @type detail: string
    )r   ÚbriefÚverboseúverbose-vars-not-capturedzNDetail must be default, brief, verbose, or verbose-vars-not-captured. (not %r)r   ú:Ú
r   z  File "z", line z, in z    %s
r   z%s:%d: %s(...)
zA [Capture of Locals and Globals disabled (use captureVars=True)]
r   z [ Locals ]
z  z : z ( Globals )
N)Ú
ValueErrorÚ	linecacheÚgetlineÚstripÚrepr)ÚframesÚwriteÚdetailÚwÚmethodÚfilenameÚlinenoZ	localVarsZ
globalVarsÚnameÚvalr   r   r   Úformat_frames*   s6    ÿÿ 

r)   z--- <exception caught here> ---c                   @  s   e Zd ZdZdS )ÚNoCurrentExceptionErrorzŠ
    Raised when trying to create a Failure from the current interpreter
    exception state and there is no current exception state.
    N)r   r   r   Ú__doc__r   r   r   r   r*   \   s   r*   c                 C  sb   t | ƒdkstdƒ‚d}t| d |ƒ}t|ƒ }}| dd… D ]}t||ƒ}t|ƒ|_|j}q>|S )zæ
    Construct a fake traceback object using a list of frames.

    It should have the same API as stdlib to allow interaction with
    other tools.

    @param tbFrames: [(methodname, filename, lineno, locals, globals), ...]
    r   zMust pass some framesNé   )ÚlenÚAssertionErrorÚ_FrameÚ_TracebackFrameÚtb_next)ZtbFramesÚstackZfirstTbÚtbZsfr   r   r   Ú
_Tracebackc   s    	

r4   c                   @  s   e Zd ZdZdd„ ZdS )r0   zq
    Fake traceback object which can be passed to functions in the standard
    library L{traceback} module.
    c                 C  s    || _ |j| _|j| _d| _dS )z-
        @param frame: _Frame object
        N)Útb_frameÚf_linenoÚ	tb_linenoÚf_lastiÚtb_lastir1   )ÚselfÚframer   r   r   Ú__init__Š   s    z_TracebackFrame.__init__N©r   r   r   r+   r<   r   r   r   r   r0   „   s   r0   c                   @  s   e Zd ZdZdd„ ZdS )r/   aD  
    A fake frame object, used by L{_Traceback}.

    @ivar f_code: fake L{code<types.CodeType>} object
    @ivar f_lineno: line number
    @ivar f_globals: fake f_globals dictionary (usually empty)
    @ivar f_locals: fake f_locals dictionary (usually empty)
    @ivar f_back: previous stack frame (towards the caller)
    c                 C  s`   |\}}}}}t ||ƒ| _|| _t|p(i ƒ| _t|p6i ƒ| _|| _d| _tt	ƒ 
¡ | _d| _dS )z¢
        @param frameinfo: (methodname, filename, lineno, locals, globals)
        @param back: previous (older) stack frame
        @type back: C{frame}
        r   N)Ú_CodeÚf_coder6   ÚdictÚ	f_globalsÚf_localsÚf_backr8   ÚvarsÚbuiltinsÚcopyÚ
f_builtinsÚf_trace)r:   Ú	frameinfoÚbackr'   r%   r&   ÚlocalzÚglobalzr   r   r   r<   Ÿ   s    z_Frame.__init__Nr=   r   r   r   r   r/   ”   s   
r/   c                   @  s    e Zd ZdZdd„ Zdd„ ZdS )r>   zÉ
    A fake code object, used by L{_Traceback} via L{_Frame}.

    It is intended to have the same API as the stdlib code type to allow
    interoperation with other tools based on that interface.
    c                 C  sd   || _ || _d| _d| _d| _g | _d| _d| _d| _d| _	d| _
d| _d| _d| _d| _d| _d S )Nó    r   r   )Úco_nameÚco_filenameÚ	co_lnotabÚco_firstlinenoÚco_argcountÚco_varnamesÚco_codeÚco_cellvarsÚ	co_constsÚco_flagsÚco_freevarsÚco_posonlyargcountÚco_kwonlyargcountÚco_namesÚ
co_nlocalsÚco_stacksize)r:   r'   r%   r   r   r   r<   ¸   s     z_Code.__init__c                 C  s   dS )N))NNNNr   ©r:   r   r   r   Úco_positionsÊ   s    z_Code.co_positionsN)r   r   r   r+   r<   r_   r   r   r   r   r>   °   s   r>   )ÚfÚreturnc                 C  s   t  | j¡ | S )a  
    Mark the given callable as extraneous to inlineCallbacks exception
    reporting; don't show these functions.

    @param f: a function that you NEVER WANT TO SEE AGAIN in ANY TRACEBACK
        reported by Failure.

    @type f: function

    @return: f
    )Ú_inlineCallbacksExtraneousÚappendÚ__code__)r`   r   r   r   Ú_extraneousÑ   s    re   c                   @  sV  e Zd ZdZdZdZdAdd„Zedd„ ƒZej	d	d„ ƒZe
ed
dddƒƒdd„ ƒZej	dd„ ƒZedd„ ƒZej	dd„ ƒZdd„ Zedd dœdd„ƒZdd„ Zdd„ Zddœdd „Zed!d"„ ƒZd#dœd$d%„Zd#dœd&d'„Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd#dœd2d3„Zd#dœd4d5„ZdBd7d#d#d8œd9d:„ZdCd;d<„Z dDd=d>„Z!dEd?d@„Z"dS )FÚFailureaÉ  
    A basic abstraction for an error that has occurred.

    This is necessary because Python's built-in error mechanisms are
    inconvenient for asynchronous communication.

    The C{frame} attribute contain the traceback frames.  Each frame is a tuple
    of (funcName, fileName, lineNumber, localsItems, globalsItems), where
    localsItems and globalsItems are the contents of
    C{locals().items()}/C{globals().items()} for that frame, or an empty tuple
    if those details were not captured.

    Local/global variables in C{frame} will only be captured if
    C{captureVars=True} when constructing the L{Failure}.

    @ivar value: The exception instance responsible for this failure.

    @ivar type: The exception's class.

    @ivar stack: Deprecated, always an empty list.  Equivalent information can
        be extracted from C{import traceback;
        traceback.extract_stack(your_failure.tb)}

    @ivar frames: list of frames, innermost first.
    r   NFc                 C  sØ   t d a t | _ d | _ | _}|| _|dkrPt ¡ \| _| _}| jdkrŠtƒ ‚n:|dkr~t|tƒrl|j	| _n
t|ƒ| _|| _n|| _|| _t| jt
ƒr¦|  | j¡ dS |dkrÎ|r¸|}nt| jddƒrÎ| jj}|| _dS )a-  
        Initialize me with an explanation of the error.

        By default, this will use the current C{exception}
        (L{sys.exc_info}()).  However, if you want to specify a
        particular kind of failure, you can pass an exception as an
        argument.

        If no C{exc_value} is passed, then an "original" C{Failure} will
        be searched for. If the current exception handler that this
        C{Failure} is being constructed in is handling an exception
        raised by L{raiseException}, then this C{Failure} will act like
        the original C{Failure}.

        For C{exc_tb} only L{traceback} instances or L{None} are allowed.
        If L{None} is supplied for C{exc_value}, the value of C{exc_tb} is
        ignored, otherwise if C{exc_tb} is L{None}, it will be found from
        execution context (ie, L{sys.exc_info}).

        @param captureVars: if set, capture locals and globals of stack
            frames.  This is pretty slow, and makes no difference unless you
            are going to use L{printDetailedTraceback}.
        r,   NÚ__traceback__)ÚcountÚtypeÚvalueÚcaptureVarsÚsysÚexc_infor*   Ú
isinstanceÚ	ExceptionÚ	__class__rf   Ú_extrapolateÚgetattrrg   r3   )r:   Ú	exc_valueÚexc_typeÚexc_tbrk   r3   r   r   r   r<   ÿ   s0    



zFailure.__init__c                 C  sÂ   t | dƒr| jS g  }| _| j}|d k	r¾|j}| jr�|j ¡ }|j|jkrPi }n
|j ¡ }||fD ]}d|krb|d= qbt| 	¡ ƒ}t| 	¡ ƒ}nd }}| 
|jj|jj|j||f¡ |j}q |S )NÚ_framesÚ__builtins__r   )Úhasattrrv   r3   r5   rk   rB   rF   rA   ÚlistÚitemsrc   r?   rN   rO   r7   r1   )r:   r    r3   r`   rK   rL   Údr   r   r   r    8  s6    



ûÿ	zFailure.framesc                 C  s
   || _ d S ©N)rv   )r:   r    r   r   r   r    [  s    ZTwistedé   é
   c                 C  s   g S r|   r   r^   r   r   r   r2   _  s    zFailure.stackc                 C  s   ~d S r|   r   )r:   r2   r   r   r   r2   c  s    c                 C  sV   | j d k	r| j S t | j¡rFt| jtƒrFt| jƒ}ttt	j
|ƒƒ| _ n
| jg| _ | j S r|   )Ú_parentsÚinspectÚisclassri   Ú
issubclassro   r   ry   Úmapr
   Úqual)r:   ZparentCsr   r   r   Úparentsg  s    


zFailure.parentsc                 C  s
   || _ d S r|   )r   )r:   r…   r   r   r   r…   s  s    c                 C  s   t   |j¡| _dS )a,  
        Extrapolate from one failure into another, copying its stack frames.

        @param otherFailure: Another L{Failure}, whose traceback information,
            if any, should be preserved as part of the stack presented by this
            one.
        @type otherFailure: L{Failure}
        N)rF   Ú__dict__)r:   ZotherFailurer   r   r   rq   w  s    
zFailure._extrapolateÚBaseException)rj   ra   c                 C  s6   t  t ¡}td7 ad|_t|_| |_| j|_d|_|S )z¨
        Create a L{Failure} for an exception without a traceback.

        By restricting the inputs significantly, this constructor runs much
        faster.
        r,   FN)rf   Ú__new__rh   rk   rj   rp   ri   r3   )rj   Úresultr   r   r   Ú_withoutTracebackƒ  s    
zFailure._withoutTracebackc                 G  s   | j |Ž }|s|  ¡  |S )a€  
        Trap this failure if its type is in a predetermined list.

        This allows you to trap a Failure in an error callback.  It will be
        automatically re-raised if it is not a type that you expect.

        The reason for having this particular API is because it's very useful
        in Deferred errback chains::

            def _ebFoo(self, failure):
                r = failure.trap(Spam, Eggs)
                print('The Failure is due to either Spam or Eggs!')
                if r == Spam:
                    print('Spam did it!')
                elif r == Eggs:
                    print('Eggs did it!')

        If the failure is not a Spam or an Eggs, then the Failure will be
        'passed on' to the next errback. In Python 2 the Failure will be
        raised; in Python 3 the underlying exception will be re-raised.

        @type errorTypes: L{Exception}
        )ÚcheckÚraiseException)r:   Ú
errorTypesÚerrorr   r   r   Útrap•  s    
zFailure.trapc                 G  sB   |D ]8}|}t  |¡r*t|tƒr*t |¡}|| jkr|  S qdS )a  
        Check if this failure's type is in a predetermined list.

        @type errorTypes: list of L{Exception} classes or
                          fully-qualified class names.
        @returns: the matching L{Exception} type, or None if no match.
        N)r€   r�   r‚   ro   r
   r„   r…   )r:   r�   rŽ   Úerrr   r   r   r‹   ²  s    


zFailure.checkr   )ra   c                 C  s   | j  | j¡‚dS )zf
        raise the original exception, preserving traceback
        information if available.
        N)rj   Úwith_tracebackr3   r^   r   r   r   rŒ   Â  s    zFailure.raiseExceptionc                 C  s   |  | j | j¡¡S )aJ  
        Throw the original exception into the given generator,
        preserving traceback information if available.

        @return: The next value yielded from the generator.
        @raise StopIteration: If there are no more values in the generator.
        @raise anything else: Anything that the generator raises.
        )Úthrowrj   r‘   r3   )r:   Úgr   r   r   ÚthrowExceptionIntoGeneratorÉ  s    
z#Failure.throwExceptionIntoGeneratorÚstrc                 C  s"   d  t | j¡t | j¡|  ¡ ¡S )Nz<{} {}: {}>)Úformatr
   r„   rp   ri   ÚgetErrorMessager^   r   r   r   Ú__repr__Õ  s
    

ýzFailure.__repr__c                 C  s   d|   ¡  S )Nz[Failure instance: %s])ÚgetBriefTracebackr^   r   r   r   Ú__str__Ü  s    zFailure.__str__c                 C  s>   d|kr|  d¡ |  d¡|d< |  d¡|d< | j |¡ d S )Nr2   r…   r   r    rv   )Úpopr†   Úupdate©r:   Ústater   r   r   Ú__setstate__ß  s
    
zFailure.__setstate__c                 C  sr   | j }| j ¡ }| d¡|d< g |d< d|kr8| d¡ | jrTdd„ | jD ƒ|d< n
| j|d< d|d	< d
|d< |S )zë
        Avoid pickling objects in the traceback.

        This is not called direclty by pickle, since C{BaseException}
        implements reduce; instead, pickle calls C{Failure.__reduce__} which
        then calls this API.
        r   r…   r2   rv   c              	   S  s6   g | ].}|d  |d |d t |d ƒt |d ƒg‘qS )r   r,   é   é   r   )Ú_safeReprVars)Ú.0Úvr   r   r   Ú
<listcomp>û  s   ú

ûz(Failure.__getstate__.<locals>.<listcomp>r    Nr3   r,   Úpickled)r…   r†   rF   r›   rk   r    )r:   Ú_Úcr   r   r   Ú__getstate__æ  s    	

ø
zFailure.__getstate__c                 C  s   t tjtƒd|  ¡ fS )Nr   )r   rf   rˆ   r©   r^   r   r   r   Ú
__reduce__  s    zFailure.__reduce__c                 C  s6   |   ¡ }| d¡|d< || _t| jddƒr2d| j_dS )zÈ
        Remove references to other objects, replacing them with strings.

        On Python 3, this will also set the C{__traceback__} attribute of the
        exception instance to L{None}.
        r    rv   rg   N)r©   r›   r†   rr   rj   rg   r�   r   r   r   ÚcleanFailure  s
    zFailure.cleanFailurec                 C  s0   | j dk	r| j S t| jƒdkr(t| jƒS dS dS )a‘  
        Get an object that represents this Failure's stack that can be passed
        to traceback.extract_tb.

        If the original traceback object is still present, return that. If this
        traceback object has been lost but we still have the information,
        return a fake traceback object (see L{_Traceback}). If there is no
        traceback information at all, return None.
        Nr   )r3   r-   r    r4   r^   r   r   r   ÚgetTracebackObject!  s
    


zFailure.getTracebackObjectc                 C  s"   t | jtƒr| j ¡ S t | j¡S )zJ
        Get a string of the exception which caused this Failure.
        )rn   rj   rf   r—   r
   Úsafe_strr^   r   r   r   r—   2  s    
zFailure.getErrorMessagec                 C  s   t ƒ }| j|d� | ¡ S )N)Úfile)r   ÚprintBriefTracebackÚgetvalue)r:   Úior   r   r   r™   :  s    zFailure.getBriefTracebackr   Úint)ÚelideFrameworkCoder"   ra   c                 C  s   t ƒ }| j|||d� | ¡ S )N)r®   r³   r"   )r   ÚprintTracebackr°   )r:   r³   r"   r±   r   r   r   ÚgetTraceback?  s      ÿzFailure.getTracebackc                 C  s8  |dkrddl m} |j}|j}|dkr4| js4d}n|}|dkr^|d| j| jrRdpTdf ƒ nD|d	krš| jrrd
}nd}|d|t 	| j
¡t 	| j¡f ƒ n|dƒ | jr¸t| j||ƒ n|d	ksÈ|dƒ |d	ksô|t | j
¡› dt 	| j¡› d�ƒ t| jtƒ�r| d¡ | j |||¡ |dk�r4|d| j ƒ dS )a”  
        Emulate Python's standard error reporting mechanism.

        @param file: If specified, a file-like object to which to write the
            traceback.

        @param elideFrameworkCode: Deprecated, ignored.

        @param detail: A string indicating how much information to include
            in the traceback.  Must be one of C{'brief'}, C{'default'}, or
            C{'verbose'}.
        Nr   )Úlogr   r   z*--- Failure #%d%s---
z (pickled) ú r   Ú	Tracebackz"Traceback (failure with no frames)z%s: %s: %s
z#Traceback (most recent call last):
z	Failure: z: r   z (chained Failure)
z*--- End of Failure #%d ---
)Útwisted.pythonr¶   Zlogerrr!   rk   rh   r¦   r    r
   r­   ri   rj   r)   r„   rn   rf   r´   )r:   r®   r³   r"   r¶   r#   ZformatDetailZ	hasFramesr   r   r   r´   F  sD    ÿÿÿÿ$

zFailure.printTracebackc                 C  s   | j ||dd� dS )z;
        Print a traceback as densely as possible.
        r   ©r"   N©r´   ©r:   r®   r³   r   r   r   r¯   ‡  s    zFailure.printBriefTracebackc                 C  s   | j ||dd� dS )zQ
        Print a traceback with detailed locals and globals information.
        r   rº   Nr»   r¼   r   r   r   ÚprintDetailedTraceback�  s    zFailure.printDetailedTraceback)NNNF)r   r   )NFr   )Nr   )Nr   )#r   r   r   r+   r¦   r   r<   Úpropertyr    Úsetterr   r	   r2   r…   rq   ÚstaticmethodrŠ   r�   r‹   rŒ   re   r”   r˜   rš   rŸ   r©   rª   r«   r¬   r—   r™   rµ   r´   r¯   r½   r   r   r   r   rf   á   sJ   
9
"





(
A
rf   c                 C  s   dd„ | D ƒS )aq  
    Convert a list of (name, object) pairs into (name, repr) pairs.

    L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
    exceptions will be raised by faulty C{__repr__} methods.

    @param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
        C{locals().items()}.
    @returns: a sequence of (name, repr) pairs.
    c                 S  s   g | ]\}}|t  |¡f‘qS r   )r
   Z	safe_repr)r£   r'   Úobjr   r   r   r¥   Ÿ  s     z!_safeReprVars.<locals>.<listcomp>r   )ZvarsDictItemsr   r   r   r¢   ”  s    r¢   TFc           	      C  sŠ   |||fdkrvt  ¡ }|d | jksvtrvzt|d ƒ}W n tk
rP   d}Y nX td |¡ƒ ddl}| 	|d ¡ || ||||ƒ dS )z;
    Initialize failure object, possibly spawning pdb.
    )NNNr   r,   z
broken strz8Jumping into debugger for post-mortem of exception '{}':Nr    )
rl   rm   rp   ÚDO_POST_MORTEMr•   r‡   Úprintr–   ÚpdbZpost_mortem)	r:   rs   rt   ru   rk   ZFailure__init__ÚexcZstrreprrÄ   r   r   r   Ú
_debuginit§  s    
ÿÿrÆ   c                   C  s
   t t_dS )z*
    Enable debug hooks for Failures.
    N)rÆ   rf   r<   r   r   r   r   ÚstartDebugModeÄ  s    rÇ   )r   )-r+   Ú
__future__r   rE   rF   r€   r   rl   Ú	functoolsr   r   r±   r   Útypingr   r   r   Úincrementalr	   r¹   r
   Ztwisted.python.deprecater   Úobjectr   rh   ZtraceupLengthro   r   r)   ZEXCEPTION_CAUGHT_HEREr*   r4   r0   r/   r>   rb   re   r‡   rf   r¢   rÂ   r<   rÆ   rÇ   r   r   r   r   Ú<module>   sN   
/!   6ú
