ϪfmpdZddlZddlZddlZddlZddlZddlmZddlmZddl m Z m Z m Z ddl Z ddlmZe de def Zdad ZGd d eZd"d ZdZGddeZdZGddZGddZGddZgZdedefdZGddeZ dZ!dZ"dddde jFfd Z$d!Z%y)#z9 Asynchronous-friendly error mechanism. See L{Failure}. N)getmro)StringIO)CallableNoReturnTypeVar)reflect _T_Callable.)boundc eZdZy)DefaultExceptionN)__name__ __module__ __qualname__8/usr/lib/python3/dist-packages/twisted/python/failure.pyr r #srr c V|dvrtd|d|}|dk(r|D]\}}}}}||d|d|dy|dk(rM|D]G\}}}}}|d|d |d |d|d tj||jzIy|d k(r$|D]\}}}}}|d |||fz|dy|dk(rp|D]j\}}}}}|d |||fz|d|D]\} } |d| dt | d|d|D]\} } |d| dt | dlyy)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 )defaultbriefverboseverbose-vars-not-capturedzKDetail must be default, brief, verbose, or verbose-vars-not-captured. (not )r: rz File "z", line z, in z %s rz%s:%d: %s(...) zA [Capture of Locals and Globals disabled (use captureVars=True)] rz [ Locals ] z z : z ( Globals ) N) ValueError linecachegetlinestriprepr) frameswritedetailwmethodfilenamelineno localVars globalVarsnamevals r format_framesr,'s"QQ5; >   A ?E 1 ;FHfi  !F81VHB/ 0 1 9 ?E H ;FHfi  (6(%xrB C j9,,Xv>DDFF G H . .?E ? ;FHfi  Hff#== > ? NO 9 ?E / ;FHfi  Hff#== > o & / cBtfCS {"-. /  ' / cBtfCS {"-. / / rz--- ---ceZdZdZy)NoCurrentExceptionErrorz Raised when trying to create a Failure from the current interpreter exception state and there is no current exception state. N)rrr__doc__rrrr.r.Zsrr.ct|dkDsJdd}|D]}t||}t|d|}t|x}}|ddD]*}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), ...] rzMust pass some framesN)len_Frame_TracebackFrametb_next) stackFramestbFramesstacksffirstTbtbs r _Tracebackr<as x=1 555  E"r5!" 8A; &E"5))Gbqrlr5!$U+ ZZ NrceZdZdZdZy)r4zq Fake traceback object which can be passed to functions in the standard library L{traceback} module. cd||_|j|_|j|_d|_y)z- @param frame: _Frame object N)tb_framef_lineno tb_linenof_lastitb_lastir5)selfframes r__init__z_TracebackFrame.__init__s(    rNrrrr/rFrrrr4r4s  rr4ceZdZdZdZy)r3aD A fake frame object, used by L{_Traceback}. @ivar f_code: fake L{code} 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|xsi|_t|xsi|_||_d|_ttj|_ d|_ y)z @param frameinfo: (methodname, filename, lineno, locals, globals) @param back: previous (older) stack frame @type back: C{frame} rN) _Codef_coder@dict f_globalsf_localsf_backrBvarsbuiltinscopy f_builtinsf_trace)rD frameinfobackr*r&r'localzglobalzs rrFz_Frame.__init__sr 3</hD(+  gm,V\r*   x.--/ rNrGrrrr3r3s rr3ceZdZdZdZdZy)rJz 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)Nrrr)co_name co_filename co_lnotabco_firstlineno co_argcount co_varnamesco_code co_cellvars co_constsco_flags co_freevarsco_posonlyargcountco_kwonlyargcountco_names co_nlocals co_stacksize)rDr*r&s rrFz_Code.__init__s{ #  "#!" rcy)N))NNNNrrDs r co_positionsz_Code.co_positionss*rN)rrrr/rFrmrrrrJrJs$+rrJfreturncDtj|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 )_inlineCallbacksExtraneousappend__code__)rns r _extraneousrts%%ajj1 HrceZdZdZdZdZejdZddZ dZ dZ dZ d e fd Zed Zed Zd efd Zd efdZdZdZdZd efdZd efdZddeded efdZddZddZddZy)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. rN YIELD_VALUEctdzat|_dx|_x|_}||_t |t r | t dd}||j}|;tj\|_|_}|j td}nJ|:t |tr|j|_nt||_||_n||_||_t |jtr|j|jyt|jdr2|j|jj |j`y|2|r|}n-t#|jddr|jj$}gx}|_gx}|_||_|r |j,} nt |jtsdx} }|r r| j.} |dz}|r| r r|r| j0j3} | j0| j4uri} n| j4j3} | | fD] } d| vs| d= | j7} | j7} ndx} } |j9d| j:j<| j:j>| j@| | f| j.} | r||j,} |r| j0j3} | j0| j4uri} n| j4j3} | | fD] } d| vs| d= tC| j7} tC| j7} ndx} } |jE| j:j<| j:j>|jF| | f|jH}|tKjL|jrXtO|jtr>tQ|j} tCtStTjV| |_,y|jg|_,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}. r1Nz$Strings are not supported by Failurer __failure__ __traceback__ __builtins__r)-counttypevalue captureVars isinstancestr TypeError _findFailuresysexc_infor. Exception __class__rv _extrapolatehasattrrygetattrrzr!r8r;r?rOrNrRrMitemsinsertrKr[r\r@listrrrAr5inspectisclass issubclassrmaprqualparents)rD exc_valueexc_typeexc_tbrr; stackOffsetr!r8rnrWrXdparentCss rrFzFailure.__init__s2  &** *DJ& i %(*:BC C  ))+I  (+  %DItz2yy -//K  )Y/%// !O "DJ DI"DJ djj' *   djj )  4::} -   djj44 5  &  :_d;ZZ--!!   ADJJ0# "A aA 1 K a*::, Gkk..0G &.A%*n-. !--/#%% LLHH$$HH((JJ  A14n A*::, Gkk..0G &.A%*n-.flln-w}}/#%% MMHH$$HH((LL  B1n2 ??499 %*TYY *Jdii(HGLL( ;1bn Axx99 XX%%qxx';';R\\2rRB n  dkk" rcH|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} )checkraiseException)rD errorTypeserrors rtrapz Failure.traps(0 J'    ! rc|D]P}|}tj|r%t|trt j |}||j vsN|cSy)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)rrrrrrr)rDrrerrs rrz Failure.checksQ  ECu%*UI*Fll5)dll"   rrocL|jj|j)zf raise the original exception, preserving traceback information if available. )r~with_tracebackr;rls rrzFailure.raiseExceptions jj''00rcj|j|jj|jS)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~rr;)rDgs rthrowExceptionIntoGeneratorz#Failure.throwExceptionIntoGenerators&wwtzz009::rctjd}|syd}|}|jr|}|j}|jr|j}|j|j j ur|jjdS|jjr0|jj|j|jk7ry|rI|j}|j|jj ur|jjdS|jj}|r>|j|jj ur|jjdSyy)zV Find the failure that represents the exception currently in context. NrD)rrr5r?rKrrsrNgetrarC _yieldOpcoderrO)clsr; secondLastTblastTb lastFramerEs rrzFailure._findFailure sC \\^B   nn!L^^FnnOO    s11:: :%%))&1 1  ((Y-=-=-E-E OO.   .   ))E||s>>GGG~~))&11 "" U\\S%D%D%M%MM>>%%f- -N5rcdjtj|jtj|j|j S)Nz <{} {}: {}>)formatrrrr}getErrorMessagerls r__repr__zFailure.__repr__DsA## LL ( LL #  "  rc(d|jzS)Nz[Failure instance: %s])getBriefTracebackrls r__str__zFailure.__str__Ks'$*@*@*BBBrc |jr |jS|jj}|jDcgc]*}|d|d|dt |dt |dg,c}|d<d|d<|j C|j Dcgc]*}|d|d|dt |dt |dg,c}|d <d|d <|Scc}wcc}w) z(Avoid pickling objects in the traceback.rr1r r!Nr;r8pickled)rrrRr! _safeReprVarsr8)rDcvs r __getstate__zFailure.__getstate__Ns <<== MM   [[   !!!ad#ad#    ( $ :: !  aDaDaD!!A$'!!A$'  AgJ) ;  " s /C/Cc|j|_t|jddrd|j_yy)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}. rzN)rrrr~rzrls r cleanFailurezFailure.cleanFailuress5))+ 4:: 5'+DJJ $ 6rc|j |jSt|jdkDr t|j|jSy)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;r2r!r<r8rls rgetTracebackObjectzFailure.getTracebackObjects@ 77 77N   !djj$++6 6rct|jtr|jjSt j |jS)zJ Get a string of the exception which caused this Failure. )rr~rvrrsafe_strrls rrzFailure.getErrorMessages: djj' *::--/ / ++rcZt}|j||jS)N)file)rprintBriefTracebackgetvalue)rDios rrzFailure.getBriefTracebacks& Z   b ){{}relideFrameworkCoder#c^t}|j||||jS)N)rrr#)rprintTracebackr)rDrr#rs r getTracebackzFailure.getTracebacks2 Z (:6  {{}rc |ddlm}|j}|j}|dk(r|jsd}n|}|dk(r*|d|j |j xrdxsdfznj|d k(r]|jrd }nd }||d tj|jd tj|jd n|d|jrH|s.t|jt d|||td t|j||n |d k(s|d|d k(sH|tj |jd tj|jd t#|jt$r.|jd|jj'||||dk(r|d|j zyy)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)logrrz*--- Failure #%d%s--- z (pickled)  r Tracebackz"Traceback (failure with no frames)z: rz#Traceback (most recent call last): z Failure: z (chained Failure) z*--- End of Failure #%d --- )twisted.pythonrlogerrr"rr|rr!rrr}r~r,r8 traceupLengthEXCEPTION_CAUGHT_HERErrrvr)rDrrr#rr$ formatDetail hasFramess rrzFailure.printTracebacks < *::D JJ Y t'7'77L!L Y  ):: >F3GH w {{' @ g..tyy97;K;KDJJ;WY  4 5 ;;%djj-91lK*+2./ $++q, 77" kN dii()G,<, G Y  - : ; rc,|j||dy)z; Print a traceback as densely as possible. rr#NrrDrrs rrzFailure.printBriefTracebacks D"4WErc,|j||dy)zQ Print a traceback with detailed locals and globals information. rrNrrs rprintDetailedTracebackzFailure.printDetailedTracebacks D"4YGr)NNNF)rr)NFr)Nr) rrrr/rr8opcodeopmaprrFrrrrrrtr classmethodrrrrrrrrrintrrrrrrrrvrvs$G E<< .Lc'J:: 11 ; ;8.8.t # CC#J ,",,3 sTWCrs  .. "m8CK+@A    y +/`:i#R   8++<   ;  ;  LHmLH^ M    $$ D:"r