o
    >hY                     @  s\  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"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   v/var/www/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/site-packages/twisted/python/failure.pyr   &   s    r   defaultc              	   C  sx  |dvrt d|f |}|dkr*| D ]\}}}}}|| d| d| d qdS |dkrT| D ]!\}}}}}|d| d| d	| d |d
t||   q0dS |dkrq| D ]\}}}}}|d|||f  qZ|d dS |dkr| D ]B\}}}}}|d|||f  |d |D ]\}	}
|d|	 dt|
 d q|d |D ]\}	}
|d|	 dt|
 d qqwdS 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lineno	localVars
globalVarsnamevalr   r   r   format_frames*   s@   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
J 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_Frame_TracebackFrametb_next)tbFramesstackfirstTbtbsfr   r   r   
_Tracebackc   s   	

r8   c                   @     e Zd ZdZdd ZdS )r1   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_lastir2   )selfframer   r   r   __init__   s   
z_TracebackFrame.__init__Nr   r   r   r-   rA   r   r   r   r   r1      s    r1   c                   @  r9   )r0   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|pi | _|| _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_coder;   dict	f_globalsf_localsf_backr=   varsbuiltinscopy
f_builtinsf_trace)r?   	frameinfobackr)   r%   r&   localzglobalzr   r   r   rA      s   
z_Frame.__init__NrB   r   r   r   r   r0      s    
r0   c                   @  s    e Zd ZdZdd Zdd ZdS )rC   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   rA      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-   rA   rd   r   r   r   r   rC      s    rC   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__)re   r   r   r   _extraneous   s   rj   c                   @  s4  e Zd ZdZdZdZdBd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dCddZdd Zdd ZdDdd Zed!d" ZdEd$d%ZdEd&d'Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 ZdEd2d3ZdEd4d5ZdFdGd:d;ZdHd<d=Z dId>d?Z!dId@dAZ"dS )J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u r(t \| _| _}| jdu r't n|du r?t|tr6|j	| _nt|| _|| _n|| _|| _t| jt
rS| | j dS |du rg|r\|}nt| jddrg| 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__rk   _extrapolategetattrrl   r6   )r?   	exc_valueexc_typeexc_tbrp   r6   r   r   r   rA      s2   




zFailure.__init__c                 C  s   t | dr| jS g  }| _| j}|d urb|j}| jrH|j }|j|ju r(i }n|j }||fD ]	}d|v r:|d= q1t|	 }t|	 }nd }}|
|jj|jj|j||f |j}|d us|S )N_frames__builtins__r   )hasattrr{   r6   r:   rp   rG   rK   rF   listitemsrh   rD   rS   rT   r<   r2   )r?   r    r6   re   rP   rQ   dr   r   r   r    8  s:   



	zFailure.framesc                 C  
   || _ d S N)r{   )r?   r    r   r   r   r    [     
Twisted   
   c                 C  s   g S r   r   rc   r   r   r   r4   _  s   zFailure.stackc                 C  s   ~d S r   r   )r?   r4   r   r   r   r4   c  s   c                 C  sZ   | j d ur| j S t| jr%t| jtr%t| j}ttt	j
|| _ | j S | jg| _ | j S r   )_parentsinspectisclassrn   
issubclassrt   r   r~   mapr
   qual)r?   parentCsr   r   r   parentsg  s   


zFailure.parentsc                 C  r   r   )r   )r?   r   r   r   r   r   s  r   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)rK   __dict__)r?   otherFailurer   r   r   rv   w  s   
zFailure._extrapolatero   BaseExceptionrf   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)rk   __new__rm   rp   ro   ru   rn   r6   )ro   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 ]}|}t |rt|trt|}|| jv 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   rt   r
   r   r   )r?   r   r   errr   r   r   r     s   

zFailure.checkr   c                 C  s   | j | j)zf
        raise the original exception, preserving traceback
        information if available.
        )ro   with_tracebackr6   rc   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.
        )throwro   r   r6   )r?   gr   r   r   throwExceptionIntoGenerator  s   
z#Failure.throwExceptionIntoGeneratorstrc                 C  s"   d t| jt| j|  S )Nz<{} {}: {}>)formatr
   r   ru   rn   getErrorMessagerc   r   r   r   __repr__  s
   

zFailure.__repr__c                 C  s   d|    S )Nz[Failure instance: %s])getBriefTracebackrc   r   r   r   __str__  s   zFailure.__str__c                 C  s>   d|v r	| d | d|d< | d|d< | j| d S )Nr4   r   r   r    r{   )popr   updater?   stater   r   r   __setstate__  s
   
zFailure.__setstate__c                 C  sr   | j }| j }|d|d< g |d< d|v r|d | jr*d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   r4   r{   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    Nr6   r.   pickled)r   r   rK   r   rp   r    )r?   _cr   r   r   __getstate__  s   	


zFailure.__getstate__c                 C  s   t tjtd|  fS )Nr   )r   rk   r   r   rc   r   r   r   
__reduce__  s   zFailure.__reduce__c                 C  s:   |   }|d|d< || _t| jddrd| j_dS 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    r{   rl   N)r   r   r   rw   ro   rl   r   r   r   r   cleanFailure  s   zFailure.cleanFailurec                 C  s,   | j dur| j S t| jdkrt| j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   )r6   r/   r    r8   rc   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.
        )rs   ro   rk   r   r
   safe_strrc   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   elideFrameworkCodeintr"   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u rddl m} |j}|j}|dkr| jsd}n|}|dkr/|d| j| jr)dp*df  n"|d	krM| jr9d
}nd}|d|t	| j
t	| jf  n|d | jr\t| j|| n|d	ksd|d |d	ksz|t| j
 dt	| j d t| jtr|d | j||| |dkr|d| j  dS 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   logerrr!   rp   rm   r   r    r
   r   rn   ro   r+   r   rs   rk   r   )r?   r   r   r"   r   r#   formatDetail	hasFramesr   r   r   r   F  sF   $
zFailure.printTracebackc                 C     | j ||dd dS )z;
        Print a traceback as densely as possible.
        r   r"   Nr   r?   r   r   r   r   r   r        zFailure.printBriefTracebackc                 C  r   )zQ
        Print a traceback with detailed locals and globals information.
        r   r   Nr   r   r   r   r   printDetailedTraceback  r   zFailure.printDetailedTraceback)NNNF)ro   r   rf   rk   )rf   r   )rf   r   )r   r   )r   r   r"   r   rf   r   )NFr   )Nr   )#r   r   r   r-   r   r   rA   propertyr    setterr   r	   r4   r   rv   staticmethodr   r   r   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rk      sL    
9
"








(



Ark   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
   	safe_repr)r   r)   objr   r   r   r     s    z!_safeReprVars.<locals>.<listcomp>r   )varsDictItemsr   r   r   r     s   r   TFc           	      C  s   |||fdkr:t  }|d | jks:tr:zt|d }W n ty'   d}Y nw 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   )
rq   rr   ru   DO_POST_MORTEMr   r   printr   pdbpost_mortem)	r?   rx   ry   rz   rp   Failure__init__excstrreprr   r   r   r   
_debuginit  s    r   c                   C  s
   t t_dS )z*
    Enable debug hooks for Failures.
    N)r   rk   rA   r   r   r   r   startDebugMode  s   
r   )r   )re   r   rf   r   )-r-   
__future__r   rJ   rK   r   r   rq   	functoolsr   r   r   r   typingr   r   r   incrementalr	   r   r
   twisted.python.deprecater   objectr   rm   traceupLengthrt   r   r+   EXCEPTION_CAUGHT_HEREr,   r8   r1   r0   rC   rg   rj   r   rk   r   r   rA   r   r   r   r   r   r   <module>   sP   
/!
   6
