ML i_0UdZddlmZddlmZddlmZmZddlm Z ddl m Z m Z mZmZmZddlmZddlmZmZmZdd lmZdd lmZmZdd lmZdd lmZdd 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/m0Z0ddl1m2Z2dZ3de4d<dZ5de4d<dZ6de4d< d' d(dZ7 d)dZ8 d*dZ9d+dZ:d,dZ; d-dZ d1dZ?d2dZ@ d3d ZAd4d!ZBd5d"ZCd6d#ZD d7d$ZEd8d%ZFy&)9z!Type inference constraint solving) annotations) defaultdict)IterableSequence) TypeAlias) SUBTYPE_OF SUPERTYPE_OF Constraintinfer_constraintsneg_op) expand_type) prepare_sccsstrongly_connected_componentstopsort)join_type_list)meet_type_list meet_types) is_subtype)get_all_type_vars)AnyTypeInstanceNoneType ParamSpecType ProperType TupleTypeType TypeOfAny TypeVarIdTypeVarLikeTypeTypeVarTupleType TypeVarTypeUninhabitedType UnionType UnpackTypeget_proper_type) type_statezdict[TypeVarId, set[Type]] _TypeAliasBoundsz set[tuple[TypeVarId, TypeVarId]]Graphzdict[TypeVarId, Type | None] Solutionsc |Dcgc]}|j}}|sggfS|Dcic]}|j|}}g}|D]} |j| jD cgc] } | j||zvs| j"c} |j| jD cic]} | j|vs| j|  c} |r t |}||zDcic]}|g} }|D]2} | j ||zvs| | j j | 4|r|rt||z|||\} }ni} g}ni} g}| jD]\}}|s |D cgc]"} | jtk(s| j$}} |D cgc]"} | jtk(s| j$}} t||}| t||Dcgc] }||vs| c}r|| <g}|D]Y} | | vr|j | | |rt}d|_nt#t$j&}|j |[|s|s t)|||}||fScc}wcc}wcc} wcc} wcc}wcc} wcc} wcc}w)aSolve 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(). T)idextend extra_tvarsupdateskip_reverse_union_constraintstype_varappendsolve_with_dependentitemsopr targetr solve_oneget_varsr" ambiguousrr special_formpre_validate_solutions) original_vars constraintsstrictallow_polymorphicskip_unsatisfiedtvvars originals extra_varscvcmapcon solutions free_varscslowersupperssolutionres candidates P/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/mypy/solve.pysolve_constraintsrR)s(* *bBEE *D * 2v %23r3I3"$J TXA!$$dZFW:W144XY1==RaADD JJy| $+- &* ##I$:$:; JJy ! " -%S-E  >C +4YR/S&DA FsLI!I&I+ 1I+ I0 3I0  I5!I::I:I?'I? J J cRt||\}t||}ttt ||}t fd|DsigfStt t||}g}i} |dD]b} t fd| Dst| D cgc]} ||  c} |} | s9|j| j| | | j<d|D]<\} }| |vr|j| | ||vs&| j| |>g}|D]6}g}|D]} |jt| |j|8i}|D]!}t||}|j|#||D cgc]} | |  c} fScc} wcc} w)aSSolve 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. c38K|]}t|ywN) check_linear).0sccrLrMs rQ z'solve_with_dependent..sAS|C0Asrc3:K|]}| xr| ywrU)rWrArLrMs rQrYz'solve_with_dependent..s%?R6":~0fRj.0?s)transitive_closurecompute_dependencieslistrsetallrr choose_freer2r,addr-solve_iterativelyr/)rBr=r<rCgraphdmapsccs raw_batchesrJfree_solutionsrXrA best_freelubatchesbatchnext_bcrI flat_batchrOrLrMs @@rQr3r3s/t[AE66 eVV ?D ADA A2v w|D$789KIN1~ 9 ?3? ?#S$ArYr]$A=QI  ./8y||, 9-1 > 1IMM.+ , > 1IMM.+ , -G  &C NN49 % &w  /1I  E66B I>b~b)> >>9%B8?s ! F  F$ci}t|}|rt|dD]}||s||s|}nn|j|t||||}|||<|O|j D]d\} } | | k(r | |k(r'|| j ||j| | f| |k(s>|| j ||j| | ff|r|j D cic] \}} |  ||  } }} |D]"}||D chc]} t| | c} ||<$|D]"}||Dchc]}t|| c}||<$|Scc} }wcc} wcc}w)aSolve 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|jSrU)raw_id)xs rQz#solve_iteratively..s key)r_sortedremover7copyrbr4r )rmrdrLrMrIs_batchrA solvable_tvresultrjrkssubsltuts rQrcrcs I%jG &89 BbzVBZ   {#6+.{0CD!' + > JJL %DAqAvKq f% aV$Kq f% aV$ %+ D"+!2 Dgr1amBE DD DB6}t |ts|js!|ry|jj}@|r t|syt|fd}t |tr|j||St|dr|Sycc}w) aChoose 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. rNcL|jv|jjfSrU)r,rr)rsr<s rQrtzchoose_free..rs144}#&((CDF& b+ &299YY^^%F &&';< sJ KD$ $!!=O!PP,$? =)EsC0ct|tr>|jjdk(r%|xr!t t |j dSt|txr|jjdk(S)Nzbuiltins.tuplerzbuiltins.object)rrtypefullnamerr%args)tprs rQrr{s^"hBGG$4$48H$HL/ 0KLL b( # M(8(8!-C<<?D$ + 499FV0WTYY\\)) ructt}tt}|Dchc]}||f}}t|}|r|j}t|\}} |r| |vr| J|jt k(r|j | } } n| |j } } | | f|vrb||D chc]} |D]} | | f|vs | | f|vs| | fc} } z}|D]} | | f|vs || xx|| zcc<|D]} | | f|vs || xx|| zcc<|| D]}|| D]}t|||n%|jt k(r|j||j vr|D]1} | |j f|vs|| j|j3||j D]}t|||jn|jtk(sJ|j||j vr|D]1} |j | f|vs|| j|j3||j D]}t||j||r|||fScc}wcc} } w)awFind 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} ) rr_poprr5rr1add_secondary_constraintsr6rbr )tvarsr=rMrLrArd remainingrE is_linear target_idlowerupperrjrkrrs rQr\r\s,!%F %F',-RH-E-K I  MMO +1~ 9 e+( ((ttz! zz9u(!**uu~&  %u*+E e8KQVXYPZ^cPcA E /1:&1I.I / /u:&1I.I /Um A -AB-iR@A ATTZ xx6!**-- ,qzz?e+1IMM!((+ ,QZZ( C))RB C44<' ''xx6!**-- ,JJ?e+1IMM!((+ ,QZZ( C))QXXrB CU X &&  _.$s I#I4I;Ic tt|trtt|try|jt t ||t |jt t ||ty)zFAdd secondary constraints inferred between lower and upper (in place).N)rr%r#r/r_r rr )rKrrs rQrrs]/%()4 : IIc#E5*=>?IIc#E5,?@Aruci}|D]w}t}||D]}|t||z}||D]}|t||z}|D]&} | |k(r || f|vs| |f|vs|j| (t|||<y|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. )r_r8rbr^) rrdrLrMrOrAdepsrrothers rQr]r]s C u* (B HR' 'D (* (B HR' 'D ( E{E{e#r{e';  t*B  JrucxD]4}tfd||Drytfd||Ds4yy)zCheck there are only linear constraints between type variables in SCC. Linear are constraints like T <: S (while T <: F[S] are non-linear). c3HK|]}t|tywrUr8r^)rWrrXs rQrYzcheck_linear..<2xDI&<"Fc3HK|]}t|tywrUr)rWrrXs rQrYzcheck_linear.. rrT)any)rXrLrMrAs` rQrVrVsC  << < << <  ruc "t}|D]}t|j}t|ts)|j D]}t|t s||jk(r%|jtk(r|j|H|jt|t|j|j|jt|j|j||Dcgc] }||vs| c}Scc}w)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 = . 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. ) r_r%r6rr#r4r!rr5rrbr r )rKreverse_union_csrEp_targetrs rQr0r0su  T"188, h *  TdK0q000QTTZ5G(,,Q/ %((D&,HYHY)Z[$((A4E4EqttT)RS T T 7!Q&66A 77 7s ; D D cjt|Dchc]}|jc}t|zScc}w)z>Find type variables for which we are solving in a target type.)rr,r_)r6rBrAs rQr8r8,s(-f5 6bBEE 6T BB 6s0cg}t||D]\}}t|jr|j|-|t ||jsd}|D]q}|j t k(r$t |j|jsd}n:|j tk(sNt |j|jrod}n|r|j|j|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. TF) zipis_callable_protocolrr2rr5rr6r )rIr<r= new_solutionsrr~bound_satisfies_allrEs rQr;r;1s(*MM9- 1  .   #  =Aq}}!="&   44:%j.Q*/'44<' 188Q]]0S*/'  #$$Q]]3Q% & ruct|}t|tr.|jjrd|jj vSy)N__call__F)r%rrr is_protocolprotocol_members)rproper_ts rQrrRs:q!H(H%(--*C*CX]];;;; ruN)TFF) r<Sequence[TypeVarLikeType]r=list[Constraint]r>boolr?rr@rreturnz/tuple[list[Type | None], list[TypeVarLikeType]]) rBlist[TypeVarId]r=rr<rrCz dict[TypeVarId, TypeVarLikeType]rz'tuple[Solutions, list[TypeVarLikeType]]) rmrrdr)rLr(rMr(rr*)rrrint)rLIterable[Type]rMrrz Type | None)rXzlist[TypeVarLikeType]r<rrzTypeVarLikeType | None)F)rrrrrr)rEr rztuple[bool, TypeVarId | None])rrr=rrztuple[Graph, Bounds, Bounds])rKzset[Constraint]rrrrrNone) rrrdr)rLr(rMr(rz dict[TypeVarId, list[TypeVarId]])rXset[TypeVarId]rLr(rMr(rr)rKrrr)r6rrBrrr)rIlist[Type | None]r<rr=rrr)rrrr)G__doc__ __future__r collectionsrcollections.abcrrtyping_extensionsrr'mypy.constraintsrr r r r mypy.expandtyper mypy.graph_utilsrrr mypy.joinr mypy.meetrr mypy.subtypesr mypy.typeopsr mypy.typesrrrrrrrrrrr r!r"r#r$r%mypy.typestater&r(__annotations__r)r*rRr3rcrr7rarrr\rr]rVr0r8r;rr[rurQrs'"#.5\\'QQ$0$*$&1 16z66 :6 #" U,U!U U U  U 5 Up:? :?!:?#:?0 :? - :?z9 9#(9289BH99x BJ0 0/>00fN "G! G!)9G!!G!T B #(28BH%0 8:C  ," Bru