U
    hW                  
   @  s  d dl mZ d dlZd dlm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 d dl
mZ d dl
mZ d dl
mZ d d	l
mZ d d
l
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dl
mZ d dlZddlmZ d dlmZ d dlm Z  d dlm!Z! d dlm"Z" d dlm#Z# d dlm$Z$ d dlm%Z% d dlm&Z& d dlm'Z' d d lm(Z( d d!lm)Z) d d"lm*Z* d d#lm+Z+ d d$lm,Z, d d%lm-Z- d d&lm.Z. d d'lm/Z/ d d(lm0Z0 d d)lm1Z1 ed*ed+Z2ed,Z3ed-d.d/Z4ed0d.d1Z5ed2Z6ed3d.d/Z7ej8r^d d4l9m:Z: ne;dZ:d5d6d7d8d9Z<eee e=eee/d:f Z>G d;d< d<e)Z?G d=d> d>e)e2 Z@G d?d@ d@e)e3e7f ZAe&dA ZBddBddCdDdEdFdGdHd6dIdDdJdKdLZCdEdEdMdNdOZDdPdQdRdSdTdUZEdddVdFdFdWdXd5dYdZd[ZFdd\dFdFdWd5d]d^d_ZGdFdFdFd`dadbZHdcd6dMdddeZId5dfdgdhdiZJd5d6dMdjdkZKdldmdMdndoZLdEdpdMdqdrZMdEdsdMdtduZNdvdDdMdwdxZOdEdydMdzd{ZPddEd6d6d|d}d~dZQedFdFdMddZRedDdDdMddZRedEdEdMddZRdEdEdMddZReddd6dddZSedddEdddZSdd6ddddZSdEdDdddZTd5d6dMddZUd5d6dMddZVd5ddMddZWd5dd6dddZXddd5dFdd6dddZYdDdFdMddZZG dd de)Z[ede[d+Z\G dd dee\ Z]ede[d.dZ^G dd dee^ Z_edeedef  d+Z`G dd dee` ZaG dd dZbeb ZcereZdnecZdecj&ZedS )    )annotationsN)deque)Any)Callable)Dict
ForwardRef)Generic)Iterable)Mapping)NewType)NoReturn)Optional)overload)Set)Tuple)Type)TYPE_CHECKING)TypeVarUnion   )compat)	Annotated)Concatenate)dataclass_transform)Final)final)get_args)
get_origin)Literal)NotRequired)	ParamSpec)Protocol)SupportsIndex)	TypeAlias)	TypedDict)	TypeGuard)Self)TypeAliasType)Never)LiteralString_T)bound_KT_KT_coT)	covariant
_KT_contra)contravariant_VT_VT_co)NoneTyper   bool)typreturnc                 C  s   t | to| jdkS )NNone)
isinstancer   __forward_arg__)r7    r<   :/tmp/pip-unpacked-wheel-y9ln43lq/sqlalchemy/util/typing.pyis_fwd_noneM   s    r>   zGenericProtocol[Any]c                   @  s   e Zd ZU dZded< dS )ArgsTypeProtocolz_protocol for types that have ``__args__``

    there's no public interface for this AFAIK

    Tuple[_AnnotationScanType, ...]__args__N__name__
__module____qualname____doc____annotations__r<   r<   r<   r=   r?   V   s   
r?   c                   @  s"   e Zd ZU dZded< ded< dS )GenericProtocolzXprotocol for generic types.

    this since Python.typing _GenericAlias is private

    r@   rA   Type[_T]
__origin__NrB   r<   r<   r<   r=   rH   `   s   
rH   c                   @  s*   e Zd ZddddZddddd	Zd
S )SupportsKeysAndGetItemzIterable[_KT])r8   c                 C  s   d S Nr<   )selfr<   r<   r=   keysu       zSupportsKeysAndGetItem.keysr.   r4   )_SupportsKeysAndGetItem__kr8   c                 C  s   d S rL   r<   )rM   rP   r<   r<   r=   __getitem__w   rO   z"SupportsKeysAndGetItem.__getitem__N)rC   rD   rE   rN   rQ   r<   r<   r<   r=   rK   t   s   rK   *Fstr_cleanup_fninclude_generic_already_seenz	Type[Any]_AnnotationScanTypestrzMapping[str, Any]z#Optional[Callable[[str, str], str]]zOptional[Set[Any]])cls
annotationoriginating_modulelocals_rT   rU   rV   r8   c          	        s   |}t |r|j}t|tr:r*|}t|d}rt|rt|s dkr\t  | krh|S  | t	 fdd|j
D }t||S |S )a;  Resolve annotations that may be string based into real objects.

    This is particularly important if a module defines "from __future__ import
    annotations", as everything inside of __annotations__ is a string. We want
    to at least have generic containers like ``Mapped``, ``Union``, ``List``,
    etc.

    r\   in_classNc              
   3  s$   | ]}t | d V  qdS )rS   N)de_stringify_annotation.0elemrV   rY   rU   r\   r[   rT   r<   r=   	<genexpr>   s   
z*de_stringify_annotation.<locals>.<genexpr>)
is_fwd_refr;   r:   rX   eval_expression
is_generic
is_literalsetaddtuplerA   _copy_generic_annotation_with)	rY   rZ   r[   r\   rT   rU   rV   Zoriginal_annotationelementsr<   rc   r=   r_   ~   s8    

   


r_   )type_r8   c              	   C  sb   t | r^t| ttttjtjtjtj	tj
fkr^tdt| s^t| tdd t| D S | S )zfCorrect dict['x', 'y'] into dict[ForwardRef('x'), ForwardRef('y')]
    and similar for list, set

    z3typing.(?:Dict|List|Set|.*Mapping|.*Sequence|.*Set)c                 S  s"   g | ]}t |trt|n|qS r<   )r:   rX   r   r`   r<   r<   r=   
<listcomp>   s   z,fixup_container_fwd_refs.<locals>.<listcomp>)rg   r   dictri   listcollections_abc
MutableSetMutableMappingMutableSequencer   Sequencerematchrepr__class_getitem__rk   r   rn   r<   r<   r=   fixup_container_fwd_refs   s6    	 r|   zGenericProtocol[_T]r@   rI   )rZ   rm   r8   c                 C  s"   t | dr| |S | j| S d S )N	copy_with)hasattrr}   rJ   )rZ   rm   r<   r<   r=   rl      s    

rl   r]   zOptional[Mapping[str, Any]]zOptional[Type[Any]])
expressionmodule_namer\   r^   r8   c          	   
   C  s   zt j| j}W n8 tk
rH } ztd| d|  |W 5 d }~X Y nX zH|d k	rt|j}||j| || t	| ||}nt	| ||}W n2 t
k
r } ztd| |W 5 d }~X Y nX |S d S )NModule z9 isn't present in sys.modules; can't evaluate expression z"Could not de-stringify annotation )sysmodules__dict__KeyError	NameErrorrp   
setdefaultrC   updateeval	Exception)	r   r   r\   r^   base_globalskeZcls_namespacerZ   errr<   r<   r=   rf      s,    

rf   r\   )namer   r\   r8   c                C  s   d| krt | ||dS ztj| j}W n8 tk
r^ } ztd| d|  |W 5 d }~X Y nX z
||  W S  tk
r } zDztj|  W  W Y 0S  tk
r   Y nX td|  d| |W 5 d }~X Y nX d S )N.r   r   z2 isn't present in sys.modules; can't resolve name zCould not locate name z in module )rf   r   r   r   r   r   builtins)r   r   r\   r   r   r<   r<   r=   eval_name_only  s,    
r   )r   r   r8   c                 C  s8   zt | |}W n tk
r&   |  Y S X t|d| S d S )NrC   )r   r   getattr)r   r   objr<   r<   r=   resolve_name_to_real_class_name?  s
    
r   zOptional[Any]c                 C  s   | d k	ot | tjkS rL   )r   _type_tuplesr   r{   r<   r<   r=   	is_pep593H  s    r   zTypeGuard[Iterable[Any]])r   r8   c                 C  s   t | tjot | ttf S rL   )r:   rr   r
   rX   bytes)r   r<   r<   r=   is_non_string_iterableL  s     r   c                 C  s   t | tjkS rL   )r   r   r    r{   r<   r<   r=   rh   R  s    rh   zOptional[_AnnotationScanType]zTypeGuard[NewType]c                 C  s
   t | dS )N__supertype__r~   r{   r<   r<   r=   
is_newtypeV  s    r   zTypeGuard[GenericProtocol[Any]]c                 C  s   t | dot | dS )NrA   rJ   r   r{   r<   r<   r=   rg   ^  s    rg   zTypeGuard[TypeAliasType]c                 C  s   t | rt| jS t| tjS rL   )rg   	is_pep695rJ   r:   _type_instancesr)   r{   r<   r<   r=   r   b  s    
r   r   c                 C  s   | j }t|r|j }q|S rL   )r   r   )rn   Z
super_typer<   r<   r=   flatten_newtypel  s    r   zSet[Any]c                   s   t    fdd| }t|trzt  }t|}|rv| }t|trV|| q4||tksjt|rndn| q4|S |hS dS )zExtracts the value from a TypeAliasType, recursively exploring unions
    and inner TypeAliasType to flatten them into a single set.

    Forward references are not evaluated, so no recursive exploration happens
    into them.
    c                   sH   |  kr| S   |  t| s"| S | j}t|s4|S fdd|jD S )Nc                   s   g | ]} |qS r<   r<   ra   t)recursive_valuer<   r=   ro     s     z:pep695_values.<locals>.recursive_value.<locals>.<listcomp>)rj   r   Z	__value__is_unionrA   )Z
inner_typevalue_seenr   r<   r=   r   |  s    
z&pep695_values.<locals>.recursive_valueN)	ri   r:   rq   r   popleftextendrj   r5   r>   )rn   restypesstackr   r<   r   r=   pep695_valuess  s    

 r   zTypeGuard[ForwardRef])rn   check_genericcheck_for_plain_stringr8   c                   sN    rt | trdS t | tjr"dS |rFt| rFt fdd| jD S dS d S )NTc                 3  s   | ]}t |d  dV  qdS )Tr   N)re   )ra   argr   r<   r=   rd     s     zis_fwd_ref.<locals>.<genexpr>F)r:   rX   r   r   rg   anyrA   )rn   r   r   r<   r   r=   re     s    re   c                 C  s   d S rL   r<   r{   r<   r<   r=   de_optionalize_union_types  s    r   c                 C  s   d S rL   r<   r{   r<   r<   r=   r     s    c                 C  s   d S rL   r<   r{   r<   r<   r=   r     s    c                 C  s   t | rt| dS t| rt| rtjr4t| j}nRt| g}t }|r||	 }|jD ]"}t|rn|
| qV|| qVqD|d dd |D }t| S | S dS )zGiven a type, filter out ``Union`` types that include ``NoneType``
    to not include the ``NoneType``.

    Contains extra logic to work on non-flattened unions, unions that contain
    ``None`` (seen in py38, 37)

    FNc                 S  s    h | ]}|t k	rt|s|qS r<   )r5   r>   r   r<   r<   r=   	<setcomp>  s       z-de_optionalize_union_types.<locals>.<setcomp>)re   #_de_optionalize_fwd_ref_union_typesr   includes_noner   Zpy39ri   rA   r   r   appendrj   discardmake_union_type)rn   r7   Zstack_of_unionsZu_typrb   r<   r<   r=   r     s"    



r   zLiteral[True])rn   return_has_noner8   c                 C  s   d S rL   r<   rn   r   r<   r<   r=   r     s    r   zLiteral[False]c                 C  s   d S rL   r<   r   r<   r<   r=   r     s    z Union[_AnnotationScanType, bool]c                 C  s  | j }td|}|r4|ddd }|dkrJ|r<dS t|dS |dkr&d	|dkrg }g }d
}|dD ]`}|d	kr|d7 }n@|dkr|d8 }n.|d
kr|dkr|d|  |	  qx|| qxntd|d}dd |D }	|rt
|t
|	kS |	r t|	 S tS n|r0dS | S td|}
d|
k}|rR|S |r~ddd |
D }|rzt|S tS | S )zreturn the non-optional type for Optional[], Union[None, ...], x|None,
    etc. without de-stringifying forward refs.

    unfortunately this seems to require lots of hardcoded heuristics

    z^(.+?)\[(.+)\]$r   r   r   T   r   [r   ], z,\s*c                 S  s   g | ]}|d krt |qS )r9   r   r`   r<   r<   r=   ro     s      z7_de_optionalize_fwd_ref_union_types.<locals>.<listcomp>Fz\s*\|\s*r9   |c                 s  s   | ]}|d kr|V  qdS )r9   Nr<   )ra   pr<   r<   r=   rd     s      z6_de_optionalize_fwd_ref_union_types.<locals>.<genexpr>)r;   rw   rx   groupsplitr   r   joinstripclearlenr   r*   )rn   r   rZ   mmZg1rm   currentZignore_commacharpartsZpipe_tokensZhas_noneZanno_strr<   r<   r=   r     sF    



)r   r8   c                  G  s   t |  S )zMake a Union type.r   )r   r<   r<   r=   r   $  s    r   c                 C  s   t | rt| dS t| r0tdd t| D S t| rHtt| d S t| rftdd t| D S t	| rxt| j
S z| tdfkpt| W S  tk
r   Y dS X dS )a.  Returns if the type annotation ``type_`` allows ``None``.

    This function supports:
    * forward refs
    * unions
    * pep593 - Annotated
    * pep695 - TypeAliasType (does not support looking into
    fw reference of other pep695)
    * NewType
    * plain types like ``int``, ``None``, etc
    Tc                 s  s   | ]}t |V  qd S rL   r   r   r<   r<   r=   rd   9  s     z includes_none.<locals>.<genexpr>r   c                 s  s   | ]}t |V  qd S rL   r   r   r<   r<   r=   rd   =  s     NF)re   r   r   r   r   r   r   r   r   r   r   r5   r>   	TypeErrorr{   r<   r<   r=   r   *  s    

r   c                 C  s2   t | tp0t| dp0| jdkp0t| jd jdkS )NrJ   )typingtyping_extensionsr   )r:   typer~   rD   __mro__r{   r<   r<   r=   	is_a_typeI  s    
r   zTypeGuard[ArgsTypeProtocol]c                 C  s   t | ddS )Nr   Z	UnionType)is_origin_ofr{   r<   r<   r=   r   R  s    r   z'Union[Tuple[Type[Any], ...], Type[Any]])rn   	class_objr8   c                 C  s(   t | }|dkrdS t|to&t||S )z[return True if the given type has an __origin__ that shares a base
    with the given classNF)r   r:   r   
issubclass)rn   r   originr<   r<   r=   is_origin_of_clsV  s    r   )modulezOptional[str])rn   namesr   r8   c                G  s4   t | }|dkrdS t||ko2|dkp2|j|S )z\return True if the given type has an __origin__ with the given name
    and optional module.NF)r   _get_type_namerD   
startswith)rn   r   r   r   r<   r<   r=   r   c  s    r   c                 C  s4   t jr| jS t| dd }|d kr,t| dd }|S d S )NrC   _name)r   py310rC   r   )rn   Ztyp_namer<   r<   r=   r   r  s    r   c                   @  s@   e Zd ZddddddZdddddd	Zddd
ddZdS )DescriptorProtoobjectr   instanceownerr8   c                 C  s   d S rL   r<   rM   r   r   r<   r<   r=   __get__~  rO   zDescriptorProto.__get__r9   r   r   r8   c                 C  s   d S rL   r<   rM   r   r   r<   r<   r=   __set__  rO   zDescriptorProto.__set__r   r8   c                 C  s   d S rL   r<   rM   r   r<   r<   r=   
__delete__  rO   zDescriptorProto.__delete__N)rC   rD   rE   r   r   r   r<   r<   r<   r=   r   }  s   r   _DESCc                   @  sH   e Zd ZdZerDddddddZdddd	d
dZdddddZdS )DescriptorReferencea  a descriptor that refers to a descriptor.

    used for cases where we need to have an instance variable referring to an
    object that is itself a descriptor, which typically confuses typing tools
    as they don't know when they should use ``__get__`` or not when referring
    to the descriptor assignment as an instance variable. See
    sqlalchemy.orm.interfaces.PropComparator.prop

    r   r   r   r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zDescriptorReference.__get__r9   r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zDescriptorReference.__set__r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zDescriptorReference.__delete__NrC   rD   rE   rF   r   r   r   r   r<   r<   r<   r=   r     s
   
r   _DESC_co)r-   r0   c                   @  sH   e Zd ZdZerDddddddZdddd	d
dZdddddZdS )RODescriptorReferenceza descriptor that refers to a descriptor.

    same as :class:`.DescriptorReference` but is read-only, so that subclasses
    can define a subtype as the generically contained element

    r   r   r   r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zRODescriptorReference.__get__r   r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zRODescriptorReference.__set__r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   z RODescriptorReference.__delete__Nr   r<   r<   r<   r=   r     s
   r   _FN.c                   @  sH   e Zd ZdZerDddddddZdddd	d
dZdddddZdS )CallableReferenceza descriptor that refers to a callable.

    works around mypy's limitation of not allowing callables assigned
    as instance variables


    r   r   r   r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zCallableReference.__get__r9   r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zCallableReference.__set__r   c                 C  s   d S rL   r<   r   r<   r<   r=   r     rO   zCallableReference.__delete__Nr   r<   r<   r<   r=   r     s
   r   c                   @  s   e Zd ZdddddZdS )_TypingInstancesrX   ztuple[type, ...])keyr8   c                 C  s@   t dd tt|d tt|d fD }|s2t||| j|< |S )Nc                 S  s   h | ]}|d k	r|qS rL   r<   r   r<   r<   r=   r     s   z/_TypingInstances.__getattr__.<locals>.<setcomp>)rk   r   r   r   AttributeErrorr   )rM   r   r   r<   r<   r=   __getattr__  s    



z_TypingInstances.__getattr__N)rC   rD   rE   r   r<   r<   r<   r=   r     s   r   )FF)f
__future__r   r   collectionsr   collections.abcabcrr   rw   r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r.   r/   r1   r3   r4   r   r   r5   r   r>   rX   rW   r?   rH   rK   Z_LiteralStarr_   r|   rl   rf   r   r   r   r   rh   r   rg   r   r   r   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ZLITERAL_TYPESr<   r<   r<   r=   <module>	   s   
	 G)("	
'  (6	