U
    d                     @  s   d 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 ededZdddgZddddddZd(dddddddZddd dd!dZd"d#d$d%d&Zd'S ))zTopological sorting algorithms.    )annotations)Any)
Collection)DefaultDict)Iterable)Iterator)Sequence)Set)Tuple)TypeVar   )util)CircularDependencyError_T)boundsortsort_as_subsetsfind_cycleszCollection[Tuple[_T, _T]]zCollection[_T]zIterator[Sequence[_T]])tuplesallitemsreturnc                 #  s   t t}| D ]\}}|| | qt|}t|  rg }|D ]} || rB|| qB|sztdt| |t	| 
|  fdd|D }|V  q6d S )NzCircular dependency detected.c                   s   g | ]}| kr|qS  r   ).0tZtodo_setr   ?/tmp/pip-unpacked-wheel-wbr0uges/sqlalchemy/util/topological.py
<listcomp>7   s      z#sort_as_subsets.<locals>.<listcomp>)r   defaultdictsetaddlist
isdisjointappendr   r   
_gen_edgesdifference_update)r   r   edgesparentchildtodooutputnoder   r   r   r      s&    

TboolzIterator[_T])r   r   deterministic_orderr   c                 c  s   t | |D ]}|E dH  q
dS )a,  sort the given list of items by dependency.

    'tuples' is a list of tuples representing a partial ordering.

    deterministic_order is no longer used, the order is now always
    deterministic given the order of "allitems".    the flag is there
    for backwards compatibility with Alembic.

    N)r   )r   r   r,   set_r   r   r   r   ;   s    zIterable[Tuple[_T, _T]]zIterable[_T]zSet[_T]c                 C  s   t t}| D ]\}}|| | qt|}t }|D ]}|g}||}	|r8|d }
||
 D ]R}||kr|||d  }|	| || ||	kr`|| |		|  qLq`|
 }qLq8|S )N)r   r   r   r   
differenceindexr$   updater"   removepop)r   r   r%   r&   r'   Znodes_to_testr)   r*   stackr(   topZcycr   r   r   r   N   s*    





zDefaultDict[_T, Set[_T]]zSet[Tuple[_T, _T]])r%   r   c                   s    fdd D S )Nc                   s"   h | ]} | D ]}||fqqS r   r   )r   leftrightr%   r   r   	<setcomp>y   s     
  z_gen_edges.<locals>.<setcomp>r   r8   r   r8   r   r#   x   s    r#   N)T)__doc__
__future__r   typingr   r   r   r   r   r   r	   r
   r    r   excr   r   __all__r   r   r   r#   r   r   r   r   <module>   s&   
  *