
    cg                       U d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	m
Z
 ddlZddlmZmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ e	rddlmZ dPdZ	 dQdRdZdSdZ i dddddd d!d"d#d$d%d&gifd'd(d)d*d+d,d-d.d/d0d1d2d%d3gifd4d5d6d7d8d9d:d;d<d=d>d?d@dAZ!dBe"dC<    G dD dE          Z# G dF dGe#          Z$ G dH dIe#          Z% G dJ dKej&                  Z'dTdOZ(dS )Uz,Checks for various exception related errors.    )annotationsN)	Generator)TYPE_CHECKINGAny)nodesobjects)InferenceContext)InferenceResultSuccessfulInferenceResult)checkers)utils)HIGH	INFERENCE)MessageDefinitionTuple)PyLinterreturnset[str]c                 V    dd} t          j        t          |           }d |D             S )Nobjr   r   boolc                V    t          | t                    ot          | t                    S N)
isinstancetype
issubclassBaseException)r   s    :lib/python3.11/site-packages/pylint/checkers/exceptions.py	predicatez&_builtin_exceptions.<locals>.predicate   s!    #t$$GC)G)GG    c                "    h | ]\  }}|j         S  )__name__.0_excs      r   	<setcomp>z&_builtin_exceptions.<locals>.<setcomp>"   s    111XaCL111r   )r   r   r   r   )inspect
getmembersbuiltins)r   memberss     r   _builtin_exceptionsr,      sB    H H H H  955G111111r   stmtnodes.NodeNGcontextInferenceContext | NoneEGenerator[tuple[nodes.NodeNG, SuccessfulInferenceResult], None, None]c              #    K   t          | t          j        t          j        f          r6| j        D ],}t          j        |          }|r|t          j        ur||fV  -dS | 	                    |          D ]}|t          j        u r| |fV  dS )zRecursively generate nodes inferred by the given statement.

    If the inferred value is a list or a tuple, recurse on the elements.
    Returns an iterator which yields tuples in the format
    ('original node', 'inferred node').
    N)
r   r   ListTupleeltsr   
safe_inferastroidUninferableinfer)r-   r/   eltinferreds       r   _annotated_unpack_inferr<   %   s       $U[122 9 	$ 	$C',,H $HG,?? $8m###JJw''  w** 	Hn r   bodylist[nodes.NodeNG]r   c                4    t          d | D                       S )z<Return whether the given statement node raises an exception.c              3  J   K   | ]}t          |t          j                  V  d S r   )r   r   Raiser$   nodes     r   	<genexpr>z_is_raising.<locals>.<genexpr><   s.      >>z$,,>>>>>>r   )any)r=   s    r   _is_raisingrF   :   s    >>>>>>>>r   E0701)zBad except clauses order (%s)bad-except-orderzUsed when except clauses are not in the correct order (from the more specific to the more generic). If you don't fix the order, some exceptions may not be caught by the most specific handler.E0702)z6Raising %s while only classes or instances are allowedraising-bad-typezkUsed when something which is neither a class nor an instance is raised (i.e. a `TypeError` will be raised).E0704)z2The raise statement is not inside an except clausemisplaced-bare-raiseag  Used when a bare raise is not used inside an except clause. This generates an error, since there are no active exceptions to be reraised. An exception to this rule is represented by a bare raise inside a finally clause, which might work, as long as an exception is raised inside the try block, but it is nevertheless a code smell that must not be relied upon.E0705zDException cause set to something which is not an exception, nor Nonebad-exception-causeziUsed when using the syntax "raise ... from ...", where the exception cause is not an exception, nor None.	old_names)E0703zbad-exception-contextE0710)zBRaising a new style class which doesn't inherit from BaseExceptionraising-non-exceptionzOUsed when a new style class which doesn't inherit from BaseException is raised.E0711)z8NotImplemented raised - should raise NotImplementedErrornotimplemented-raisedzAUsed when NotImplemented is raised instead of NotImplementedErrorE0712)z>Catching an exception which doesn't inherit from Exception: %scatching-non-exceptionzcUsed when a class which doesn't inherit from Exception is used as an exception in an except clause.W0702)zNo exception type(s) specifiedbare-exceptaJ  A bare ``except:`` clause will catch ``SystemExit`` and ``KeyboardInterrupt`` exceptions, making it harder to interrupt a program with ``Control-C``, and can disguise other problems. If you want to catch all exceptions that signal program errors, use ``except Exception:`` (bare except is equivalent to ``except BaseException:``).W0718z!Catching too general exception %sbroad-exception-caughtzIf you use a naked ``except Exception:`` clause, you might end up catching exceptions other than the ones you expect to catch. This can hide bugs or make it harder to debug programs when unrelated errors are hidden.)W0703zbroad-exceptW0705)z,Catching previously caught exception type %sduplicate-exceptzQUsed when an except catches a type that was already caught by a previous handler.W0706)z%The except handler raises immediatelytry-except-raisezUsed when an except handler uses raise as its first or only operator. This is useless because it raises back the exception immediately. Remove the raise operator or the entire try-except-raise block!W0707)z3Consider explicitly re-raising using %s'%s from %s'raise-missing-fromah  Python's exception chaining shows the traceback of the current exception, but also of the original exception. When you raise a new exception after another exception was caught it's likely that the second exception is a friendly re-wrapping of the first exception. In such cases `raise from` provides a better link between the two tracebacks in the final error.W0711)z;Exception to catch is the result of a binary "%s" operationbinary-op-exceptionz~Used when the exception to catch is of the form "except A or B:".  If intending to catch multiple, rewrite as "except (A, B):"W0715)z?Exception arguments suggest string formatting might be intendedraising-format-tuplezUsed when passing multiple arguments to an exception constructor, the first of them a string literal containing what appears to be placeholders intended for formattingW0716)zInvalid exception operation. %swrong-exception-operationzUsed when an operation is done against an exception, but the operation is not valid for the exception in question. Usually emitted when having binary operations between exceptions in except handlers.W0719)z!Raising too general exception: %sbroad-exception-raisedaA  Raising exceptions that are too generic force you to catch exceptions generically too. It will force you to use a naked ``except Exception:`` clause. You might then end up catching exceptions other than the ones you expect to catch. This can hide bugs or make it harder to debug programs when unrelated errors are hidden.z!dict[str, MessageDefinitionTuple]MSGSc                  *    e Zd ZdZddZdd
ZddZdS )BaseVisitorz/Base class for visitors defined in this module.checkerExceptionsCheckerrC   nodes.Raiser   Nonec                "    || _         || _        d S r   )_checker_node)selfrm   rC   s      r   __init__zBaseVisitor.__init__   s    


r   r   c                    |j         j                                        }t          | d|z   d           }|r ||           d S |                     |           d S )Nvisit_)	__class__r"   lowergetattrvisit_default)rt   rC   namedispatch_meths       r   visitzBaseVisitor.visit   se    ~&,,..hot<< 	%M$t$$$$$r   r%   r.   c                    dS )z)Default implementation for all the nodes.Nr!   rt   r%   s     r   r{   zBaseVisitor.visit_default   s      r   N)rm   rn   rC   ro   r   rp   )rC   r   r   rp   )r%   r.   r   rp   )r"   
__module____qualname____doc__ru   r~   r{   r!   r   r   rl   rl      sV        99   % % % %8 8 8 8 8 8r   rl   c                  "    e Zd ZdZd
dZddZd	S )ExceptionRaiseRefVisitorz4Visit references (anything that is not an AST leaf).rC   
nodes.Namer   rp   c                   |j         dk    r)| j                            d| j        t                     d S 	 t          t          |                    }n# t          j        $ r Y d S w xY w|D ]f\  }}t          |t          j                  rG| j                            |          r-| j                            d|j         | j        t                     gd S )NNotImplementedrT   rC   
confidenceri   argsrC   r   )r|   rr   add_messagers   r   listr<   r7   InferenceErrorr   r   ClassDef_is_overgeneral_exceptionr   )rt   rC   
exceptionsr%   	exceptions        r   
visit_namez#ExceptionRaiseRefVisitor.visit_name   s   9(( 	M%%'djT &    F	5d;;<<JJ% 	 	 	FF	 ' 		 		LAy5>  -99)DD )),"(	 *   			 		s   A A&%A&
nodes.Callc                   t          |j        t          j                  r|                     |j                   t          |j                  dk    rt          |j        d         t          j                  rnt          |j        d         j        t                    rK|j        d         j        }d|v sd|v r3d|v r1| j
                            d| j        t                     d S d S d S d S d S d S )N   r   %{}re   r   )r   funcr   Namer   lenr   Constvaluestrrr   r   rs   r   )rt   rC   msgs      r   
visit_callz#ExceptionRaiseRefVisitor.visit_call   s   di,, 	'OODI&&&	NNQ		49Q<55		 49Q<-s33		
 )A,$Ccz cSj SCZ ))* *     		 		 		 		 		 		   r   N)rC   r   r   rp   )rC   r   r   rp   )r"   r   r   r   r   r   r!   r   r   r   r      sB        >>   .     r   r   c                  >    e Zd ZdZddZdd	ZeZddZddZddZ	dS )ExceptionRaiseLeafVisitorz1Visitor for handling leaf kinds of a raise value.rC   nodes.Constr   rp   c                t    | j                             d| j        |j        j        j        t                     d S )NrJ   rC   r   r   )rr   r   rs   r   rx   r"   r   rt   rC   s     r   visit_constz%ExceptionRaiseLeafVisitor.visit_const   sA    !!%. 	 	" 	
 	
 	
 	
 	
r   instanceobjects.ExceptionInstancec                >    |j         }|                     |           d S r   )_proxiedvisit_classdef)rt   r   clss      r   visit_instancez(ExceptionRaiseLeafVisitor.visit_instance   s$    C     r   nodes.ClassDefc                    t          j        |          sDt          j        |          r2|j        r-| j                            d| j        t                     d S d S d S d S )NrR   r   )r   inherit_from_std_exhas_known_basesnewstylerr   r   rs   r   r   s     r   r   z(ExceptionRaiseLeafVisitor.visit_classdef  s    (.. 	53H3N3N 	} ))+( *     	 	 	 	 r   r%   nodes.Tuplec                V    | j                             d| j        dt                     d S )NrJ   tupler   )rr   r   rs   r   r   s     r   visit_tuplez%ExceptionRaiseLeafVisitor.visit_tuple  s9    !! 	 	" 	
 	
 	
 	
 	
r   r.   c                    t          |d|j        j                  }| j                            d| j        |t                     d S )Nr|   rJ   r   )rz   rx   r"   rr   r   rs   r   )rt   rC   r|   s      r   r{   z'ExceptionRaiseLeafVisitor.visit_default  sO    tVT^%<==!! 	 	" 	
 	
 	
 	
 	
r   N)rC   r   r   rp   )r   r   r   rp   )rC   r   r   rp   )r%   r   r   rp   )rC   r.   r   rp   )
r"   r   r   r   r   r   visit_exceptioninstancer   r   r{   r!   r   r   r   r      s        ;;
 
 
 
! ! ! !
 -   
 
 
 

 
 
 
 
 
r   r   c            
      Z    e Zd ZdZdZeZddddddffZd4 fdZ e	j
        dddddddd          d5d            Zd5dZd5dZd5dZd6d Zd7d"Z e	j
        d#          d8d%            Z e	j
        d#          d9d'            Z e	j
        d(d)d*d+d,d-d.          d7d/            Zd:d3Z xZS );rn   zException related checks.r   zovergeneral-exceptions)zbuiltins.BaseExceptionzbuiltins.Exceptioncsvz<comma-separated class names>z0Exceptions that will emit a warning when caught.)defaultr   metavarhelpr   rp   c                    t                      | _         | j        j        j        D ](}d|vr"t	          j        d| dt          ddd           )t                                                       d S )N.zSpecifying exception names in the overgeneral-exceptions option without module name is deprecated and support for it will be removed in pylint 3.0. Use fully qualified name (maybe 'builtins.z' ?) instead.z*pylint: Command line or configuration filer   pylint)categoryfilenamelinenomodule)	r,   linterconfigovergeneral_exceptionswarningswarn_explicitUserWarningsuperopen)rt   exc_namerx   s     r   r   zExceptionsChecker.open3  s    #6#8#8 *A 	 	H(" 
&Z CKZ Z Z )I#	 	 	 	 	r   rL   rJ   rR   rT   rN   re   ra   ri   rC   ro   c                   |j         |                     |           d S |j        |                     |           n|                     |           |j         }t          | |                              |           t          j        |          }||t          j
        u rd S t          | |                              |           d S r   )r&   _check_misplaced_bare_raisecause_check_raise_missing_from_check_bad_exception_causer   r~   r   r6   r7   r8   r   )rt   rC   exprr;   s       r   visit_raisezExceptionsChecker.visit_raiseC  s     8 	,,T222F: 	2**40000++D111x t,,224888#D)) 	x7+>> 	F!$--33H=====r   c                   |                                 }t          |t          j                  r!|                                r|j        dk    rd S |}t          j        t          j        f}|r3t          |j        |          s|j        }|rt          |j        |          t          j        f}|rt          |j        |          s|                     d|t                     d S d S )N__exit__rL   r   )
scoper   r   FunctionDef	is_methodr|   ExceptHandlerparentr   r   )rt   rC   r   currentignoresexpecteds         r   r   z-ExceptionsChecker._check_misplaced_bare_raise_  s    

ue/00	!!	 
j(	
 F &(9: 	%jAA 	%nG  	%jAA 	% ') 	QjBB 	Q3$4PPPPP	Q 	Qr   c                ~   t          j        |j                  }|t          j        dfv rdS t          |t          j                  r(|j        | 	                    d|t                     dS dS t          |t          j                  s3t          j        |          s!| 	                    d|t                     dS dS dS )zyVerify that the exception cause is properly set.

        An exception cause can be only `None` or an exception.
        NrN   r   )r   r6   r   r7   r8   r   r   r   r   r   r   r   r   )rt   rC   r   s      r   r   z,ExceptionsChecker._check_bad_exception_causet  s    
  ,,W($// 	FeU[)) 	U{ Y  !6Ti XXXXXY YE5>22 	U5;T<
 <
 	U 2)TTTTT	U 	U 	U 	Ur   c                   |j         d S t          j        |          }|sd S |j        d}t	          |j        t          j        t          j        f          r|j        	                                }| 
                    d|d| d|	                                dft                     d S t	          |j         t          j                  r$t	          |j         j        t          j                  s9t	          |j         t          j                  rY|j         j        |j        j        k    rA| 
                    d|d|	                                |j        j        ft                     d S d S d S )N	Exceptionra   z'except z as exc' and r&   r    )r&   r   !find_except_wrapper_node_in_scoper|   r   r   r   r   r4   	as_stringr   r   Callr   )rt   rC   containing_except_nodeclass_of_old_errors       r   r   z+ExceptionsChecker._check_raise_missing_from  s   8 	 F!&!H!N!N% 	F "& 	 "-05
EK7PQQ M%;%@%J%J%L%L"$@1@@@NN$$
    	 	 	 	 	 tx,,	48=%*55	 $(EJ//	 !7!<!AA		 $$..**,B,G,LM	      	 	 	 	r   handlernodes.ExceptHandlerr&   r   partr.   c                L   t          |t          j                  rGd |j        D             }t	          d |D                       rd S t          d |D                       rd S t          |t          j                  st          |t          j                  r}|j        vt          |j	        t          j                  r|j	        j        |j	        
                    |          r0|                     d|j	        |                                f           n0|                     d|j	        |                                f           d S t          j        |          sG|j        | j        vr;t          j        |          r)|                     d|j	        |j        f           d S d S d S d S )Nc                6    g | ]}t          j        |          S r!   )r   r6   )r$   r:   s     r   
<listcomp>zCExceptionsChecker._check_catching_non_exception.<locals>.<listcomp>  s#    BBB#(--BBBr   c              3  2   K   | ]}|t           j        u V  d S r   )r7   r8   rB   s     r   rD   zBExceptionsChecker._check_catching_non_exception.<locals>.<genexpr>  s*      DD447..DDDDDDr   c              3  l   K   | ]/}|o(t          j        |          pt          j        |           V  0d S r   )r   r   r   rB   s     r   rD   zBExceptionsChecker._check_catching_non_exception.<locals>.<genexpr>  s`           Y.t44WE<QRV<W<W8W     r   rV   rC   r   )r   r   r4   r5   rE   allr   r   r   r   	parent_ofr   r   r   r   r|   r,   r   )rt   r   r&   r   r;   s        r   _check_catching_non_exceptionz/ExceptionsChecker._check_catching_non_exception  s    c5;'' 	BBBBBHDD8DDDDD    %     
 #u~.. 	 #u{++ 	 w|U[99>El>P\++C00 $$0$\"nn..0 %      , ..**, !   
 F )#..	 88	 $S))   ,7<sxk !     	 	 	 	 r   nodes.TryExceptc                |  	 dd}d}d }g }|j         D ]}|rM ||          }|s d S | d S |D ]5}t          j        |          	t          	fd|D                       rd} n6t	          |j        d         g          r!|j        d         j        d	}|} ||          }|r|                     d
|           d S d S )Nr   r   r   list[InferenceResult] | Nonec                    g }| j         rZt          j        | j                   }t          |t          j                  rt          d |j        D                       }n|r|g}nd S |S )Nc                ^    h | ]*}t          |t          j        t          j        f          (|+S r!   )r   r   r   	Attribute)r$   r   s     r   r'   zdExceptionsChecker._check_try_except_raise.<locals>.gather_exceptions_from_handler.<locals>.<setcomp>  sA        )))ej%/5RSS%  r   )r   r   r6   r   r   r4   r   r5   )r   r   exceptions_in_handlers      r   gather_exceptions_from_handlerzQExceptionsChecker._check_try_except_raise.<locals>.gather_exceptions_from_handler  s     13J|  (-(8(F(F%3U[AA  !% -B-G  " "JJ +  "7!8JJ  4r   Fc              3  f   K   | ]+}t          j        t          j        |                    V  ,d S r   )r   is_subclass_ofr6   )r$   einferred_currents     r   rD   z<ExceptionsChecker._check_try_except_raise.<locals>.<genexpr>  sP         ,U-=a-@-@BRSS     r   r   Tr_   )rC   )r   r   r   r   )handlersr   r6   rE   rF   r=   r&   r   )
rt   rC   r   
bare_raisehandler_having_bare_raiseexceptions_in_bare_handlerr   excs_in_current_handlerexc_in_current_handlerr  s
            @r   _check_try_except_raisez)ExceptionsChecker._check_try_except_raise  sd   	 	 	 	* 
$(!CE"} 	U 	UG 
 +I*H*Q*Q'. EE- EE.E  *','78N'O'O$    !;      &+
 GLO,-- Y<?& Y!%J07-1O1OPW1X1X. U  !3:S TTTTTU Ur   rg   nodes.BinOpc                    t          |j        t          j                  rRd|j                                         d|j                                         d}|                     d||f           d S d S )NDid you mean '(, )' instead?rg   r   )r   r   r   r   leftr   rightr   rt   rC   
suggestions      r   visit_binopzExceptionsChecker.visit_binop!  s~    dk5#677 	Yg49+>+>+@+@ggDJDXDXDZDZgggJ8t:-XXXXX	Y 	Yr   nodes.Comparec                    t          |j        t          j                  r]d|j                                         dd                    d |j        D                        d}|                     d||f           d S d S )Nr  r  c              3  D   K   | ]\  }}|                                 V  d S r   )r   )r$   r%   os      r   rD   z2ExceptionsChecker.visit_compare.<locals>.<genexpr>.  s.      @@tq!Q[[]]@@@@@@r   r  rg   r   )	r   r   r   r   r  r   joinopsr   r  s      r   visit_comparezExceptionsChecker.visit_compare(  s    dk5#677 	YN$)"5"5"7"7 N N99@@tx@@@@@N N N  8t:-XXXXX	Y 	Yr   rX   rZ   r_   rc   rH   rV   r]   c           	        |                      |           g }t          |j                  }t          |j                  D ]@\  }}|j        [t          |j                  s|                     d|t                     ||dz
  k     r d}|                     d||t                     ht          |j        t          j                  r)|                     d||j        j        t                     	 t          t          |j                            }n# t          j        $ r Y w xY w|D ]E\  }}	t          |	t          j                  rt%          j        |	          r|	j        }	|                     ||	|           t          |	t          j                  smd	 |	                                D             }
|D ]:}||
v r4|j         d
|	j         }|                     d|j        |t2                     ;|                     |	          r<t          |j                  s(|                     d|	j        |j        t2                     |	|v r(|                     d|	j        |j        t2                     G|d |D             z  }BdS )zCheck for empty except.NrX   r   r   z-empty except clause should always appear lastrH   r   rc   c                F    g | ]}t          |t          j                  |S r!   )r   r   r   )r$   ancs     r   r   z5ExceptionsChecker.visit_tryexcept.<locals>.<listcomp>e  s:     % % %%c5>::%% % %r   z is an ancestor class of rZ   r   r]   c                    g | ]\  }}|S r!   r!   r#   s      r   r   z5ExceptionsChecker.visit_tryexcept.<locals>.<listcomp>  s    &D&D&Dvq#s&D&D&Dr   )r	  r   r  	enumerater   rF   r=   r   r   r   r   BoolOpopr   r<   r7   r   Instancer   r   r   r   r   	ancestorsr|   r   r   )rt   rC   exceptions_classesnb_handlersindexr   r   r   r   r   exc_ancestorsprevious_excs               r   visit_tryexceptz!ExceptionsChecker.visit_tryexcept2  s(    	$$T***(*$-(('66 F	E F	ENE7| EE"7<00 S$$]T$RRR K!O, IC$$*CD %    GL%,77 9E  )  #	 !    !%&=gl&K&K!L!LJJ-   H (2 * *OD)!!7#3  73I>>7 %.$6	66w	4PPP%i@@ ! % %#,#6#6#8#8% % %M );  '=8 %1%6"a"aQZQ_"a"aC ,, 2%,\%(+4	 -    55i@@ J J  ((4!*!('0	 )    !$66 ((.!*!('0	 )    #&D&D&D&D&DD""MF	E F	Es   1!DD%$D%r   r   r   c                    |                                 | j        j        j        v pGd|j        vo>|j        | j        j        j        v o&|                                j        t          j        k    S )Nr   )qnamer   r   r   r|   rootr   EXCEPTIONS_MODULE)rt   r   s     r   r   z+ExceptionsChecker._is_overgeneral_exception  sg    OO!3!JJ A).( A$+"4"KKA  %)@@	
r   )r   rp   )rC   ro   r   rp   )r   r   r&   r   r   r.   r   rp   )rC   r   r   rp   )rC   r
  r   rp   )rC   r  r   rp   )r   r   r   r   )r"   r   r   r   r|   rj   msgsoptionsr   r   only_required_for_messagesr   r   r   r   r   r	  r  r  r)  r   __classcell__)rx   s   @r   rn   rn   "  s       ##DD %K:J	 	

G       &U% 	 	> > >	 	>$Q Q Q Q*U U U U", , , ,\3 3 3 3j7U 7U 7U 7Ur &U%&ABBY Y Y CBY &U%&ABBY Y Y CBY &U%   KE KE KE KEZ
 
 
 
 
 
 
 
r   rn   r   r   rp   c                J    |                      t          |                      d S r   )register_checkerrn   )r   s    r   registerr4    s%    
-f5566666r   )r   r   r   )r-   r.   r/   r0   r   r1   )r=   r>   r   r   )r   r   r   rp   ))r   
__future__r   r*   r(   r   collections.abcr   typingr   r   r7   r   r   astroid.contextr	   astroid.typingr
   r   r   r   pylint.checkersr   pylint.interfacesr   r   pylint.typingr   pylint.lintr   r,   r<   rF   rj   __annotations__rl   r   r   BaseCheckerrn   r4  r!   r   r   <module>r@     s  
 3 2 2 " " " " " "    % % % % % % % % % % % % % %  " " " " " " " " , , , , , , E E E E E E E E       ! ! ! ! ! ! - - - - - - - - 0 0 0 0 0 0 %$$$$$$2 2 2 2 <@    *? ? ? ?
w+ w+  w+  	w+0 N	 
9:;1w+@  Aw+L  Mw+V  Ww+b  cw+t + 	M 
012uw+D  Ew+P  Qw+`  aw+r  sw+@  Aw+N  Ow+\  ]w+ w w w wt8 8 8 8 8 8 8 8&& & & & &{ & & &R*
 *
 *
 *
 *
 *
 *
 *
Zm
 m
 m
 m
 m
, m
 m
 m
`7 7 7 7 7 7r   