
    sg6                        d dl mZ d dlZd dlmZ ddlmZmZmZm	Z	 ddl
mZ ddlmZmZ d dlZg dZ G d	 d
e      Zd Z ede      d        Z ede      efd       Zd Zd Z G d d      Zd Z G d de      Zd Zd Zy)    )warnN)
deprecated   )orderingambiguitiessuper_signatureAmbiguityWarning)expand_tuples)Variadic
isvariadic)MDNotImplementedErrorambiguity_warnhalt_orderingrestart_orderingvariadic_signature_matches_itervariadic_signature_matches
DispatchersourceMethodDispatcherstr_signaturewarning_textc                       e Zd ZdZy)r   z- A NotImplementedError for multiple dispatch N)__name__
__module____qualname____doc__     p/var/www/html/venv/lib/python3.12/site-packages/torch/fx/experimental/unification/multipledispatch/dispatcher.pyr   r      s    7r   r   c                 L    t        t        | j                  |      t               y)aA   Raise warning when ambiguity is detected
    Parameters
    ----------
    dispatcher : Dispatcher
        The dispatcher on which the ambiguity was detected
    ambiguities : set
        Set of type signature pairs that are ambiguous within this dispatcher
    See Also:
        Dispatcher.add
        warning_text
    N)r   r   namer	   )
dispatcherr   s     r   r   r      s     	joo{	35EFr   z?`halt_ordering` is deprecated, you can safely remove this call.categoryc                       y)z5Deprecated interface to temporarily disable ordering.Nr   r   r   r   r   r           r   z`restart_ordering` is deprecated, if you would like to eagerly order the dispatchers, you should call the `reorder()` method on each dispatcher.c                      y)z4Deprecated interface to temporarily resume ordering.Nr   )on_ambiguitys    r   r   r   (   r&   r   c              #      K   t        |      }t        |      }| D ])  }t        ||      }| t        |      rt        |      }+ 	 t        |      }d y# t        $ r t        |      sJ d Y yw xY ww)ag  Check if a set of input types matches a variadic signature.
    Notes
    -----
    The algorithm is as follows:
    Initialize the current signature to the first in the sequence
    For each type in `types`:
        If the current signature is variadic
            If the type matches the signature
                yield True
            Else
                Try to get the next signature
                If no signatures are left we can't possibly have a match
                    so yield False
        Else
            yield True if the type matches the current signature
            Get the next signature
    FTN)iternext
issubclassr   StopIteration)typesfull_signaturesigitersigtypmatchess         r   r   r   1   s     $ >"G
w-C S#&# w-C	w-C K  	c?"?J	s.   7A8A8A A8A52A84A55A8c                 4    |sJ t        t        | |            S N)allr   )r.   r/   s     r   r   r   X   s    >.unEFFr   c                       e Zd ZdZdZddZd Zed        Zed        Z	d Z
ed	        Zefd
Zd Zd ZeZd Zd Z ede      d        Zd Zd Zed        Zd Zd Zd Zd Zy)r   a   Dispatch methods based on type signature
    Use ``dispatch`` to add implementations
    Examples
    --------
    >>> # xdoctest: +SKIP("bad import name")
    >>> from multipledispatch import dispatch
    >>> @dispatch(int)
    ... def f(x):
    ...     return x + 1
    >>> @dispatch(float)
    ... def f(x):
    ...     return x - 1
    >>> f(3)
    4
    >>> f(3.0)
    2.0
    )r   r!   funcs	_ordering_cachedocNc                 J    |x| _         | _        i | _        || _        i | _        y r5   )r!   r   r8   r;   r:   )selfr!   r;   s      r   __init__zDispatcher.__init__r   s%    $((	DM
r   c                       fd}|S )a   register dispatcher with new implementation
        >>> # xdoctest: +SKIP
        >>> f = Dispatcher('f')
        >>> @f.register(int)
        ... def inc(x):
        ...     return x + 1
        >>> @f.register(float)
        ... def dec(x):
        ...     return x - 1
        >>> @f.register(list)
        ... @f.register(tuple)
        ... def reverse(x):
        ...     return x[::-1]
        >>> f(1)
        2
        >>> f(1.0)
        0.0
        >>> f([1, 2, 3])
        [3, 2, 1]
        c                 0     j                   | fi  | S r5   )add)funckwargsr=   r.   s    r   _dfz Dispatcher.register.<locals>._df   s    DHHUD+F+Kr   r   )r=   r.   rC   rD   s   ``` r   registerzDispatcher.registery   s    *	 
r   c                     t        t        d      r/t        j                  |      }|j                  j	                         S y )N	signature)hasattrinspectrG   
parametersvaluesclsrB   r1   s      r   get_func_paramszDispatcher.get_func_params   s4    7K(##D)C>>((** )r   c                     | j                  |      }|rDt        j                  fd|D        }t        d |D              }t	        fd|D              r|S yy)z; get annotations of function positional parameters
        c              3   j   K   | ]*  }|j                   j                  j                  fv r| , y wr5   )kindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORD).0param	Parameters     r   	<genexpr>z2Dispatcher.get_func_annotations.<locals>.<genexpr>   s;      9 00 6688  9s   03c              3   4   K   | ]  }|j                     y wr5   )
annotation)rT   rU   s     r   rW   z2Dispatcher.get_func_annotations.<locals>.<genexpr>   s       %    %   c              3   :   K   | ]  }|j                   u  y wr5   )empty)rT   annrV   s     r   rW   z2Dispatcher.get_func_annotations.<locals>.<genexpr>   s     E#3ioo-Es   N)rN   rI   rV   tupler6   )rM   rB   paramsannotationsrV   s       @r   get_func_annotationszDispatcher.get_func_annotations   sk     $$T*))I9 9F
    %# % %K EEE"" F r   c           	         |s| j                  |      }|r|}t        d |D              r#t        |      D ]  }| j                  ||        yg }t	        |d      D ]  \  }}t        |t        t        f      s6dj                  d |D              }t        d| d| d	| j                         t        |t              rN|t        |      k7  rt        d
      t        |      dk7  rt        d      |j                  t        |d             |j                  |        || j                  t        |      <   | j                   j#                          	 | `y# t&        $ r Y yw xY w)ay   Add new types/method pair to dispatcher
        >>> # xdoctest: +SKIP
        >>> D = Dispatcher('add')
        >>> D.add((int, int), lambda x, y: x + y)
        >>> D.add((float, float), lambda x, y: x + y)
        >>> D(1, 2)
        3
        >>> D(1, 2.0)
        Traceback (most recent call last):
        ...
        NotImplementedError: Could not find signature for add: <int, float>
        >>> # When ``add`` detects a warning it calls the ``on_ambiguity`` callback
        >>> # with a dispatcher/itself, and a set of ambiguous type signature pairs
        >>> # as inputs.  See ``ambiguity_warn`` for an example.
        c              3   <   K   | ]  }t        |t                y wr5   )
isinstancer^   )rT   r2   s     r   rW   z!Dispatcher.add.<locals>.<genexpr>   s     ;#z#u%;s   Nr   )start, c              3   j   K   | ]+  }t        |t              r|j                  n
t        |       - y wr5   )rd   typer   str)rT   cs     r   rW   z!Dispatcher.add.<locals>.<genexpr>   s3      $D45 3=Q2EAJJ),Q%0 $Ds   13zTried to dispatch on non-type: z
In signature: <z>
In function: z+Variadic signature must be the last elementzVariadic signature must contain exactly one element. To use a variadic union type place the desired types inside of a tuple, e.g., [(int, str)]r   )ra   anyr
   rA   	enumeraterd   rh   listjoin	TypeErrorr!   lenappendr   r8   r^   r:   clearr9   AttributeError)	r=   rG   rB   r`   typsnew_signatureindexr2   str_sigs	            r   rA   zDispatcher.add   s   " 33D9K'	 ;;;%i0 %t$%#IQ7 	*JE3cD$<0)) $D9B$D D"A# G229 ;004		{!< = =
 #t$C	N*#E  s8q=#@ 
 $$Xc!f%56$$S)/	*2 ,0

5'(	 		s   E 	E! E!c                 Z    	 | j                   S # t        $ r | j                         cY S w xY wr5   )r9   rs   reorderr=   s    r   r   zDispatcher.ordering   s,    	">>! 	"<<>!	"s    **c                 ~    t        | j                        x| _        }t        | j                        }|r	 || |       |S r5   )r   r8   r9   r   )r=   r(   odambs       r   ry   zDispatcher.reorder   s7    &tzz22$**%s#	r   c           	      &   t        |D cg c]  }t        |       c}      }	 | j                  |   }	  ||i |S c c}w # t        $ rP} | j                  | }|s&t        d| j                   dt        |       d      ||| j                  |<   Y d }~bd }~ww xY w# t        $ rj} | j                  | }t        |       |D ]   }	  ||i |c cY d }~S # t        $ r Y w xY w t        d| j                   dt        |       d      |d }~ww xY w)NCould not find signature for : <>zMatching functions for z(> found, but none completed successfully)r^   rh   r:   KeyErrordispatchNotImplementedErrorr!   r   r   dispatch_iterr+   )r=   argsrC   argr.   rB   er8   s           r   __call__zDispatcher.__call__   sC   D1StCy12	&;;u%D	i((( 2  	& 4==%(D)3DII;c-PUBVAWWXY[`ab!%DKK	& % 	i&D&&.EK 000,  &)99+Su!5 66^`bghi	is]   <A B 	B
ABB	D&DCDD	C!D C!!*DDc                 "    d| j                    dS )Nz<dispatched r   )r!   rz   s    r   __str__zDispatcher.__str__  s    dii[**r   c                     || j                   v r| j                   |   S 	 t         | j                  |       S # t        $ r Y yw xY w)ai  Determine appropriate implementation for this type signature
        This method is internal.  Users should call this object as a function.
        Implementation resolution occurs within the ``__call__`` method.
        >>> # xdoctest: +SKIP
        >>> from multipledispatch import dispatch
        >>> @dispatch(int)
        ... def inc(x):
        ...     return x + 1
        >>> implementation = inc.dispatch(int)
        >>> implementation(3)
        4
        >>> print(inc.dispatch(float))
        None
        See Also:
          ``multipledispatch.conflict`` - module to determine resolution order
        N)r8   r+   r   r-   r=   r.   s     r   r   zDispatcher.dispatch  sO    $ DJJ::e$$	***E233 		s   7 	AAc              '   2  K   t        |      }| j                  D ]y  }t        |      |k(  r.t        t        t        ||            r| j
                  |   }| ?t        |      sKt        |d         sZt        ||      sg| j
                  |   }| { y w)N)rp   r   r6   mapr,   r8   r   r   )r=   r.   nrG   results        r   r   zDispatcher.dispatch_iter2  s     J 	!I9~"s3z5)+L'MI.YJy}$=-eY?!ZZ	2F L	!s   A"B%B4BBz1`resolve()` is deprecated, use `dispatch(*types)`r#   c                       | j                   | S )z Determine appropriate implementation for this type signature
        .. deprecated:: 0.4.4
            Use ``dispatch(*types)`` instead
        )r   r   s     r   resolvezDispatcher.resolve>  s     t}}e$$r   c                 4    | j                   | j                  dS )Nr!   r8   r   rz   s    r   __getstate__zDispatcher.__getstate__F  s    		% 	%r   c                 n    |d   | _         |d   | _        t        | j                        | _        i | _        y )Nr!   r8   )r!   r8   r   r9   r:   )r=   ds     r   __setstate__zDispatcher.__setstate__J  s/    fI	wZ
!$**-r   c                    d| j                    g}| j                  r|j                  | j                         g }| j                  d d d   D ]  }| j                  |   }|j
                  rRdt        |       d}|dt        |      z  dz   z  }||j
                  j                         z  }|j                  |       p|j                  t        |              |r#|j                  ddj                  |      z          d	j                  |      S )
NzMultiply dispatched method: r   z	Inputs: <z>
-
zOther signatures:
    z
    

)
r!   r;   rq   r   r8   r   r   rp   striprn   )r=   docsotherr1   rB   ss         r   r   zDispatcher.__doc__P  s    .tyyk:;88KK!==2& 	1C::c?D||c 2337S3q6\D((T\\''))A]3/0	1 KK1HMM%4HHI{{4  r   c                 P     | j                   t        t        |       j                  S r5   )r   r   rh   r   )r=   r   s     r   _helpzDispatcher._helpg  s    t}}c$o.666r   c                 4    t         | j                  |        y)z: Print docstring for the function corresponding to inputs N)printr   r=   r   rC   s      r   helpzDispatcher.helpj  s    jdjj$ r   c                 l     | j                   t        t        |       }|st        d      t	        |      S )NzNo function found)r   r   rh   ro   r   )r=   r   rB   s      r   _sourcezDispatcher._sourcen  s1    t}}c$o./00d|r   c                 4    t         | j                  |        y)z< Print source code for the function corresponding to inputs N)r   r   r   s      r   r   zDispatcher.sourcet  s    ldllD!"r   r5   )r   r   r   r   	__slots__r>   rE   classmethodrN   ra   rA   propertyr   r   ry   r   r   __repr__r   r   r   FutureWarningr   r   r   r   r   r   r   r   r   r   r   r   ^   s    " JI4 + +
 # #&=~ " " $2 i4+H4
! Cm\% ]%% ! !,7!#r   r   c                 h    dt        j                  |        d}|t        j                  |       z   }|S )NzFile: r   )rI   getsourcefile	getsource)rB   r   s     r   r   r   y  s6    
&&t,-T2A	Gd##AHr   c                   0    e Zd ZdZdZed        Zd Zd Zy)r   zO Dispatch methods based on type signature
    See Also:
        Dispatcher
    objrM   c                     t        t        d      rDt        j                  |      }t        j                  |j
                  j                         dd       S y )NrG   r   )rH   rI   rG   itlislicerJ   rK   rL   s      r   rN   z MethodDispatcher.get_func_params  sA    7K(##D)C::cnn335q$?? )r   c                 "    || _         || _        | S r5   r   )r=   instanceowners      r   __get__zMethodDispatcher.__get__  s    r   c                     t        |D cg c]  }t        |       c}      } | j                  | }|s%t        d| j                   dt        |       d       || j                  g|i |S c c}w )Nr   r   r   )r^   rh   r   r   r!   r   r   )r=   r   rC   r   r.   rB   s         r   r   zMethodDispatcher.__call__  su    D1StCy12t}}e$%(Edii[PSTabgThSiij&kllDHH.t.v..	 2s   A/N)	r   r   r   r   r   r   rN   r   r   r   r   r   r   r     s,     I@ @

/r   r   c                 2    dj                  d | D              S )zb String representation of type signature
    >>> str_signature((int, float))
    'int, float'
    rf   c              3   4   K   | ]  }|j                     y wr5   )r   )rT   rM   s     r   rW   z str_signature.<locals>.<genexpr>  s     1cS\\1rZ   )rn   )r1   s    r   r   r     s    
 991S111r   c                     d|  d}|dz  }|D ]#  }|ddj                  d |D              z   dz   z  }% |dz  }|dj                  |D cg c]   }d	t        t        |            z   d
|  dz   " c}      z  }|S c c}w )z! The text for ambiguity warnings z*
Ambiguities exist in dispatched function r   z;The following signatures may result in ambiguous behavior:
	rf   c              3   >   K   | ]  }d t        |      z   dz     yw)[]N)r   )rT   r   s     r   rW   zwarning_text.<locals>.<genexpr>  s     E1#a 0036Es   r   z,

Consider making the following additions:

z
@dispatch(z)
def z(...))rn   r   r   )r!   r}   textpairr   s        r   r   r     s    8dCDJJD M		EEEFHLM 	MM 	>>DFKK:=?56 &oa6H(II$TF%01 ? @ @DK?s   	%A9
)warningsr   rI   typing_extensionsr   conflictr   r   r   r	   utilsr
   variadicr   r   	itertoolsr   __all__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s      ( N N   * v8/ 8G E@	@ A
 #1 ?
?$NGX# X#v/z /42
r   