
    \dCm                     \   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 ddl	m
Z
 ddlZddlm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 Z G d de          Zd ZdZddddej        fdZ d Z!dS )z9
Asynchronous-friendly error mechanism.

See L{Failure}.
    N)getmro)StringIO)NoReturn)reflect   c                       e Zd ZdS )DefaultExceptionN)__name__
__module____qualname__     6lib/python3.11/site-packages/twisted/python/failure.pyr	   r	   !   s        Dr   r	   defaultc           
         |dvrt          d|d          |}|dk    r!| D ]\  }}}}} || d| d| d           dS |dk    rU| D ]P\  }}}}} |d| d	| d
| d            |dt          j        ||                                          z             QdS |dk    r)| D ]\  }}}}} |d|||fz              |d           dS |dk    r| D ]\  }}}}} |d|||fz              |d           |D ]$\  }	}
 |d|	 dt	          |
           d           % |d           |D ]$\  }	}
 |d|	 dt	          |
           d           %~d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-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_framesr(   %   s{   " QQQj5;VV>
 
 	
 	A?E 	1 	1;FHfiA//F//V///0000	1 	1	9		?E 	H 	H;FHfiABBB6BBBBBCCCAj9,Xv>>DDFFFGGGG	H 	H 
.	.	.?E 	? 	?;FHfiA Hff#==>>>>	
NOOOOO	9		?E 	/ 	/;FHfiA Hff#==>>>Ao& / /	c-t--S		---....A' / /	c-t--S		---..../ 
		/ 	/r   z--- <exception caught here> ---c                       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*   X   s           r   r*   c                 ,   t          |          dk    s
J d            d}| D ]}t          ||          }t          |d         |          }t          |          x}}|dd         D ]-}t          ||          }t          |          |_        |j        }.|S )a5  
    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 stackFrames: [(methodname, filename, lineno, locals, globals), ...]
    @param tbFrames: [(methodname, filename, lineno, locals, globals), ...]
    r   zMust pass some framesN   )len_Frame_TracebackFrametb_next)stackFramestbFramesstacksffirstTbtbs         r   
_Tracebackr8   _   s     x==15 E " "r5!! 8A;&&E"5)))Gbqrrl  r5!!$U++
Z Nr   c                       e Zd ZdZd ZdS )r0   zq
    Fake traceback object which can be passed to functions in the standard
    library L{traceback} module.
    c                 R    || _         |j        | _        |j        | _        d| _        dS )z-
        @param frame: _Frame object
        N)tb_framef_lineno	tb_linenof_lastitb_lastir1   )selfframes     r   __init__z_TracebackFrame.__init__   s(     r   Nr
   r   r   r+   rB   r   r   r   r0   r0      s-         
    r   r0   c                       e Zd ZdZ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                 &   |\  }}}}}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globalzs           r   rB   z_Frame.__init__   s     3</hD(++gm,,V\r**x..--//r   NrC   r   r   r   r/   r/      s-             r   r/   c                       e Zd ZdZd Zd ZdS )rF   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| _        d S )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)r@   r&   r"   s      r   rB   z_Code.__init__   s    #"#!"r   c                     dS )N))NNNNr   r@   s    r   co_positionsz_Code.co_positions   s    **r   N)r
   r   r   r+   rB   ri   r   r   r   rF   rF      s<           $+ + + + +r   rF   c                 D    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__)fs    r   _extraneousro      s     %%aj111Hr   c                       e Zd ZdZdZdZej        d         ZddZ	d Z
d Zd	 Zd
efdZed             Zed             Zd
efdZd
efdZd Zd Zd Zd
efdZd
efdZddeded
efdZddZddZddZdS ) 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{stack} and C{frame} attributes contain 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.

    @ivar value: The exception instance responsible for this failure.
    @ivar type: The exception's class.
    @ivar stack: list of frames, innermost last, excluding C{Failure.__init__}.
    @ivar frames: list of frames, innermost first.
    r   NYIELD_VALUEFc                    t           dz   a t           | _         dx| _        x| _        }|| _        t	          |t
                    r|t          d          d}||                                 }|9t          j	                    \  | _        | _        }| j        t                      d}nN|>t	          |t                    r|j        | _        nt          |          | _        || _        n|| _        || _        t	          | j        t                    r|                     | j                   dS t          | j        d          r(|                     | j        j                   | j        `dS |'|r|}n"t#          | j        dd          r| j        j        }g x}| _        g x}| _        || _        |r|j        }	nt	          | j        t                    sdx}	}|r|	r|	j        }	|dz  }|r|	|	r|rz|	j                                        }
|	j        |	j        u ri }n|	j                                        }||
fD ]	}d|v r|d= 
|
                                }
|                                }ndx}
}|                    d|	j        j        |	j        j        |	j         |
|f           |	j        }	|	||j        }	|r|	j                                        }
|	j        |	j        u ri }n|	j                                        }||
fD ]	}d|v r|d= 
tC          |
                                          }
tC          |                                          }ndx}
}|"                    |	j        j        |	j        j        |j#        |
|f           |j$        }|tK          j&        | j                  r\tO          | j        t                    rBtQ          | j                  }tC          tS          tT          j+        |                    | _,        dS | j        g| _,        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-   Nz$Strings are not supported by Failurer   __failure____traceback____builtins__r   )-counttypevaluecaptureVars
isinstancestr	TypeError_findFailuresysexc_infor*   	Exception	__class__rq   _extrapolatehasattrrt   getattrru   r   r4   r7   r;   rK   rJ   rN   rI   itemsinsertrG   rW   rX   r<   listrl   r=   r1   inspectisclass
issubclassr   mapr   qualparents)r@   	exc_valueexc_typeexc_tbrz   r7   stackOffsetr   r4   rn   rS   rT   dparentCss                 r   rB   zFailure.__init__  sW   2 	
&**	*DJ&i%% 	D(*:BCCC))++I(+%DItz2y -///KK)Y// ,%/		 !OO	"DJJ DI"DJdj'** 	dj)))F4:}-- 	
 dj4555 
&F: ._d;; .Z-!!

  	#AADJ00 	# #"A 	a 	 A1K	  	a 	  	 &**:,, GGk..00G & . .A%**n-!--//#%%LLH$H(J	 	 	 A1  	4 nA &**:,, GGk..00G & . .A%**n-fllnn--w}}//#%%MMH$H(L   B1 n2 ?49%% 	'*TY	*J*J 	'di((HGL( ; ;<<DLLL I;DLLLr   c                 \   t          j         |j                  | _        t          j                    \  }}}g }|Q|j        }|j        t          vr3|                    |j        j        |j        j	        |j
        ddf           |j        }|Q|                    | 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}
        Nr   )rN   __dict__r   r   r;   rG   rk   rl   rW   rX   r=   r1   extendr   )r@   otherFailure_r7   r   rn   s         r   r   zFailure._extrapolate  s     	,"788 <>>1bnAx999X%qx';R\2rR   B n 	dk"""r   c                 F     | 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errors      r   trapzFailure.trap  s1    0 
J' 	"!!!r   c                     |D ]N}|}t          j        |          r)t          |t                    rt	          j        |          }|| j        v r|c S Od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   r   r   r   r   )r@   r   r   errs       r   r   zFailure.check  sj       	 	ECu%% **UI*F*F *l5))dl"" #tr   returnc                 @    | j                             | j                  )zf
        raise the original exception, preserving traceback
        information if available.
        )ry   with_tracebackr7   rh   s    r   r   zFailure.raiseException  s    
 j''000r   c                 N    |                     | 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.
        )throwrx   ry   r7   )r@   gs     r   throwExceptionIntoGeneratorz#Failure.throwExceptionIntoGenerator  s      wwty$*dg666r   c                     t          j                    d         }|sdS d}|}|j        r|}|j        }|j        |j        }|j        | j        j        u r|j                            d          S |j        j	        r |j        j	        |j
                 | j        k    rdS |r4|j        }|j        | j        j        u r|j                            d          S |j        j        }|r-|j        | j        j        u r|j                            d          S dS dS )zV
        Find the failure that represents the exception currently in context.
        Nr@   )r   r   r1   r;   rG   r   rm   rJ   getr]   r?   _yieldOpcoder   rK   )clsr7   secondLastTblastTb	lastFramerA   s         r   r~   zFailure._findFailure  sC   
 \^^B 	Fn 	$!L^F n 	$ O	 s1:::%))&111  ( 	Y-=-EO.
. . F
  	2 )E|s>GGG~))&111 " 	.U\S%D%MMM>%%f---	. 	.MMr   c                     d                     t          j        | j                  t          j        | j                  |                                           S )Nz<{} {}: {}>)formatr   r   r   rx   getErrorMessagerh   s    r   __repr__zFailure.__repr__C  sG    ##L((L##  ""
 
 	
r   c                 0    d|                                  z  S )Nz[Failure instance: %s])getBriefTracebackrh   s    r   __str__zFailure.__str__J  s    '$*@*@*B*BBBr   c                     | j         r| j        S | j                                        }d | j        D             |d<   d|d<   | j        d | j        D             |d<   d|d<   |S )	z(Avoid pickling objects in the traceback.c           
          g | ]A}|d          |d         |d         t          |d                   t          |d                   gBS r   r-         r   _safeReprVars.0vs     r   
<listcomp>z(Failure.__getstate__.<locals>.<listcomp>S  s_     	
 	
 	
  !!!ad##ad##	
 	
 	
r   r   Nr7   c           
          g | ]A}|d          |d         |d         t          |d                   t          |d                   gBS r   r   r   s     r   r   z(Failure.__getstate__.<locals>.<listcomp>d  s_     	 	 	  aDaDaD!!A$''!!A$''	 	 	r   r4   r-   pickled)r   r   rN   r   r4   )r@   cs     r   __getstate__zFailure.__getstate__M  s    < 	!= M  	
 	
 [	
 	
 	
( $:!	 	 	 	 	AgJ )r   c                     |                                  | _        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}.
        ru   N)r   r   r   ry   ru   rh   s    r   cleanFailurezFailure.cleanFailurer  sG     ))++4:55 	,'+DJ$$$	, 	,r   c                     | j         | j         S t          | j                  dk    rt          | j        | 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   )r7   r.   r   r8   r4   rh   s    r   getTracebackObjectzFailure.getTracebackObject~  sA     77N!!dj$+6664r   c                     t          | j        t                    r| j                                        S t	          j        | j                  S )zJ
        Get a string of the exception which caused this Failure.
        )r{   ry   rq   r   r   safe_strrh   s    r   r   zFailure.getErrorMessage  s?     dj'** 	0:--///
+++r   c                 r    t                      }|                     |           |                                S )N)file)r   printBriefTracebackgetvalue)r@   ios     r   r   zFailure.getBriefTraceback  s0    ZZ  b ))){{}}r   r   elideFrameworkCoder   c                 v    t                      }|                     |||           |                                S )N)r   r   r   )r   printTracebackr   )r@   r   r   r   s       r   getTracebackzFailure.getTraceback  s@    ZZ(:6 	 	
 	
 	
 {{}}r   c           	         |ddl m} |j        }|j        }|dk    r
| j        sd}n|}|dk    r |d| j        | j        rdpdfz             n`|d	k    rO| j        rd
}nd} ||dt          j	        | j
                  dt          j	        | j                  d           n |d           | j        rP|s7t          | j        t           d         ||            |t           d           t          | j        ||           n|d	k    s |d           |d	k    s? |t          j        | j
                   dt          j	        | j                   d           t#          | j        t$                    r1|                    d           | j                            |||           |dk    r |d| j        z             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: A flag indicating whether to attempt to
            remove uninteresting frames from within Twisted itself from the
            output.

        @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   rz   rw   r   r   r   r   rx   ry   r(   r4   traceupLengthEXCEPTION_CAUGHT_HEREr   r{   rq   r   )r@   r   r   r   r   r    formatDetail	hasFramess           r   r   zFailure.printTraceback  sO    <******:DJYt'7 7LL!L YA): >F3GH    w{ A'		@	A99g.ty99997;KDJ;W;W;W;WY   
 A4555 ; 	% 0dj-91lKKK*...///$+q,77777""AkNNN   Adi((LLG,<TZ,H,HLLLMMM dj'** 	HJJ-...J%%d,>GGGYA-
:;;;;; r   c                 6    |                      ||d           dS )z;
        Print a traceback as densely as possible.
        r   r   Nr   r@   r   r   s      r   r   zFailure.printBriefTraceback  s&     	D"4WEEEEEr   c                 6    |                      ||d           dS )zQ
        Print a traceback with detailed locals and globals information.
        r   r   Nr   r   s      r   printDetailedTracebackzFailure.printDetailedTraceback  s&     	D"4YGGGGGr   )NNNF)r   r   )NFr   )Nr   ) r
   r   r   r+   r   r4   opcodeopmapr   rB   r   r   r   r   r   ro   r   classmethodr~   r|   r   r   r   r   r   r   r   intr   r   r   r   r   r   r   rq   rq      s        $ GE <.Ld' d' d' d'L  :  :   1 1 1 1 1 7 7 [7 8. 8. [8.t
# 
 
 
 
C C C C C# # #J
, 
, 
,  ", , , , ,3    
 s  TW    C< C< C< C<JF F F FH H H H H Hr   rq   c                     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                 @    g | ]\  }}|t          j        |          fS r   )r   	safe_repr)r   r&   objs      r   r   z!_safeReprVars.<locals>.<listcomp>   s,    LLL{cT7$S))*LLLr   r   )varsDictItemss    r   r   r     s     MLmLLLLr   TFc                 `   |||fdk    rt          j                    }|d         | j        k    sqt          rj	 t	          |d                   }n# t
          $ r d}Y nw xY 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   )
r   r   r   DO_POST_MORTEMr|   BaseExceptionprintr   pdbpost_mortem)	r@   r   r   r   rz   Failure__init__excstrreprr   s	            r   
_debuginitr     s     	8V$(:::lnn1v''N''c!f++  ' ' '&'JQQ   
 JJJOOCF###OD)Xv{CCCCCs   A AAc                  (    t           t          _        dS )z*
    Enable debug hooks for Failures.
    N)r   rq   rB   r   r   r   startDebugModer   %  s     "Gr   )r   )"r+   rM   rN   r   r   r   r   r   r   typingr   r   r   r   rw   r   r   r	   r(   r   r*   r8   r0   r/   rF   rk   ro   r   rq   r   r   rB   r   r   r   r   r   <module>r      sE           



                    " " " " " "		 	 	 	 	y 	 	 	+/ +/ +/ +/` :     i   # # #R               8+ + + + + + + +<      MH MH MH MH MHm MH MH MH`M M M  
 $D D D D:" " " " "r   