
    %^gPV                       U d dl mZ d dlmZ d dlmZ d dlmZmZm	Z	m
Z
mZmZm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mZ d d	lmZmZmZmZmZm Z m!Z! d d
l"m#Z#m$Z$ d dl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 d dl3m4Z4 eeeef   Z5de6d<    G d de
      Z7 G d d      Z8eee	ee,ee,   f      f   Z9 G d d      Z:ddZ;ddZ<y)    )annotations)defaultdict)contextmanager)DefaultDictIteratorList
NamedTupleOptionalTupleUnion)	TypeAlias)!remove_instance_last_known_values)join_simple)Keyliteralliteral_hashsubkeys)
Expression	IndexExpr
MemberExprNameExprRefExprTypeInfoVar)is_same_type
is_subtype)AnyTypeInstanceNoneTypePartialType
ProperType	TupleTypeType	TypeOfAnyTypeType	UnionType
UnpackTypefind_unpack_in_listget_proper_type)fill_typevars_with_any
_TypeAliasBindableExpressionc                  "    e Zd ZU ded<   ded<   y)CurrentTyper#   typeboolfrom_assignmentN)__name__
__module____qualname____annotations__     +lib/python3.12/site-packages/mypy/binder.pyr.   r.   !   s    
Jr7   r.   c                  "    e Zd ZdZdddZddZy)Framea  A Frame represents a specific point in the execution of a program.
    It carries information about the current types of expressions at
    that point, arising either from assignments to those expressions
    or the result of isinstance checks. It also records whether it is
    possible to reach that point at all.

    This information is not copied into a new Frame when it is pushed
    onto the stack, so a given Frame only has information about types
    that were assigned in that frame.
    c                J    || _         i | _        d| _        || _        d| _        y )NF)idtypesunreachableconditional_framesuppress_unreachable_warnings)selfr<   r?   s      r8   __init__zFrame.__init__2   s(    -/
 !2-2*r7   c           	     p    d| j                    d| j                   d| j                   d| j                   d	S )NzFrame(z, ))r<   r=   r>   r?   rA   s    r8   __repr__zFrame.__repr__9   s:    y4::,b1A1A0B"TE[E[D\\]^^r7   NF)r<   intr?   r0   returnNone)rI   str)r2   r3   r4   __doc__rB   rF   r6   r7   r8   r:   r:   &   s    	3_r7   r:   c                  R   e Zd ZU dZdZded<   d$dZd%dZd&d'dZd(d)d	Z	d*d+d
Z
d*d,dZddd-dZd$dZd$dZd.dZd/dZd/dZd0dZd1dZd2dZd3dZed4d       Z	 d(	 	 	 	 	 	 	 	 	 d5dZd6dZd7dZd8dZd$dZd$dZedd d ddd!	 	 	 	 	 	 	 	 	 	 	 	 	 d9d"       Zed:d#       Zy);ConditionalTypeBindera  Keep track of conditional types of variables.

    NB: Variables are tracked by literal expression, so it is possible
    to confuse the binder; for example,

    ```
    class A:
        a: Union[int, str] = None
    x = A()
    lst = [x]
    reveal_type(x.a)      # Union[int, str]
    x.a = 1
    reveal_type(x.a)      # int
    reveal_type(lst[0].a) # Union[int, str]
    lst[0].a = 'a'
    reveal_type(x.a)      # int
    reveal_type(lst[0].a) # str
    ```
    NzAssigns | Nonetype_assignmentsc                    d| _         t        | j                               g| _        g | _        i | _        i | _        d| _        t               | _	        g | _
        g | _        y )N   F)next_idr:   _get_idframesoptions_on_returndeclarationsdependencieslast_pop_changedset
try_framesbreak_framescontinue_framesrE   s    r8   rB   zConditionalTypeBinder.__init__Y   sa     T\\^,- 57 57 24 !&$'E')*,r7   c                D    | xj                   dz  c_         | j                   S )NrQ   )rR   rE   s    r8   rS   zConditionalTypeBinder._get_idy   s    ||r7   c                    ||}n3| j                   j                  |t                     j                  |       t	        |      D ]  }| j                  ||        y N)rW   
setdefaultrY   addr   _add_dependencies)rA   keyvalueelts       r8   rb   z'ConditionalTypeBinder._add_dependencies}   sM    =E((ce488?3<C""3.  r7   Fc                    t        | j                         |      }| j                  j                  |       | j                  j                  g        |S )z!Push a new frame into the binder.)r:   rS   rT   appendrU   )rA   r?   fs      r8   
push_framez ConditionalTypeBinder.push_frame   s@    $,,."341%%b)r7   c                P    t        ||      | j                  |   j                  |<   y r_   )r.   rT   r=   )rA   rc   r/   r1   indexs        r8   _putzConditionalTypeBinder._put   s"    (3D/(JE  %r7   c                    |dk  r|t        | j                        z  }t        |dd      D ];  }|| j                  |   j                  v s| j                  |   j                  |   c S  y Nr   )lenrT   ranger=   )rA   rc   rk   is       r8   _getzConditionalTypeBinder._get   sc    19S%%Eub"%Adkk!n***{{1~++C00 & r7   Tr1   c                  t        |t        t        t        f      sy t	        |      sy t        |      }|J d       || j                  vr)t        |      | j                  |<   | j                  |       | j                  |||       y )Nz/Internal error: binder tried to put non-literal)

isinstancer   r   r   r   r   rV   get_declarationrb   rl   )rA   exprtypr1   rc   s        r8   putzConditionalTypeBinder.put   s{    $J ABt}4 Q QQd'''%4T%:Dc"""3'		#sO,r7   c                ,    d| j                   d   _        y NTro   )rT   r>   rE   s    r8   r>   z!ConditionalTypeBinder.unreachable   s    &*B#r7   c                ,    d| j                   d   _        y r|   )rT   r@   rE   s    r8   r@   z3ConditionalTypeBinder.suppress_unreachable_warnings   s    8<B5r7   c                j    t        |      }|J d       | j                  |      }|y |j                  S )Nz/Internal error: binder tried to get non-literal)r   rs   r/   )rA   rx   rc   founds       r8   getzConditionalTypeBinder.get   s;    4 Q QQ		#=zzr7   c                :    t        d | j                  D              S )Nc              3  4   K   | ]  }|j                     y wr_   r>   .0rh   s     r8   	<genexpr>z7ConditionalTypeBinder.is_unreachable.<locals>.<genexpr>   s     6+Q1==+   anyrT   rE   s    r8   is_unreachablez$ConditionalTypeBinder.is_unreachable   s     6$++666r7   c                :    t        d | j                  D              S )Nc              3  4   K   | ]  }|j                     y wr_   )r@   r   s     r8   r   zJConditionalTypeBinder.is_unreachable_warning_suppressed.<locals>.<genexpr>   s     HKq122Kr   r   rE   s    r8   !is_unreachable_warning_suppressedz7ConditionalTypeBinder.is_unreachable_warning_suppressed   s    HDKKHHHr7   c                N    t        |      }|J d       | j                  |       y)z0Remove all references to a Node from the binder.Nz0Internal error: binder tried cleanse non-literal)r   _cleanse_key)rA   rx   rc   s      r8   cleansezConditionalTypeBinder.cleanse   s*    4 R RR#r7   c                ^    | j                   D ]  }||j                  v s|j                  |=   y)z/Remove all references to a key from the binder.N)rT   r=   )rA   rc   frames      r8   r   z"ConditionalTypeBinder._cleanse_key   s(    [[Eekk!KK$ !r7   c                   t        d |D              }|D cg c]  }|j                  r| }}d}|D ch c]  }|j                  D ]  }|  }}}|D ]  }| j                  |      }|D cg c]  }|j                  j	                  ||        }}t        d |D              rQ|rt        d |D              rf|d   }	|	J |	j                  t        | j                  j	                  |            }
t        |
t              r3t        fd|dd D              st        t        j                  |
	      n|dd D ]  }|J t        | j                  |   |j                        t        t              rt              t        t               sWt        t              sht        j"                  j$                  D cg c]  }t        t        |      t              r|  c}      }|| j                  |   k(  s| |t'        |d         r| j)                  |d
       d
} | | j*                  d   _        |S c c}w c c}}w c c}w c c}w )zUpdate the frame to reflect that each key will be updated
        as in one of the frames.  Return whether any item changes.

        If a key is declared as AnyType, only update it if all the
        options are the same.
        c              3  6   K   | ]  }|j                      y wr_   r   r   s     r8   r   z<ConditionalTypeBinder.update_from_options.<locals>.<genexpr>   s     >v!-vs   Fc              3  $   K   | ]  }|d u  
 y wr_   r6   r   xs     r8   r   z<ConditionalTypeBinder.update_from_options.<locals>.<genexpr>   s     7&619&6s   c              3  B   K   | ]  }|d uxr |j                      y wr_   rt   r   s     r8   r   z<ConditionalTypeBinder.update_from_options.<locals>.<genexpr>   s*      %AQA7a&7&7"77AQs   r   Nc              3  V   K   | ]   }|d uxr t        |j                         " y wr_   )r   r/   )r   tr/   s     r8   r   z<ConditionalTypeBinder.update_from_options.<locals>.<genexpr>   s-      J^QATM@l4&@@J^s   &)rQ   )
source_anyTrt   ro   )allr>   r=   rs   r   r   r/   r)   rV   rv   r   r$   from_another_anyr   r&   collapse_variadic_unionr!   
make_unionitemsr   rl   rT   )rA   rT   all_reachablerh   changedrc   keyscurrent_valueresulting_valuescurrent_typedeclaration_typeotherr   
simplifiedr/   s                 @r8   update_from_optionsz)ConditionalTypeBinder.update_from_options   sM    >v>>#9V1==!V9#7VqwwwV7C IIcNMIOPAC ?P7&677  %AQ% " +A.L+++$$D.t/@/@/D/DS/IJ*G4 JZ[\[]J^  #9#=#=JZ[D-ab1E ,,,&t'8'8'=tUZZPD "$	26t<!$
3
48S &/%9%9(,

b
1*_UVEWY`:aQ
b&
 &):):3)??#-D) 2* $L}Q?O,P		#tT	:k n +1jB#{ :7  QZ cs!   III/#II!Ic                
   |dkD  r| j                  |        | j                  j                         }| j                  j                         }|r|j	                  d| j                  d          | j                  |      | _        |S )zcPop a frame and return it.

        See frame_context() for documentation of fall_through.
        r   ro   )
allow_jumprT   poprU   insertr   rX   )rA   can_skipfall_throughresultoptionss        r8   	pop_framezConditionalTypeBinder.pop_frame  so     !OO\M*"((,,.NN1dkk"o. $ 8 8 Ar7   c              #     K   d}| j                   | j                   }t        t              | _         | j                    || _         yw)a  Push a new map to collect assigned types in multiassign from union.

        If this map is not None, actual binding is deferred until all items in
        the union are processed (a union of collected items is later bound
        manually by the caller).
        N)rO   r   list)rA   old_assignmentss     r8   accumulate_type_assignmentsz1ConditionalTypeBinder.accumulate_type_assignments  sE        ,"33O +D 1### /s   AAc           	     >   t        |      }| j                  !| j                  |   j                  ||f       y t        |t        t
        t        f      sy t        |      sy | j                  |       |y t        ||      sy t        |      }t        |      }t        | j                  ||            }t        |t              r|s| j                  ||       nt        |t              rt        |t              rt        d |j                   D              rt        t        | j                  |t#                           t"              rP|j                   D cg c]  }t        t        |      t"              r|n|! }	}| j                  |t        |	             nat        |t              r?t        |t              rt        d |j                   D              s| j                  ||       n| j                  ||       | j$                  D ]  }
| j'                  |
        y c c}w )Nc              3  N   K   | ]  }t        t        |      t                y wr_   )rv   r)   r   r   items     r8   r   z4ConditionalTypeBinder.assign_type.<locals>.<genexpr>`  s     ]L\DJt4h?L\   #%c              3  N   K   | ]  }t        t        |      t                y wr_   )rv   r)   r   r   s     r8   r   z4ConditionalTypeBinder.assign_type.<locals>.<genexpr>m  s     \K[4Jt4g>K[r   )r   rO   rg   rv   r   r   r   r   invalidate_dependenciesr   r)   most_recent_enclosing_typer   rz   r&   r   r   r   rZ   r   )rA   rx   r/   declared_typerestrict_any
p_declaredp_typeenclosing_typer   	new_itemsrr   s              r8   assign_typez!ConditionalTypeBinder.assign_type.  s   
 16  , !!$'..m/DE$J ABt}$$T*  $. $]3
 &()H)Ht)TUng.| HHT>* vw':y1]JL\L\]] ? ?hj QRT\ ',,,D #?4#8(CM,   HHT9Y/0(z9-\:K[K[\\ HHT=)HHT4 A OOA !s   $Hc                    t        |      }|J | j                  j                  |t                     D ]  }| j	                  |        y)a  Invalidate knowledge of types that include expr, but not expr itself.

        For example, when expr is foo.bar, invalidate foo.bar.baz.

        It is overly conservative: it invalidates globally, including
        in code paths unreachable from here.
        N)r   rW   r   rY   r   )rA   rx   rc   deps       r8   r   z-ConditionalTypeBinder.invalidate_dependenciesz  sE     4 $$((ce4Cc" 5r7   c           	     P   t        |      }t        |t              rt        |      S t	        |      }|J t        |      g| j
                  D cg c]E  }||j                  v r5t        ||j                  |   d         r|j                  |   j                  G c}z   }|d   S c c}w rn   )	r)   rv   r   rw   r   rT   r=   r   r/   )rA   rx   r/   rc   rh   	encloserss         r8   r   z0ConditionalTypeBinder.most_recent_enclosing_type  s    t$dG$"4((4 $T*+[[/
 agg~*T1773<?"C GGCL /
 
	
 }/
s   A
B#c                L   |dk  r|t        | j                        z  }t        | j                               }| j                  |dz   d  D ];  }|j
                  j                  |j
                         |j                  s5d|_        = | j                  |   j                  |       y )Nr   rQ   T)	rp   rU   r:   rS   rT   r=   updater>   rg   )rA   rk   r   rh   s       r8   r   z ConditionalTypeBinder.allow_jump  s     19S//00Edlln%UQY[)AKKqww'}}$(! * 	u%,,U3r7   c                `    | j                  | j                  d          | j                          y Nro   )r   r[   r>   rE   s    r8   handle_breakz"ConditionalTypeBinder.handle_break  s%    ))"-.r7   c                `    | j                  | j                  d          | j                          y r   )r   r\   r>   rE   s    r8   handle_continuez%ConditionalTypeBinder.handle_continue  s%    ,,R01r7   rQ   r   )r   break_framecontinue_framer?   	try_framec             #    K   t        | j                        dkD  sJ |r1| j                  j                  t        | j                        |z
         |r1| j                  j                  t        | j                        |z
         |r1| j
                  j                  t        | j                        dz
         | j                  |      }|r| j                  d       | | j                  ||       |r| j                  j                          |r| j                  j                          |r2| j
                  j                  t        | j                        dz
         yyw)a4  Return a context manager that pushes/pops frames on enter/exit.

        If can_skip is True, control flow is allowed to bypass the
        newly-created frame.

        If fall_through > 0, then it will allow control flow that
        falls off the end of the frame to escape to its ancestor
        `fall_through` levels higher. Otherwise control flow ends
        at the end of the frame.

        If break_frame > 0, then 'break' statements within this frame
        will jump out to the frame break_frame levels higher than the
        frame created by this call to frame_context. Similarly for
        continue_frame and 'continue' statements.

        If try_frame is true, then execution is allowed to jump at any
        point within the newly created frame (or its descendants) to
        its parent (i.e., to the frame that was on top before this
        call to frame_context).

        After the context manager exits, self.last_pop_changed indicates
        whether any types changed in the newly-topmost frame as a result
        of popping this frame.
        rQ   ro   N)rp   rT   r[   rg   r\   rZ   ra   ri   r   r   r   remove)rA   r   r   r   r   r?   r   	new_frames           r8   frame_contextz#ConditionalTypeBinder.frame_context  s    F 4;;!###$$S%5%CD  ''DKK(8>(IJOODKK 01 45OO$56	OOBx.!!#  $$&OO""3t{{#3a#78 s   EEc              #     K   t        | j                        dk(  sJ | j                          | j                  dd       t        | j                        dk(  sJ yw)zqA variant of frame_context for use at the top level of
        a namespace (module, function, or class).
        rQ   Tr   N)rp   rT   ri   r   rE   s    r8   top_frame_contextz'ConditionalTypeBinder.top_frame_context  sQ     
 4;;1$$$ootQ4;;1$$$s   AA)rI   rJ   )rI   rH   r_   )rc   r   rd   z
Key | NonerI   rJ   rG   )r?   r0   rI   r:   )ro   )
rc   r   r/   r#   r1   r0   rk   rH   rI   rJ   )rc   r   rk   rH   rI   zCurrentType | None)rx   r   ry   r#   r1   r0   rI   rJ   )rx   r   rI   Type | None)rI   r0   )rx   r   rI   rJ   )rc   r   rI   rJ   )rT   zlist[Frame]rI   r0   )r   r0   r   rH   rI   r:   )rI   zIterator[Assigns])
rx   r   r/   r#   r   r   r   r0   rI   rJ   )rx   r,   rI   rJ   )rx   r,   r/   r#   rI   r   )rk   rH   rI   rJ   )r   r0   r   rH   r   rH   r   rH   r?   r0   r   r0   rI   Iterator[Frame])rI   r   ) r2   r3   r4   rL   rO   r5   rB   rS   rb   ri   rl   rs   rz   r>   r@   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r6   r7   r8   rN   rN   @   sX   , (,n+-@/K KO 
-+=7
I%EN& 0 0 ^cJJ&*J;FJVZJ	JX#
4 
 "'79 79 	79
 79 79  79 79 
79 79r % %r7   rN   c                ,   t        | t              rt        | j                  t              r2| j                  j                  }t        t        |      t              s|S y t        | j                  t              rt        t        | j                              S y r_   )
rv   r   noder   r/   r)   r    r   r%   r*   )rx   r/   s     r8   rw   rw     sh    $ dii%99>>Dod3[A  		8,2499=>>r7   c                   g }g }| j                   D ]@  }t        |      }t        |t              r|j	                  |       0|j	                  |       B t        |      dk  r| S t        |d       }|d   }|d   }t        |j                         }|| S |j                   |   }t        |t              sJ t        |j                        }	t        |	t              s| S |	j                  j                  dk(  sJ |j                   |dz   d }
t        |j                         t        |
      k  r| S |
r|j                   t        |
       d |
k7  r| S |
r|j                   dt        |
        }n|j                   }|	j                  d   }t        |dd       D ]%  \  }}|j                   ||g|dz   z  z   |
z   k7  s#| c S  |j                   ||gt        | j                         dz
  z  z   |gz   |
z   k7  r| S t        |j                         dk(  r|	j                         }nt        ||gz   |
z   |j                        }t!        j"                  |g|z         S )	a  Simplify a union involving variadic tuple if possible.

    This will collapse a type like e.g.
        tuple[X, Z] | tuple[X, Y, Z] | tuple[X, Y, Y, *tuple[Y, ...], Z]
    back to
        tuple[X, *tuple[Y, ...], Z]
    which is equivalent, but much simpler form of the same type.
    rQ   c                ,    t        | j                        S r_   )rp   r   )r   s    r8   <lambda>z)collapse_variadic_union.<locals>.<lambda>  s    CLr7   )rc   r   ro   Nzbuiltins.tuple)fallback)r   r)   rv   r"   rg   rp   sortedr(   r'   r/   r   fullnameargs	enumeratecopy_modifiedpartial_fallbackr&   r   )ry   tuple_itemsother_itemsr   p_tfirstlastunpack_indexunpackunpackedsuffixprefixargrr   itr   s                   r8   r   r     s<    KKYYa c9%s#q!  ;1
*@AKNEr?D&tzz2L
ZZ%Ffj)))v{{+Hh)
==!!%5555ZZq(*+F 5;;#f+%
%++s6{ln-7
^F|, --
C;q,-288vQ/&88J .
 zzVses399~'9::fXENN

5;;1#113
v069DDYDYZ
{ :;;r7   N)rx   r,   rI   r   )ry   r&   rI   r#   )=
__future__r   collectionsr   
contextlibr   typingr   r   r   r	   r
   r   r   typing_extensionsr   r+   mypy.erasetyper   	mypy.joinr   mypy.literalsr   r   r   r   
mypy.nodesr   r   r   r   r   r   r   mypy.subtypesr   r   
mypy.typesr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   mypy.typevarsr*   r,   r5   r.   r:   AssignsrN   rw   r   r6   r7   r8   <module>r     s    " # % R R R 5 < ! = = Z Z Z 2    1!&y*h'F!G J G* 
_ _. j$uT8D>-A'B"CC
Dj% j%Z9<r7   