
    VhY                       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         ZdadZ G d de      Zd$dZdZ G d de      Zd Z  G d d      Z! G d d      Z" G d d      Z#g Z$d%dZ% G d de&      Z'd Z(d Z)dddd!e'jT                  fd"Z+d# Z,y)&z9
Asynchronous-friendly error mechanism.

See L{Failure}.
    )annotationsN)partial)getmro)StringIO)CallableNoReturnTypeVar)Version)reflect)deprecatedProperty_T_Callable.)bound   c                      e Zd Zy)DefaultExceptionN)__name__
__module____qualname__     F/home/dcms/DCMS/lib/python3.12/site-packages/twisted/python/failure.pyr   r   &   s    r   r   c           
     V   |dvrt        d|d      |}|dk(  r| D ]  \  }}}}} || d| d| d        y|dk(  rM| D ]G  \  }}}}} |d| d	| d
| d        |dt        j                  ||      j                         z         I y|dk(  r$| D ]  \  }}}}} |d|||fz           |d       y|dk(  rp| D ]j  \  }}}}} |d|||fz          |d       |D ]  \  }	}
 |d|	 dt	        |
       d         |d       |D ]  \  }	}
 |d|	 dt	        |
       d        l yy)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
    )defaultbriefverboseverbose-vars-not-capturedzKDetail must be default, brief, verbose, or verbose-vars-not-captured. (not )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vals              r   format_framesr0   *   s   " QQ5;>
 	
 	A?E 	1;FHfi
!F81VHB/0	1	9	?E 	H;FHfi
(6(%xrBCj9,,Xv>DDFFG	H 
.	.?E 	?;FHfi Hff#==>	?	
NO	9	?E 	/;FHfi Hff#==>o& /	cBtfCS	{"-./' /	cBtfCS	{"-./	/ 
r   z--- <exception caught here> ---c                      e Zd ZdZy)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   r2   r2   \   s    r   r2   c                    t        |       dkD  sJ d       d}t        | d   |      }t        |      x}}| dd D ]*  }t        ||      }t        |      |_        |j                  }, |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sfs        r   
_Tracebackr?   c   s     x=1555 E 8A;&E"5))Gbqrl r5!$U+
ZZ Nr   c                      e Zd ZdZd Zy)r8   zq
    Fake traceback object which can be passed to functions in the standard
    library L{traceback} module.
    c                d    || _         |j                  | _        |j                  | _        d| _        y)z-
        @param frame: _Frame object
        N)tb_framef_lineno	tb_linenof_lastitb_lastir9   )selfframes     r   __init__z_TracebackFrame.__init__   s(     r   Nr   r   r   r3   rI   r   r   r   r8   r8      s    
r   r8   c                      e Zd ZdZd Zy)r7   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                   |\  }}}}}t        ||      | _        || _        t        |xs i       | _        t        |xs i       | _        || _        d| _        t        t              j                         | _        d| _        y)z
        @param frameinfo: (methodname, filename, lineno, locals, globals)
        @param back: previous (older) stack frame
        @type back: C{frame}
        r   N)_Codef_coderC   dict	f_globalsf_localsf_backrE   varsbuiltinscopy
f_builtinsf_trace)rG   	frameinfobackr.   r*   r+   localzglobalzs           r   rI   z_Frame.__init__   sr     3</hD(+gm,V\r*x.--/r   NrJ   r   r   r   r7   r7      s    r   r7   c                      e Zd ZdZd Zd Zy)rM   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                    || _         || _        d| _        d| _        d| _        g | _        d| _        d| _        d| _        d| _	        d| _
        d| _        d| _        d| _        d| _        d| _        y )Nr   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)rG   r.   r*   s      r   rI   z_Code.__init__   s{    #"#!"r   c                     y)N))NNNNr   rG   s    r   co_positionsz_Code.co_positions   s    *r   N)r   r   r   r3   rI   rp   r   r   r   rM   rM      s    $+r   rM   c                D    t         j                  | 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__)fs    r   _extraneousrv      s     %%ajj1Hr   c                  v   e Zd ZdZdZdZd!dZed        Zej                  d        Z e
 eddd	d            d
        Zej                  d        Zed        Zej                  d        Zd Zed"d       Zd Zd Zd#dZed        Zd$dZd$dZd Zd Zd Zd Zd Zd$dZd$dZd%d&dZd'dZ d(dZ!d(d Z"y))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   Nc                R   t         dz   a t         | _         dx| _        x| _        }|| _        |8t	        j
                         \  | _        | _        }| j                  Tt               |:t        |t              r|j                  | _        nt        |      | _        || _        n|| _        || _        t        | j                  t              r| j                  | j                         y|9|r
|}|| _        yt        | j                  dd      r| j                  j                  }|| _        y)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}.
        r5   N__traceback__)counttypevaluecaptureVarssysexc_infor2   
isinstance	Exception	__class__rx   _extrapolategetattrrz   r=   )rG   	exc_valueexc_typeexc_tbr~   r=   s         r   rI   zFailure.__init__   s    2 	
&**	*DJ&(+%DItz2yy -//)Y/%//	 !O	"DJ DI"DJdjj'*djj):  _d;ZZ--r   c                t   t        | d      r| j                  S g x}| _        | j                  }||j                  }| j                  r|j
                  j                         }|j
                  |j                  u ri }n|j                  j                         }||fD ]
  }d|v s|d=  t        |j                               }t        |j                               }ndx}}|j                  |j                  j                  |j                  j                  |j                  ||f       |j                  }||S )N_frames__builtins__r   )hasattrr   r=   rB   r~   rQ   rU   rP   listitemsrs   rN   r^   r_   rD   r9   )rG   r%   r=   ru   rZ   r[   ds          r   r%   zFailure.frames8  s   4#<< ""WWnA*::, Gkk..0G & .A%*n-. flln-w}}/#%%MMHH$$HH((LL B1 n2 r   c                    || _         y N)r   )rG   r%   s     r   r%   zFailure.frames[  s	    r   Twisted   
   c                    g S r   r   ro   s    r   r;   zFailure.stack_  s    	r   c                     ~y r   r   )rG   r;   s     r   r;   zFailure.stackc  s    r   c                r   | j                   | j                   S t        j                  | j                        rct	        | j                  t
              rIt        | j                        }t        t        t        j                  |            | _         | j                   S | j                  g| _         | j                   S r   )_parentsinspectisclassr|   
issubclassr   r   r   mapr   qual)rG   parentCss     r   parentszFailure.parentsg  s}    ==$== ??499%*TYY	*Jdii(H W\\8!<=DM }} "YYKDM}}r   c                    || _         y r   )r   )rG   r   s     r   r   zFailure.parentss  s	    r   c                L    t        j                   |j                        | _        y)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)rU   __dict__)rG   otherFailures     r   r   zFailure._extrapolatew  s     		,"7"78r   c                    t         j                  t               }t        dz  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.
        r5   FN)rx   __new__r{   r~   r}   r   r|   r=   )r}   results     r   _withoutTracebackzFailure._withoutTraceback  sH     )
"oo	r   c                H     | j                   | }|s| j                          |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)rG   
errorTypeserrors      r   trapzFailure.trap  s(    0 

J'!r   c                    |D ]P  }|}t        j                  |      r%t        |t              rt	        j
                  |      }|| j                  v sN|c S  y)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   r   r   r   r   )rG   r   r   errs       r   r   zFailure.check  sQ       	ECu%*UI*Fll5)dll"	 r   c                L    | j                   j                  | j                        )zf
        raise the original exception, preserving traceback
        information if available.
        )r}   with_tracebackr=   ro   s    r   r   zFailure.raiseException  s    
 jj''00r   c                j    |j                  | j                  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.
        )throwr}   r   r=   )rG   gs     r   throwExceptionIntoGeneratorz#Failure.throwExceptionIntoGenerator  s&     wwtzz009::r   c                    dj                  t        j                  | j                        t        j                  | j                        | j                               S )Nz<{} {}: {}>)formatr   r   r   r|   getErrorMessagero   s    r   __repr__zFailure.__repr__  sA    ##LL(LL#  "
 	
r   c                (    d| j                         z  S )Nz[Failure instance: %s])getBriefTracebackro   s    r   __str__zFailure.__str__  s    '$*@*@*BBBr   c                    d|v r|j                  d       |j                  d      |d<   |j                  d      |d<   | j                  j                  |       y )Nr;   r   r   r%   r   )popr   updaterG   states     r   __setstate__zFailure.__setstate__  sN    eIIg!IIi0j 99X.iU#r   c                   | j                   }| j                  j                         }|j                  d      |d<   g |d<   d|v r|j                  d       | j                  rD| j
                  D cg c]*  }|d   |d   |d   t        |d         t        |d	         g, c}|d
<   n| j
                  |d
<   d|d<   d|d<   |S c c}w )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   r;   r   r   r5         r   r%   Nr=   pickled)r   r   rU   r   r~   r%   _safeReprVars)rG   _cvs       r   __getstate__zFailure.__getstate__  s     LLMM  uuZ()'
>EE) 	  aDaDaD!!A$'!!A$'	AhK ++AhK $)#	s   //C c                `    t        t        j                  t              d| j                         fS )Nr   )r   rx   r   r   ro   s    r   
__reduce__zFailure.__reduce__  s%     12t7H7H7JKKr   c                    | j                         }|j                  d      |d<   || _        t        | j                  dd      rd| j                  _        yy)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   rz   N)r   r   r   r   r}   rz   r   s     r   cleanFailurezFailure.cleanFailure  sM     !!# 99X.i4::5'+DJJ$ 6r   c                    | j                   | j                   S t        | j                        dkD  rt        | j                        S y)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   )r=   r6   r%   r?   ro   s    r   getTracebackObjectzFailure.getTracebackObject!  s:     7777N!dkk**r   c                    t        | j                  t              r| j                  j                         S t	        j
                  | j                        S )zJ
        Get a string of the exception which caused this Failure.
        )r   r}   rx   r   r   safe_strro   s    r   r   zFailure.getErrorMessage2  s:     djj'*::--//

++r   c                Z    t               }| j                  |       |j                         S )N)file)r   printBriefTracebackgetvalue)rG   ios     r   r   zFailure.getBriefTraceback:  s&    Z  b ){{}r   c                ^    t               }| j                  |||       |j                         S )N)r   elideFrameworkCoder'   )r   printTracebackr   )rG   r   r'   r   s       r   getTracebackzFailure.getTraceback?  s2    Z(:6 	 	
 {{}r   c           	     d   |ddl m} |j                  }|j                  }|dk(  r| j                  sd}n|}|dk(  r* |d| j
                  | j                  xr dxs dfz         nj|d	k(  r]| j                  rd
}nd} ||dt        j                  | j                        dt        j                  | j                        d       n |d       | j                  rt        | j                  ||       n|d	k(  s |d       |d	k(  sH |t        j                  | j                         dt        j                  | j                         d       t        | j                  t              r.|j                  d       | j                  j!                  |||       |dk(  r |d| j
                  z         yy)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: r   z#Traceback (most recent call last):
z	Failure: z (chained Failure)
z*--- End of Failure #%d ---
)twisted.pythonr   logerrr&   r~   r{   r   r%   r   r   r|   r}   r0   r   r   rx   r   )rG   r   r   r'   r   r(   formatDetail	hasFramess           r   r   zFailure.printTracebackF  s    <*::DJJYt'7'7 7L!L Y):: >F3GH w{{'	@	g..tyy97;K;KDJJ;WY
 45 ;;$++q,77"kN  dii()G,<,<TZZ,H+ILM djj'*JJ-.JJ%%d,>GY-

:; r   c                ,    | j                  ||d       y)z;
        Print a traceback as densely as possible.
        r   r'   Nr   rG   r   r   s      r   r   zFailure.printBriefTraceback  s     	D"4WEr   c                ,    | j                  ||d       y)zQ
        Print a traceback with detailed locals and globals information.
        r   r   Nr   r   s      r   printDetailedTracebackzFailure.printDetailedTraceback  s     	D"4YGr   )NNNF)r}   BaseExceptionreturnrx   )r   r   )r   str)r   r   )r   intr'   r   r   r   )NFr   )Nr   )#r   r   r   r3   r   r   rI   propertyr%   setterr   r
   r;   r   r   staticmethodr   r   r   r   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx   rx      s1   4 GH7r    D ]]  	2r156 7 \\  	 	 ^^   
9  ": 1 	; 	;
C$&PL
,",
?<BFHr   rx   c                b    | D cg c]  \  }}|t        j                  |      f c}}S c c}}w )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.
    )r   	safe_repr)varsDictItemsr.   objs      r   r   r     s-     ?LL{cT7$$S)*LLLs   !+TFc                (   |||fdk(  rmt        j                         }|d   | j                  k(  sGt        rA	 t	        |d         }t        dj                  |             ddl}|j                  |d           || ||||       y# t
        $ r d}Y Lw xY w)z;
    Initialize failure object, possibly spawning pdb.
    )NNNr   r5   z
broken strz8Jumping into debugger for post-mortem of exception '{}':Nr   )
r   r   r   DO_POST_MORTEMr   r   printr   pdbpost_mortem)	rG   r   r   r   r~   Failure__init__excstrreprr   s	            r   
_debuginitr     s     	8V$(::lln1v'N'c!f+ JQQ
 OOCF#D)Xv{C ! '&'s   B BBc                 "    t         t        _        y)z*
    Enable debug hooks for Failures.
    N)r   rx   rI   r   r   r   startDebugModer     s     "Gr   )r   )ru   r   r   r   )-r3   
__future__r   rT   rU   r   r!   r   	functoolsr   r   r   r   typingr   r   r	   incrementalr
   r   r   twisted.python.deprecater   objectr   r{   traceupLengthr   r   r0   EXCEPTION_CAUGHT_HEREr2   r?   r8   r7   rM   rr   rv   r   rx   r   r   rI   r   r   r   r   r   <module>r	     s    #     
    . .  " 7m8CK+@A		y 	+/^ : i B   8+ +<    pHm pHfM  
 $$D:"r   