
    X-Ph]                       U d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z
 ddlmZmZmZmZ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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'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 dZ3de4d<   dZ5de4d<   dZ6de4d<   	 	 	 dTdUd"Z7dVd(Z8dWd-Z9dXd0Z:dYd4Z;dZd[d8Z<d\d<Z=d]d?Z>d^dFZ?d_dHZ@d`dJZAdadKZBdbdMZCdcdPZDdddRZEdSS )ez!Type inference constraint solving    )annotations)defaultdict)IterableSequence)	TypeAlias)
SUBTYPE_OFSUPERTYPE_OF
Constraintinfer_constraintsneg_opexpand_type)prepare_sccsstrongly_connected_componentstopsort)
join_types)meet_type_list
meet_types)
is_subtype)get_all_type_vars)AnyTypeInstanceNoneTypeParamSpecType
ProperType	TupleTypeType	TypeOfAny	TypeVarIdTypeVarLikeTypeTypeVarTupleTypeTypeVarTypeUninhabitedType	UnionType
UnpackTypeget_proper_type)
type_statezdict[TypeVarId, set[Type]]
_TypeAliasBoundsz set[tuple[TypeVarId, TypeVarId]]Graphzdict[TypeVarId, Type | None]	SolutionsTForiginal_varsSequence[TypeVarLikeType]constraintslist[Constraint]strictboolallow_polymorphicskip_unsatisfiedreturn/tuple[list[Type | None], list[TypeVarLikeType]]c                   d | D             sg g fS d | D             g |D ]O}                     fd|j        D                                            fd|j        D                        P|rt          |          }d z   D             }|D ].}|j        z   v r ||j                                     |           /|r |rt          z   |          \  }}	nqi }g }	nli }g }	|                                D ]S\  }
}|sd |D             }d |D             }t          ||          }|t          |fd	D                       s|||
<   Tg }D ]h}||v r|                    ||                    "|rt                      }d
|_        nt          t          j                  }|                    |           i|	s|st          || |          }||	fS )a  Solve type constraints.

    Return the best type(s) for type variables; each type can be None if the value of
    the variable could not be solved.

    If a variable has no constraints, if strict=True then arbitrarily
    pick UninhabitedType as the value of the type variable. If strict=False, pick AnyType.
    If allow_polymorphic=True, then use the full algorithm that can potentially return
    free type variables in solutions (these require special care when applying). Otherwise,
    use a simplified algorithm that just solves each type variable individually if possible.

    The skip_unsatisfied flag matches the same one in applytype.apply_generic_arguments().
    c                    g | ]	}|j         
S  id.0tvs     J/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/mypy/solve.py
<listcomp>z%solve_constraints.<locals>.<listcomp>=   s    ***bBE***    c                    i | ]
}|j         |S r8   r9   r;   s     r>   
<dictcomp>z%solve_constraints.<locals>.<dictcomp>A   s    333r333r@   c                6    g | ]}|j         z   v|j         S r8   r9   )r<   v
extra_varsvarss     r>   r?   z%solve_constraints.<locals>.<listcomp>E   s,    XXXA!$dZFW:W:W14:W:W:Wr@   c                2    i | ]}|j         v|j         |S r8   r9   )r<   rD   	originalss     r>   rB   z%solve_constraints.<locals>.<dictcomp>F   s)    RRRaAD	<Q<Q!$<Q<Q<Qr@   c                    i | ]}|g S r8   r8   r;   s     r>   rB   z%solve_constraints.<locals>.<dictcomp>M   s    .R.R.R"r2.R.R.Rr@   c                <    g | ]}|j         t          k    |j        S r8   )opr	   targetr<   cs     r>   r?   z%solve_constraints.<locals>.<listcomp>`   s&    CCC1adl.B.Bah.B.B.Br@   c                <    g | ]}|j         t          k    |j        S r8   )rK   r   rL   rM   s     r>   r?   z%solve_constraints.<locals>.<listcomp>a   s&    AAA1adj.@.@ah.@.@.@r@   Nc                    g | ]}|v|	S r8   r8   )r<   r=   rF   s     r>   r?   z%solve_constraints.<locals>.<listcomp>f   s    EEE"bnn2nnnr@   T)extendextra_tvarsupdateskip_reverse_union_constraintstype_varappendsolve_with_dependentitems	solve_oneget_varsr#   	ambiguousr   r   special_formpre_validate_solutions)r,   r.   r0   r2   r3   rN   cmapcon	solutions	free_varsr=   cslowersupperssolutionresrD   	candidaterE   rH   rF   s                     @@@r>   solve_constraintsrh   )   s   ( +*M***D 2v33]333I"$J T TXXXXXXXXYYYRRRR1=RRRSSSS B4[AA /S.Rz@Q.R.R.RD + +<4*,,,%%c*** ) 	#7z!;i$ $ Iyy III		jjll 	) 	)FB CCCCCFAAAAAF 00H xEEEE
EEE( ( !)	"C " "	>>JJy|$$$$  <+--	&*	###I$:;;	JJy!!!! F- F %S-EE	>r@   rF   list[TypeVarId]rH    dict[TypeVarId, TypeVarLikeType]'tuple[Solutions, list[TypeVarLikeType]]c                   t          | |          \  }t          | |          }t          t          t	          |           |                    }t          fd|D                       si g fS t          t          t          ||                              }g }i |d         D ]`}	t          fd|	D                       rBt          fd|	D             |          }
|
r$|	                    |
j
                   |
|
j
        <   a|D ]O\  }}||v r!|                             |                    ||v r!|                             |                    Pg }|D ]@}g }|D ]$}	|                    t          |	                     %|	                    |           Ai }|D ])}t          ||          }|                    |           *|fd|D             fS )aS  Solve set of constraints that may depend on each other, like T <: List[S].

    The whole algorithm consists of five steps:
      * Propagate via linear constraints and use secondary constraints to get transitive closure
      * Find dependencies between type variables, group them in SCCs, and sort topologically
      * Check that all SCC are intrinsically linear, we can't solve (express) T <: List[T]
      * Variables in leaf SCCs that don't have constant bounds are free (choose one per SCC)
      * Solve constraints iteratively starting from leaves, updating bounds after each step.
    c              3  :   K   | ]}t          |          V  d S N)check_linear)r<   sccrc   rd   s     r>   	<genexpr>z'solve_with_dependent.<locals>.<genexpr>   s/      AAS|C00AAAAAAr@   r   c              3  <   K   | ]}|          o|          V  d S rn   r8   )r<   r=   rc   rd   s     r>   rq   z'solve_with_dependent.<locals>.<genexpr>   s4      ??R6":~0fRj.??????r@   c                     g | ]
}|         S r8   r8   )r<   r=   rH   s     r>   r?   z(solve_with_dependent.<locals>.<listcomp>   s    $A$A$ArYr]$A$A$Ar@   c                     g | ]
}|         S r8   r8   )r<   r=   free_solutionss     r>   r?   z(solve_with_dependent.<locals>.<listcomp>   s    >>>b~b)>>>r@   )transitive_closurecompute_dependencieslistr   setallr   r   choose_freerV   r:   addrQ   solve_iterativelyrS   )rF   r.   r,   rH   graphdmapsccsraw_batchesra   rp   	best_freelubatchesbatchnext_bcr`   
flat_batchrf   ru   rc   rd   s      `               @@@r>   rW   rW      sM    /t[AAE66eVV<<D-c$ii>>??DAAAAADAAAAA 2vw|D$778899KIN1~ 
9 
9 ?????3????? 	9#$A$A$A$AS$A$A$A=QQI 9   .../8y|,  - -1	>>1IMM.+,,,	>>1IMM.+,,, G     	& 	&CNN499%%%%w.0I  

E66BB>>>>I>>>>>r@   r   r~   rc   rd   c                   i }t          |           }|rt          |d           D ]}||         s||         r|} nn|                    |           t          ||         ||                   }|||<   |e|                                D ]|\  }	}
|	|
k    r|	|k    r2||
                             |           |                    |	|
f           |
|k    r2||	                             |           |                    |	|
f           }|d |                                D             |D ]}fd||         D             ||<   |D ]}fd||         D             ||<   |S )a  Solve transitive closure sequentially, updating upper/lower bounds after each step.

    Transitive closure is represented as a linear graph plus lower/upper bounds for each
    type variable, see transitive_closure() docstring for details.

    We solve for type variables that appear in `batch`. If a bound is not constant (i.e. it
    looks like T :> F[S, ...]), we substitute solutions found so far in the target F[S, ...]
    after solving the batch.

    Importantly, after solving each variable in a batch, we move it from linear graph to
    upper/lower bounds, this way we can guarantee consistency of solutions (see comment below
    for an example when this is important).
    c                    | j         S rn   )raw_id)xs    r>   <lambda>z#solve_iteratively.<locals>.<lambda>   s     r@   keyNc                    i | ]
\  }}|||S rn   r8   )r<   r=   ss      r>   rB   z%solve_iteratively.<locals>.<dictcomp>   s    DDDgr1amBmmmr@   c                0    h | ]}t          |          S r8   r   )r<   ltsubss     r>   	<setcomp>z$solve_iteratively.<locals>.<setcomp>   #    AAAk"d++AAAr@   c                0    h | ]}t          |          S r8   r   )r<   utr   s     r>   r   z$solve_iteratively.<locals>.<setcomp>   r   r@   )ry   sortedremoverY   copyr|   rX   )r   r~   rc   rd   r`   s_batchr=   solvable_tvresultr   r   r   s              @r>   r}   r}      s     I%jjG
 %&8&8999 	 	Bbz VBZ   {###6+.{0CDD!'	+>  JJLL 	% 	%DAqAvvKq	f%%%aV$$$Kq	f%%%aV$$$;  %D ED!2!2DDDD B BAAAAfRjAAAr

 B BAAAAfRjAAAr

r@   Iterable[Type]Type | Nonec                   d}d}d}g }|D ]B}t          |          }t          |t                    r|j        s|                    |           C|}|s| st                      }d|_        |S | D ]:}||}t
          j        rt          j        ||g          }*t          ||          };|D ]}||}t          ||          }t          |          }	t          |          }
t          |	t                    st          |
t                    r`t          |	t                    r|n|}t          |t                    rt          |t                    sJ t          t          j        |          S ||r|}ndS ||}nt          ||          r|}nd}|S )zWSolve constraints by finding by using meets of upper bounds, and joins of lower bounds.NT)
source_any)r&   
isinstancer#   r[   rV   r'   infer_unionsr$   
make_unionr   r   r   r   r   from_another_anyr   )rc   rd   bottomtoprg   
new_uppersr   purL   p_topp_bottomr   s               r>   rY   rY      s   FC!I J ! !Q"o.. 	!bl 	!a   F  & #%%	"	
  	4 	4>FF& 4 #-vv.>??#FF33 * *;CCS&))CCC  Ev&&H%!! Z'%B%B &ug66BSSF
*j11UjW6U6UUUUy1jIIII	 	II 4				FC	 	  			r@   rp   list[TypeVarLikeType]TypeVarLikeType | Nonec                   t          |           dk    r| d         S t          d | D                       }t          |          }t          |t          t
          f          rdS g }| D ]<}t          |t                    r%|j        r|r dS |j                                        }=|rt          |          sdS t          | fd          }t          |t                    r|                    ||          S t          |d	          r|S dS )
a  Choose the best solution for an SCC containing only type variables.

    This is needed to preserve e.g. the upper bound in a situation like this:
        def dec(f: Callable[[T], S]) -> Callable[[T], S]: ...

        @dec
        def test(x: U) -> U: ...

    where U <: A.
       r   c                    g | ]	}|j         
S r8   )upper_bound)r<   ts     r>   r?   zchoose_free.<locals>.<listcomp>I  s    (D(D(D1(D(D(Dr@   Nc                .    | j         v| j         j        fS rn   )r:   r   )r   r,   s    r>   r   zchoose_free.<locals>.<lambda>a  s    14}#<adk"J r@   r   )valuesr   T)allow_tuple)lenr   r&   r   r#   r   r"   r   r   is_trivial_boundmincopy_modified)rp   r,   common_upper_boundcommon_upper_bound_pr   r=   bests    `     r>   r{   r{   7  sE    3xx1}}1v'(D(D(D(D(DEE*+=>>&((CDD  tF & &b+&& 	&29 	&  ttY^^%%F &';<<  t sJJJJKKKD$$$ Q!!=O!PPP,$??? 4r@   tpr   r   c                    t          | t                    r9| j        j        dk    r)|o&t	          t          | j        d                             S t          | t                    o| j        j        dk    S )Nzbuiltins.tupler   zbuiltins.object)r   r   typefullnamer   r&   args)r   r   s     r>   r   r   j  sg    "h MBG$48H$H$HL/
0K0KLLLb(##M(8<M(MMr@   rN   r
   tuple[bool, TypeVarId | None]c                z   t          | j        t                    r(t          | j        t                    rd| j        j        fS t          | j        t
                    r9t          | j        t
                    r| j        j        j        sd| j        j        fS t          | j        t                    rt          | j                  }t          |t                    rbt          |j                  dk    rJ|j        d         }t          |t                    r(t          |j        t                    rd|j        j        fS dS )zUFind out if this constraint represent a linear relationship, return target id if yes.Tr   r   )FN)r   origin_type_varr"   rL   r:   r   prefix	arg_typesr!   r&   r   r   rX   r%   r   )rN   rL   items      r>   find_linearr   p  s   !#[11 %ah,, 	%$$!#]33 %ah.. 	%qx7P 	%$$!#%566 * **fi(( 	*S->->!-C-C<?D$
++ *
49FV0W0W *TY\));r@   tvarstuple[Graph, Bounds, Bounds]c                P    t          t                    }t          t                    }d  D             t          |          }|r|                                }t          |          \  }}|r| v r|J |j        t
          k    r|j        |cn
||j        cfv r_ fd D             z   D ]}|fv r||xx         |         z  cc<    D ]}	|	fv r||	xx         |         z  cc<   |         D ]}
|         D ]}t          ||
|           n|j        t
          k    rm|j        ||j                 v r D ]-}	|	|j        fv r ||	         	                    |j                   .||j                 D ]}
t          ||
|j                   n~|j        t          k    sJ |j        ||j                 v r D ]-}|j        |fv r ||         	                    |j                   .||j                 D ]}t          ||j        |           |؉||fS )aw  Find transitive closure for given constraints on type variables.

    Transitive closure gives maximal set of lower/upper bounds for each type variable,
    such that we cannot deduce any further bounds by chaining other existing bounds.

    The transitive closure is represented by:
      * A set of lower and upper bounds for each type variable, where only constant and
        non-linear terms are included in the bounds.
      * A graph of linear constraints between type variables (represented as a set of pairs)
    Such separation simplifies reasoning, and allows an efficient and simple incremental
    transitive closure algorithm that we use here.

    For example if we have initial constraints [T <: S, S <: U, U <: int], the transitive
    closure is given by:
      * {} <: T <: {int}
      * {} <: S <: {int}
      * {} <: U <: {int}
      * {T <: S, S <: U, T <: U}
    c                    h | ]}||fS r8   r8   r;   s     r>   r   z%transitive_closure.<locals>.<setcomp>  s    ---RH---r@   Nc                :    h | ]}D ]}|fv |fv ||fS r8   r8   )r<   r   r   r~   lowerr   uppers      r>   r   z%transitive_closure.<locals>.<setcomp>  sV       u *+E
e8K8KQVXYPZ^cPcPcAPcPcPcPcr@   )r   ry   popr   rK   r   rU   add_secondary_constraintsrL   r|   r	   )r   r.   rd   rc   	remainingrN   	is_linear	target_idr   r   r   r   r~   r   r   s   `           @@@r>   rv   rv     s   , !%%F %%F--u---EK  I
 +CMMOO
  +1~~	9 $	Ce++(((tz!! z9uu(!*uu~&&        %   E  / /1:&&1III.III / /u:&&1III.IIIUm A A - A AB-iR@@@@AA TZx6!*--- , ,qz?e++1IMM!(+++QZ( C C))RBBBBC 4<''''x6!*--- , ,J?e++1IMM!(+++QZ( C C))QXrBBBBW  +CX &&  r@   rb   set[Constraint]r   r   r   Nonec           	     j   t          t          |          t                    r$t          t          |          t                    rdS |                     t	          t          ||t                                         |                     t	          t          ||t                                         dS )zFAdd secondary constraints inferred between lower and upper (in place).N)r   r&   r$   rS   ry   r   r   r	   )rb   r   r   s      r>   r   r     s    /%(()44 	: :  	IIc#E5*==>>???IIc#E5,??@@AAAAAr@    dict[TypeVarId, list[TypeVarId]]c                &   i }| D ]}t                      }||         D ]}|t          ||           z  }||         D ]}|t          ||           z  }| D ]*}	|	|k    r	||	f|v s|	|f|v r|                    |	           +t          |          ||<   |S )zCompute dependencies between type variables induced by constraints.

    If we have a constraint like T <: List[S], we say that T depends on S, since
    we will need to solve for S first before we can solve for T.
    )ry   rZ   r|   rx   )
r   r~   rc   rd   rf   r=   depsr   r   others
             r>   rw   rw     s     C  uu* 	( 	(BHR'''DD* 	( 	(BHR'''DD 	  	 E{{E{e##r{e';';t**BJr@   set[TypeVarId]c                      D ]J}t           fd||         D                       r dS t           fd||         D                       r dS KdS )zCheck there are only linear constraints between type variables in SCC.

    Linear are constraints like T <: S (while T <: F[S] are non-linear).
    c              3  R   K   | ]!}t          |t                              V  "d S rn   rZ   rx   )r<   r   rp   s     r>   rq   zcheck_linear.<locals>.<genexpr>  3      <<2xDII&&<<<<<<r@   Fc              3  R   K   | ]!}t          |t                              V  "d S rn   r   )r<   r   rp   s     r>   rq   zcheck_linear.<locals>.<genexpr>  r   r@   T)any)rp   rc   rd   r=   s   `   r>   ro   ro     s~    
   <<<<<<<<< 	55<<<<<<<<< 	55	4r@   c           
     
   t                      | D ]}t          |j                  }t          |t                    r|j        D ]}t          |t                    r||j        k    r&|j        t          k    r
                    |           H
                    t          |t          |j                  |j                             
                    t          |j        |j        |                     fd| D             S )a?  Avoid ambiguities for constraints inferred from unions during polymorphic inference.

    Polymorphic inference implicitly relies on assumption that a reverse of a linear constraint
    is a linear constraint. This is however not true in presence of union types, for example
    T :> Union[S, int] vs S <: T. Trying to solve such constraints would be detected ambiguous
    as (T, S) form a non-linear SCC. However, simply removing the linear part results in a valid
    solution T = Union[S, int], S = <free>. A similar scenario is when we get T <: Union[T, int],
    such constraints carry no information, and will equally confuse linearity check.

    TODO: a cleaner solution may be to avoid inferring such constraints in first place, but
    this would require passing around a flag through all infer_constraints() calls.
    c                    g | ]}|v|	S r8   r8   )r<   rN   reverse_union_css     r>   r?   z2skip_reverse_union_constraints.<locals>.<listcomp>  s$    777!Q&666A666r@   )ry   r&   rL   r   r$   rX   r"   r   rK   r   r|   r
   r   )rb   rN   p_targetr   r   s       @r>   rT   rT     s    uu T T"18,,h	** 		T  T TdK00 Tq000QTZ5G5G(,,Q///  %((D&,,HY)Z)Z[[[$((A4EqtT)R)RSSS7777r7777r@   rL   c                T    d t          |           D             t          |          z  S )z>Find type variables for which we are solving in a target type.c                    h | ]	}|j         
S r8   r9   r;   s     r>   r   zget_vars.<locals>.<setcomp>  s    666bBE666r@   )r   ry   )rL   rF   s     r>   rZ   rZ     s*    66-f55666TBBr@   r`   list[Type | None]c                   g }t          ||           D ]\  }}t          |j                  r|                    |           /|t	          ||j                  sd}|D ]^}|j        t          k    rt	          |j        |j                  sd} n/|j        t          k    rt	          |j        |j                  sd} n_|r|                    |j                   |                    |           |S )zCheck is each solution satisfies the upper bound of the corresponding type variable.

    If it doesn't satisfy the bound, check if bound itself satisfies all constraints, and
    if yes, use it instead as a fallback solution.
    NTF)	zipis_callable_protocolr   rV   r   rK   r   rL   r	   )r`   r,   r.   new_solutionsr   r   bound_satisfies_allrN   s           r>   r]   r]      s    (*MM9--    1.. 	   ###=Aq}!=!=="&   4:%%j.Q.Q%*/'E4<''
18Q]0S0S'*/'E" $$Q]333Qr@   r   c                    t          |           }t          |t                    r|j        j        rd|j        j        v S dS )N__call__F)r&   r   r   r   is_protocolprotocol_members)r   proper_ts     r>   r   r   A  sB    q!!H(H%% <(-*C <X];;;5r@   N)TFF)r,   r-   r.   r/   r0   r1   r2   r1   r3   r1   r4   r5   )
rF   ri   r.   r/   r,   ri   rH   rj   r4   rk   )
r   ri   r~   r*   rc   r)   rd   r)   r4   r+   )rc   r   rd   r   r4   r   )rp   r   r,   ri   r4   r   )F)r   r   r   r1   r4   r1   )rN   r
   r4   r   )r   ri   r.   r/   r4   r   )rb   r   r   r   r   r   r4   r   )
r   ri   r~   r*   rc   r)   rd   r)   r4   r   )rp   r   rc   r)   rd   r)   r4   r1   )rb   r/   r4   r/   )rL   r   rF   ri   r4   r   )r`   r   r,   r-   r.   r/   r4   r   )r   r   r4   r1   )F__doc__
__future__r   collectionsr   collections.abcr   r   typing_extensionsr   r(   mypy.constraintsr   r	   r
   r   r   mypy.expandtyper   mypy.graph_utilsr   r   r   	mypy.joinr   	mypy.meetr   r   mypy.subtypesr   mypy.typeopsr   
mypy.typesr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   mypy.typestater'   r)   __annotations__r*   r+   rh   rW   r}   rY   r{   r   r   rv   r   rw   ro   rT   rZ   r]   r   r8   r@   r>   <module>r     sg   ' ' ' " " " " " " # # # # # # . . . . . . . . 5 5 5 5 5 5 \ \ \ \ \ \ \ \ \ \ \ \ \ \ ' ' ' ' ' ' Q Q Q Q Q Q Q Q Q Q             0 0 0 0 0 0 0 0 $ $ $ $ $ $ * * * * * *                                   $ & % % % % %1 1 1 1 16 6 6 6 66	 6 6 6 6 #"U U U U Up:? :? :? :?z9 9 9 9x: : : :z0 0 0 0fN N N N N   "G! G! G! G!TB B B B   0
 
 
 
8 8 8 8:C C C C
   B     r@   