
    -Ph                         d dl Z ddlmZmZmZmZmZmZmZ ddlm	Z	m
Z
mZmZ ddlmZmZmZ ddlmZ ddlmZmZ  G d	 d
e          ZdS )    N   )	ExprNodes
PyrexTypes
MemoryViewParseTreeTransformsStringEncodingErrorsNaming)	CloneNodeCodeObjectNode	ProxyNode	TupleNode)FuncDefNodeStatListNodeDefNode   )
OrderedSet)errorCannotSpecializec                        e Zd ZdZdZdZdZdZdZdZ	e
j        g dz   Z fdZd Zd Zd Zd Zd	 Zd
 Zd Zd Zd Zd Zd Zd ZdZdZd Zd Zd Zd Zd Zd Z d Z!d Z"d Z#d Z$d Z%d Z& fdZ'd  Z( xZ)S )!FusedCFuncDefNodea{  
    This node replaces a function with fused arguments. It deep-copies the
    function for every permutation of fused types, and allocates a new local
    scope for it. It keeps track of the original function in self.node, and
    the entry of the original function in the symbol table is given the
    'fused_cfunction' attribute which points back to us.
    Then when a function lookup occurs (to e.g. call it), the call can be
    dispatched to the right function.

    node    FuncDefNode    the original function
    nodes   [FuncDefNode]  list of copies of node with different specific types
    py_func DefNode        the fused python function subscriptable from
                           Python space
    __signatures__         A DictNode mapping signature specialization strings
                           to PyCFunction nodes
    resulting_fused_function  PyCFunction for the fused DefNode that delegates
                              to specializations
    fused_func_assignment   Assignment of the fused function to the function name
    defaults_tuple          TupleNode of defaults (letting PyCFunctionNode build
                            defaults would result in many different tuples)
    specialized_pycfuncs    List of synthesized pycfunction nodes for the
                            specializations

    fused_compound_types    All fused (compound) types (e.g. floating[:])
    N)__signatures__resulting_fused_functionfused_func_assignmentc                 
   t                                          |j                   g | _        || _        t          | j        t                    }|r|                     |           n|                     |           | j        D ]^}|j	        j
        j        rJ |j        j        j        rJ |j        j        r|j        j        rJ |s|j        j        r|j
        j        sJ _| |j	        _        | j        d d          | _        d S N)super__init__posnodesnode
isinstancer   copy_def	copy_cdefentrytypeis_fusedlocal_scopereturn_typecfunc_declaratoroptional_arg_countop_arg_structfused_cfunctionstats)selfr!   envis_defn	__class__s        Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/Cython/Compiler/FusedNode.pyr   zFusedCFuncDefNode.__init__1   s   """
	DIw// 	 MM#NN3  	, 	,Aw|,,,,}09999( 2=1111 ,a0C ,v++++%)
" Z]


    c                    t          j        d | j        j        D                       }|                     |          }t          j        |          }|| _        | j        j        |j        v r$|j        	                    | j        j                   |D ]\  }}t          j        | j                  }| j        j        j        |j        _        |                     |j        |           | j        j                            |          |_        t!          |          |_        |                    |           |                     |||           |                     ||| j        j        ||           t          j        |j        |           d|j        _        |j        |j        |j        j        <   d t3          | j        j        |j                  D             }t5          j        |j         dd                    |           d          |_        |                     |          s n| j        | _        |                     | j        |d          | _         dS )	zh
        Create a copy of the original def or lambda function for specialized
        versions.
        c                 4    g | ]}|j         j        |j         S  r&   r'   .0args     r4   
<listcomp>z.FusedCFuncDefNode.copy_def.<locals>.<listcomp>T   s$    EEE#383DESXEEEr5   Tc                 d    g | ]-\  }}|j         j        |j                             d d          .S ) T)for_display)r&   r'   declaration_code)r;   fargsargs      r4   r=   z.FusedCFuncDefNode.copy_def.<locals>.<listcomp>q   sL     & & & T49%&	**24*@@& & &r5   [,]r1   N)!r   uniquer!   args_get_fused_base_types get_all_specialized_permutationsfused_compound_typesr%   pyfunc_entriesremovecopydeepcopy	signature_specialize_function_argsr)   
specializer   code_objectanalyse_declarationscreate_new_local_scopespecialize_copied_defspecialize_entryusedentriesnamezipr   EncodedStringjoinreplace_fused_typechecksorig_py_funcmake_fused_cpdefpy_func)	r/   r0   rL   fused_typespermutationscnamefused_to_specificcopied_nodespecialised_type_namess	            r4   r#   zFusedCFuncDefNode.copy_defN   sT   
  *0EEEEE G  G001EFF!B;OO$8!9?c000%%dio666(4 	 	$E$-	22K*.)/*CK'**;+;=NOOO&*i&;&F&F4E'G 'GK#&4[&A&AK#,,S111 ''S:KLLL&&{E49?'8:NP P P '(95AAA%)K"2=2CCK)./& &$'	8H$I$I& & &"
  .;{?O<u<uRURZRZ[qRrRr<u<u<uvvK00==  !I,,TYD,IIr5   c                    | j         j                                        }| j         j        x| _        }d| j         _        |r|j                            |j                   | j         j                                        }|| _	        g }|D ]9\  }}t          j        | j                   }	 |j                            |          }	n.# t          $ r! t          |j        d           d| _        Y  dS w xY w|j        }
|	                    |
|           |j        D ][}|
j        |j        k    rI|	                    |j                  r/||_        |j        j        s|
j        |j        _        |}
|j        }	 n\|                    |
           |	|_        |	|
c|
_        |	_        |
j        p| j         j        j        p|j        p|
j        |
_        | j         j        j        r"| j         j                            |	||           |	j        |_        |                     |||           |                     |j        j         |           |!                    |           |j        rQ|j                            |j        j                   | "                    |j        || j         j        j#        ||           | $                    |          s n;| j         j        |j        v r4|j        %                    | j         j                  }||j        ||dz   <   n|j        &                    |           |r| '                    ||d          | _        dS || _        dS )zf
        Create a copy of the original c(p)def function for all specialized
        versions.
        NzQReturn type is a fused type that cannot be determined from the function arguments)fused_cnamer   FrG   )(r!   r&   rK   rb   r`   rM   rN   r%   get_fused_typesrL   rO   rP   rS   r   r   r   rX   cfunc_entriesre   same_as_resolved_type
func_cnameappendrY   defined_in_pxdis_c_class_scope
is_cmethodr*   r+   declare_optional_arg_structr)   rV   rR   rI   declare_cpdef_wrapperrW   as_variabler_   indexextendra   )r/   r0   rd   r`   rc   new_cfunc_entriesre   rf   rg   r&   r%   
orig_entrycindexs                r4   r$   zFusedCFuncDefNode.copy_cdef~   s   
 y~FFHH ,09+<<L 	 	:%%l&8999in4466$/!(4 9	 9	$E$-	22K"'223DEE#   ko (B C C C#  %E!!%/// "/ 	0 	0
;*"222t7Q7QR\Ra7b7b2(2K%&,7 H7<7G)4&E%?DE!((///#K%)5"EJ
* +)/8+.+  * J
 y)< I	*FF+/% G I I I '+&6K#''S:KLLL **;+G+L+<> > >
 --c222" 8"))+*=*CDDD**#+UDIO4O);8 8 8 00==  9?c///&,,TY_==F1BCfVAXo..$$%6777 	(00s8= 1 ? ?DLLL (DLLLs   (C&C.-C.c                 ^    g }t                      }|D ]}|                    ||           |S )zq
        Get a list of unique basic fused types, from a list of
        (possibly) compound fused types.
        )resultseen)setrk   )r/   rL   
base_typesr}   
fused_types        r4   rJ   z'FusedCFuncDefNode._get_fused_base_types   sE    
 
uu. 	E 	EJ&&jt&DDDDr5   c                     |D ]k}|j         j        r]|j                             |          |_         |j         j        r|j                             |j                   |j        rd|j        _        ld S )NT)r&   r'   rS   is_memoryviewslicevalidate_memslice_dtyper   
annotationuntyped)r/   rI   rf   r<   s       r4   rR   z+FusedCFuncDefNode._specialize_function_args   s|     	2 	2Cx  28../@AA8. >H44SW===> 2 .2CN*	2 	2r5   c                     |                     |           ||j        _        d|_        | j                            |           dS )a  
        Create a new local scope for the copied node and append it to
        self.nodes. A new local scope is needed because the arguments with the
        fused types are already in the local scope, and we need the specialized
        entries created after analyse_declarations on each specialized version
        of the (CFunc)DefNode.
        f2s is a dict mapping each fused type to its specialized version
        FN)create_local_scoper(   rf   has_fused_argumentsr    ro   )r/   r!   r0   f2ss       r4   rV   z(FusedCFuncDefNode.create_new_local_scope   sI     	$$$-0* $) 
$r5   c                    |                      |          }fd|D             }d                    |          |_        t          j        ||j        j                  |j        _        |j        |j        _        |j        |j        _        dS )zwSpecialize the copy of a DefNode given the copied node,
        the specialization cname and the original DefNode entryc                 :    g | ]}t          j        |          S r8   )r   specialization_signature_string)r;   r   r   s     r4   r=   z;FusedCFuncDefNode.specialize_copied_def.<locals>.<listcomp>  s6     
 
 
 6z3GG
 
 
r5   |N)	rJ   r^   specialized_signature_stringr   get_fused_cnamer%   pymethdef_cnamedoc	doc_cname)r/   r!   re   py_entryr   rL   rc   type_stringss       `   r4   rW   z'FusedCFuncDefNode.specialize_copied_def  s     001EFF
 
 
 
"-
 
 

 -0HH\,B,B)%/%?(-tz/I&K &K
"!
'1
r5   c                     t          j                    }t          j        |j                  } ||           t          j                    |k    rdS dS )z
        Branch-prune fused type checks like

            if fused_t is int:
                ...

        Returns whether an error was issued and whether we should stop in
        in order to prevent a flood of errors.
        FT)r	   get_errors_countr   ReplaceFusedTypeChecksr(   )r/   rg   
num_errors	transforms       r4   r_   z*FusedCFuncDefNode.replace_fused_typechecks  sZ     ,..
'>'2'>@ @		+"$$z115tr5   c                     |D ]L}|                                 }|j                            ||j                   |                    d           MdS )zl
        Generate Cython code for instance checks, matching an object to
        specialized types.
        )py_type_namespecialized_type_namez
                    if isinstance(arg, {{py_type_name}}):
                        dest_sig[{{dest_sig_idx}}] = '{{specialized_type_name}}'; break
                N)r   contextupdatespecialization_string	put_chunk)r/   normal_typespyx_coder0   specialized_typer   s         r4   _fused_instance_checksz(FusedCFuncDefNode._fused_instance_checks%  s|    
 !- 	 	+88::L##)&6&L $       	 	r5   c                     t          |                              dd                              dd          }|j        rt          j        |z   }|S )N___ )strreplace
is_typedefr
   fused_dtype_prefix)r/   dtyper[   s      r4   _dtype_namezFusedCFuncDefNode._dtype_name7  sJ    5zz!!#t,,44S#>> 	4,t3Dr5   c                 X    |j         r|                     |          S t          |          S r   )r   r   r   r/   r   s     r4   _dtype_typezFusedCFuncDefNode._dtype_type=  s-     	+##E***5zzr5   c                 D    |j         rdS d|                     |          z  S )Nzsizeof(void *)z
sizeof(%s))is_pyobjectr   r   s     r4   _sizeof_dtypezFusedCFuncDefNode._sizeof_dtypeB  s,     	:##$"2"25"9"999r5   c                    |                     d          5  |                    d           |                    d           ddd           n# 1 swxY w Y   |                     d          5  |                    d           |                    d           ddd           n# 1 swxY w Y   |                     d          5  |                    d           |                    d           ddd           dS # 1 swxY w Y   dS )	z?Setup some common cases to match dtypes against specializationszif kind in u'iu':pass	dtype_intNzelif kind == u'f':dtype_floatzelif kind == u'c':dtype_complex)indenterputlnnamed_insertion_pointr/   r   s     r4   %_buffer_check_numpy_dtype_setup_casesz7FusedCFuncDefNode._buffer_check_numpy_dtype_setup_casesH  s   233 	8 	8NN6"""**;777	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 344 	: 	:NN6"""**=999	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 344 	< 	<NN6"""**?;;;	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	<s5   +AAA-+B$$B(+B(+C<<D D z8dest_sig[{{dest_sig_idx}}] = '{{specialized_type_name}}'z!dest_sig[{{dest_sig_idx}}] = Nonec                    |                      |           ||z   D ]"}|}|j        r|j        }|j        }|j                            |                     |          dz   d|                     |          z  ||j                   |j	        |d         f|j
        |d         f|j        |d         fg}|D ]\  }}	|sd|j        fz  }
|j	        r|
dz  }
|j        r|
d	z  }
|	                    d
|
z            5  |	                    | j                   |	                    d           ddd           n# 1 swxY w Y   $dS )zO
        Match a numpy dtype object to the individual specializations.
        z == itemsizez!not (%s_is_signed ^ dtype_signed))itemsize_matchsigned_matchr   r   r   r   r   z3{{itemsize_match}} and (<Py_ssize_t>arg.ndim) == %dz and {{signed_match}}z and arg_is_pythran_compatiblezif %s:breakN)r   is_pythran_expr
org_bufferr   r   r   r   r   r   is_intis_float
is_complexndimr   r   match)r/   r   specialized_buffer_typespythran_typesr   
final_typer   dtypesdtype_category
codewriterconds              r4   _buffer_check_numpy_dtypez+FusedCFuncDefNode._buffer_check_numpy_dtypeX  s    	228<<< -.F F 	. 	.)J/ ?#3#> $*E###11%88>I@4CSCSTYCZCZZ&0&F	 $ H H H x45-!89!8O#<=F /5 . .*
% L0@0EPH H< 433D- =<<D((D99 . .$$TZ000$$W---. . . . . . . . . . . . . . ..#	. 	.s   50D11D58D5c                    |j         }|j        rdg|j        z  }n|j        }t	          j        ||          }|                    |           |j                            |j	        |           |
                    d           |j                            |j        |                     |          |j                   |                    d| j        z             dS )z
        For each specialized type, try to coerce the object to a memoryview
        slice of that type. This means obtaining a buffer and parsing the
        format string.
        TODO: separate buffer acquisition from format parsing
        )directstrided)coerce_from_py_funcr   z;{{memviewslice_cname}} {{coerce_from_py_func}}(object, int))r   sizeof_dtype
ndim_dtypea  
                # try {{dtype}}
                if (((itemsize == -1 and arg_as_memoryview.itemsize == {{sizeof_dtype}})
                        or itemsize == {{sizeof_dtype}})
                        and arg_as_memoryview.ndim == {{ndim_dtype}}):
                    memslice = {{coerce_from_py_func}}(arg_as_memoryview, 0)
                    if memslice.memview:
                        __PYX_XCLEAR_MEMVIEW(&memslice, 1)
                        # print 'found a match for the buffer through format parsing'
                        %s
                        break
                    else:
                        __pyx_PyErr_Clear()
            N)r   	is_bufferr   axesr   MemoryViewSliceTypecreate_from_py_utility_coder   r   from_py_functionr   r   r   r   r   )r/   r   	decl_coder   r0   r   r   memslice_types           r4   !_buffer_parse_format_string_checkz3FusedCFuncDefNode._buffer_parse_format_string_check  s    !&% 	))*-=-BBDD#(D"6udCC11#666 - > 	  	 	 	 	I	K 	K 	K 	"2"H++E22', 	  	. 	. 	. 	 *	 	 	 	 	r5   c                 T   |                     d|rdndz   dz   |rdndz   dz              |                    d           |r|                     d           |                     |||           |                    d           |rC|j                            |d	         j        
           |                     d| j        z             |                     d           |                    d          5  |D ]}| 	                    ||||           	 ddd           dS # 1 swxY w Y   dS )a^  
        Generate Cython code to match objects to buffer specializations.
        First try to get a numpy dtype object and match it against the individual
        specializations. If that fails, try naively to coerce the object
        to each specialization, which obtains the buffer each time and tries
        to match the format string.
        z
                z!arg_is_pythran_compatible = Falser?   z
                if ndarray is not None:
                    if isinstance(arg, ndarray):
                        dtype = arg.dtype
                        z arg_is_pythran_compatible = TrueaD  
                    elif __pyx_memoryview_check(arg):
                        arg_base = arg.base
                        if isinstance(arg_base, ndarray):
                            dtype = arg_base.dtype
                        else:
                            dtype = None
                    else:
                        dtype = None

                    itemsize = -1
                    if dtype is not None:
                        itemsize = dtype.itemsize
                        kind = ord(dtype.kind)
                        dtype_signed = kind == u'i'
            r   aS  
                        # Pythran only supports the endianness of the current compiler
                        byteorder = dtype.byteorder
                        if byteorder == "<" and not __Pyx_Is_Little_Endian():
                            arg_is_pythran_compatible = False
                        elif byteorder == ">" and __Pyx_Is_Little_Endian():
                            arg_is_pythran_compatible = False
                        if arg_is_pythran_compatible:
                            cur_stride = itemsize
                            shape = arg.shape
                            strides = arg.strides
                            for i in range(arg.ndim-1, -1, -1):
                                if (<Py_ssize_t>strides[i]) != cur_stride:
                                    arg_is_pythran_compatible = False
                                    break
                                cur_stride *= <Py_ssize_t> shape[i]
                            else:
                                arg_is_pythran_compatible = not (arg.flags.f_contiguous and (<Py_ssize_t>arg.ndim) > 1)
                r   r   zb
                if arg is None:
                    %s
                    break
                z
            try:
                arg_as_memoryview = memoryview(arg)
            except (ValueError, TypeError):
                pass
            zelse:N)
r   indentr   dedentr   r   r   r   r   r   )r/   buffer_typesr   r   r   accept_noner0   r   s           r4   _buffer_checksz FusedCFuncDefNode._buffer_checks  s    	>KS::QSUX
 FSZAAXZ\
_	 	 	, 	 	  ( 	&&x}MMM 	"
 ##&21o&K $     j	!" " " 		 	 	 w'' 	D 	D$0 D D 66 )-=sD D D DD	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	Ds   1DD!$D!c           
      b   |                     d           |d                              d           |r|d                              d           |d                              d           |d                              d           t                      }t                      }|D ]}|j        }|                     |          }	|j        r\|	|vrX|                    |	           |                    d|                                d	|	d
|                                d           |j        j	        r}t          |          |vrl|                    t          |                     |j                            |	|                     |                     |d                              d           dS )zr
        If we have any buffer specializations, write out some variable
        declarations and imports.
        z
                ctypedef struct {{memviewslice_cname}}:
                    void *memview

                void __PYX_XCLEAR_MEMVIEW({{memviewslice_cname}} *, int have_gil)
                bint __pyx_memoryview_check(object)
            local_variable_declarationsz
                cdef {{memviewslice_cname}} memslice
                cdef Py_ssize_t itemsize
                cdef bint dtype_signed
                cdef Py_UCS4 kind

                itemsize = -1
            zl
                cdef bint arg_is_pythran_compatible
                cdef Py_ssize_t cur_stride
            importszq
                cdef type ndarray
                ndarray = __Pyx_ImportNumPyArrayTypeIfAvailable()
            z?
                cdef memoryview arg_as_memoryview
            z	ctypedef r   z "")
dtype_name
dtype_typez
                            cdef bint {{dtype_name}}_is_signed
                            {{dtype_name}}_is_signed = not (<{{dtype_type}}> -1 > 0)
                        N)r   r~   r   r   r   addr   resolveempty_declaration_coder   r   r   r   r   )
r/   r   r   all_buffer_typesr   seen_typedefsseen_int_dtypesbuffer_typer   r   s
             r4   _buffer_declarationsz&FusedCFuncDefNode._buffer_declarations  s   
 		 	 	 	./99	 	 	  	23== ?   
 	%%	 	 	 	%%	
 	
 	
 %%+ 	 	K%E))%00J R]22!%%j111OOO16***161M1M1O1O1O1OQR R R  ' 	u::_44#''E

333$++z7;7G7G7N7N , P P P:;EE  	 	r5   c                    t          j        |j                  }|                                 t	                      }g g g }}}d}|D ]}|                                }	|	r9|	|v r|                    |	           |	dk    rd};|                    |           Q|j        r|                    |           n|j	        s|j
        r|                    |           ||||fS )zV
        Specialize fused types and split into normal types and buffer types.
        FobjectT)r   get_specialized_typesr&   sortr~   r   r   ro   r   r   r   )
r/   r<   specialized_typesseen_py_type_namesr   r   r   has_object_fallbackr   r   s
             r4   _split_fused_typesz$FusedCFuncDefNode._split_fused_typesC  s    '<SXFF 	    UU46BMl# 1 	6 	6+88::L 6#555"&&|4448++*.'' ''(89999!1 6$$%56666!+ 6/?/R 6##$4555\=:MMMr5   c                 0    |                     d           d S )Na  
                # PROCESSING ARGUMENT {{arg_tuple_idx}}
                if {{arg_tuple_idx}} < len(<tuple>args):
                    arg = (<tuple>args)[{{arg_tuple_idx}}]
                elif kwargs is not None and '{{arg.name}}' in <dict>kwargs:
                    arg = (<dict>kwargs)['{{arg.name}}']
                else:
                {{if arg.default}}
                    arg = (<tuple>defaults)[{{default_idx}}]
                {{else}}
                    {{if arg_tuple_idx < min_positional_args}}
                        raise TypeError("Expected at least %d argument%s, got %d" % (
                            {{min_positional_args}}, {{'"s"' if min_positional_args != 1 else '""'}}, len(<tuple>args)))
                    {{else}}
                        raise TypeError("Missing keyword-only argument: '%s'" % "{{arg.default}}")
                    {{endif}}
                {{endif}}
            r   r   s     r4   _unpack_argumentz"FusedCFuncDefNode._unpack_argument`  s)    	 	 	 	 	r5   c                 0    |                     d           dS )z
        Generate Cython code for constructing a persistent nested dictionary index of
        fused type specialization signatures.
        a  
                fused_sigindex = <dict> _fused_sigindex_ref[0]
                if fused_sigindex is None:
                    fused_sigindex = {}
                    for sig in <dict> signatures:
                        sigindex_node = fused_sigindex
                        *sig_series, last_type = sig.strip('()').split('|')
                        for sig_type in sig_series:
                            if sig_type not in sigindex_node:
                                sigindex_node[sig_type] = sigindex_node = {}
                            else:
                                sigindex_node = <dict> sigindex_node[sig_type]
                        sigindex_node[last_type] = sig
                    _fused_sigindex_ref[0] = fused_sigindex
            Nr   r   s     r4   _fused_signature_indexz(FusedCFuncDefNode._fused_signature_indexu  s+    " 		
 	
 	
 	
 	
r5   c           
      
   ddl m}m}m} |                     d | j        j        D                       }t          j        | j        j        t          |          |r| j        j
        | j        j        z
  n"t          d | j        j        D                       |j        j        d}|                    |          }	|                    |          }
|
                    d           |
                                 |	                    d           |	                                 |	                    d	           |	                    d
           d}d}t'                      }t)                      }t+          | j        j                  D ]\  }}|j        j        rC|j                                        }t          |          dk    rt3          d          |d         }|j        j        r||vr|                    |           |                    ||||           |                     |          \  }}}}|                     |	           |	                    d          5  |r|                     ||	|           |s|rM|                     |j        !                    dd                     | "                    |||	|
|j#        |           |r6|	j$                            d           |	%                    | j&                   n|	%                    | j'                   |	%                    d           ddd           n# 1 swxY w Y   |dz  }|                    |           |                    d |D                        |j(        r|dz  }	|rt| )                    |	|
||           |                     |j        !                    dd                     |                     |j        !                    dd                     | *                    |	           |	                    d           |	+                                }ddl,m-} |                    |d |            g          } |.                    | j        j/                  |j0                  }|1                    |
+                                |2                                           ||_3        |4                    |           |j5        d         }|j3        | _6        to          | j        tp                    r| j9        dd         |_:        nd | j9        D             |_:        |S )a!  
        This creates the function that is indexable from Python and does
        runtime dispatch based on the argument types. The function gets the
        arg tuple and kwargs dict (or None) and the defaults tuple
        as arguments from the Binding Fused Function's tp_call.
        r   )TreeFragmentCodeUtilityCodec                 4    g | ]}|j         j        |j         S r8   r9   r:   s     r4   r=   z6FusedCFuncDefNode.make_fused_cpdef.<locals>.<listcomp>  s;     2E 2E 2E#(2C2EH2E 2E 2Er5   c              3   (   K   | ]}|j         	dV  d S )Nr   )defaultr:   s     r4   	<genexpr>z5FusedCFuncDefNode.make_fused_cpdef.<locals>.<genexpr>  s)      GG#3;3FA3F3F3F3FGGr5   )memviewslice_cname	func_argsn_fusedmin_positional_argsr[   )r   z
                cdef extern from *:
                    void __pyx_PyErr_Clear "PyErr_Clear" ()
                    type __Pyx_ImportNumPyArrayTypeIfAvailable()
                    int __Pyx_Is_Little_Endian()
            aX  
                def __pyx_fused_cpdef(signatures, args, kwargs, defaults, _fused_sigindex_ref=[None]):
                    # FIXME: use a typed signature - currently fails badly because
                    #        default arguments inherit the types we specify here!

                    cdef list search_list
                    cdef dict sigindex_node

                    dest_sig = [None] * {{n_fused}}

                    if kwargs is not None and not kwargs:
                        kwargs = None

                    cdef Py_ssize_t i

                    # instance check body
            r   r   r   zODetermination of more than one fused base type per argument is not implemented.)arg_tuple_idxr<   dest_sig_idxdefault_idxzwhile 1:IsLittleEndianzModuleSetupCode.cr   r   r   Nc              3   $   K   | ]}|j         V  d S r   )r   )r;   tys     r4   r	  z5FusedCFuncDefNode.make_fused_cpdef.<locals>.<genexpr>  s$      'N'N"'N'N'N'N'N'Nr5   ImportzImportExport.cImportNumPyArraya  
                sigindex_matches = []
                sigindex_candidates = [fused_sigindex]

                for dst_type in dest_sig:
                    found_matches = []
                    found_candidates = []
                    # Make two separate lists: One for signature sub-trees
                    #        with at least one definite match, and another for
                    #        signature sub-trees with only ambiguous matches
                    #        (where `dest_sig[i] is None`).
                    if dst_type is None:
                        for sn in sigindex_matches:
                            found_matches.extend((<dict> sn).values())
                        for sn in sigindex_candidates:
                            found_candidates.extend((<dict> sn).values())
                    else:
                        for search_list in (sigindex_matches, sigindex_candidates):
                            for sn in search_list:
                                type_match = (<dict> sn).get(dst_type)
                                if type_match is not None:
                                    found_matches.append(type_match)
                    sigindex_matches = found_matches
                    sigindex_candidates = found_candidates
                    if not (found_matches or found_candidates):
                        break

                candidates = sigindex_matches

                if not candidates:
                    raise TypeError("No matching signature found")
                elif len(candidates) > 1:
                    raise TypeError("Function call with ambiguous argument types")
                else:
                    return (<dict>signatures)[candidates[0]]
            )ConstantFoldingmodule)levelpipelinec                     g | ]	}|j         
S r8   )rb   )r;   r2   s     r4   r=   z6FusedCFuncDefNode.make_fused_cpdef.<locals>.<listcomp>@  s    )H)H)H!))H)H)Hr5   );r?   r  r  r  rJ   r!   rI   r   r
  lennum_required_argsnum_required_kw_argssumr%   r[   PyxCodeWriterr   r   r   r   r~   	enumerater&   r'   rk   NotImplementedErrorr   r   r   r   r   r   use_utility_codeload_cachedr   r   r   r   r   no_matchr  r   r  getvalueOptimizer  SetPosTransformr   rootdeclare_declarations_in_scopeglobal_scopescoperU   r.   fragment_scoper"   r   r    specialized_cpdefs)r/   r`   r0   r1   r  r  r  rc   r   r   r   fused_indexr  r   seen_fused_typesir<   arg_fused_typesr   r   r   r   r   fragment_coder  fragmentastrb   s                               r4   ra   z"FusedCFuncDefNode.make_fused_cpdef  s    	655555555500 2E 2E $	2E 2E 2E F F #-"?;'' H	+di.LLLGGGGGGG &+	
 	
 %%g%66&&w&77		 	 	 		 	 	& 	&&y111&&'DEEE%<<55	// *	! *	!FAsx  0"%(":":"<"<''!++- /V W W W,Q/
x  OZ7G%G%G $$Z000"#!, +	     RVQhQhilQmQmNlM;N%%h/// &&z22 , ,# Q33L(CPPP# 2} 2,,T-=-I-IJZ\o-p-pqqq++(-9OS2 2 2 + 6 (//h/OOO tz2222 t}555NN7+++, , , , , , , , , , , , , , , q  ''555 '''N'N'N'N'NNNN{ !q  	e%%h	;K][[[  !1!=!=hHX!Y!YZZZ  !1!=!=>PRb!c!cddd##H---#$	 $	 $	L !))++ 	.-----,,__5F5F4G - I I9l**49=99(-HH11  #"2"2"4"4	6 	6 	6	  %%%)B-!idi)) 	I)-AAAG&&)H)HTZ)H)H)HG&s   CL;;L?	L?	c           	         d}| j         j        }|D ]+}t          ||t          | j        j        |                     ,| j        j        | j         _        | j        j        | j         _        |j                            dd            t          | j
        t                    r||j        |j        <   n||j        |j                 _        |j                            |           | | j         j        _        g }| j        D ]u}t          | j
        t                    r"|                    |           | j         |_        >|                    |j                    | j         |j         _        ||j        _        v|                     |           d S )N)
r[   r   re   rn   pyfunc_cnamer   r   r   	is_memberr,  __pyx_fused_cpdef)rb   r%   setattrgetattrr`   r[   r   rZ   popr"   r!   r   ru   rM   ro   r-   r    fused_py_funcsynthesize_defnodes)r/   r0   copy_attributesr%   attr	def_nodesr!   s          r4   update_fused_defnode_entryz,FusedCFuncDefNode.update_fused_defnode_entryD  sy   
 "# 	< 	<DE4D-3T::< < < < !-2,0+T222di)) 	8&+CK
##27CK
#/!!%(((-1*	J 	/ 	/D$)W-- /  &&&%)\""  ...-1\*).
&&  +++++r5   c                    | j         D ]?}|                                D ](}|j        D ]}|j        r|                    |           )@| j        r|| j                            |          | _        | j                            |          | _        | j                            |          | _        | j	                            |          | _	        g x| _
        }| j        j        D ]}|j        r|j                            |          |_        |j        j        r-|                    t!          j        |j                             a|                    t#          |j                            |                               |                    d           t'          | j                  D ]\  }}|                    |          x}| j        |<   t+          |t,                    r|| j        urt/          |j        |          D ]o\  }}	|	h|	j        r!|	                    |j        |          |_        /t5          |	                              |                              |j        |          |_        p| j        rd |D             }
t7          | j        |
          | _        | j                            |d                              |          | _        t#          | j                  | _        | j        j         }t5          | j                  |_        t'          | j!                  D ]=\  }}|                    |          x}| j!        |<   t5          | j                  |_        >| S )z
        Analyse the expressions. Take care to only evaluate default arguments
        once and clone the result for all specializations
        Nc                 0    g | ]}|t          |          S r8   )r   )r;   r  s     r4   r=   z9FusedCFuncDefNode.analyse_expressions.<locals>.<listcomp>  s%    JJJ7'JIg&&JJJr5   )rI   T)skip_children)"rL   rk   typesr   create_declaration_utility_coderb   r   analyse_expressionsr   r   defaultsr!   rI   r  
is_literalro   rO   r   coerce_to_tempr!  r.   r"   r   r\   	coerce_tor&   r   r   r   defaults_tupleanalyse_typescoerce_to_pyobjectr<   specialized_pycfuncs)r/   r0   fused_compound_typer   specialization_typerI  r<   r1  statr  rI   
fused_funcpycfuncs                r4   rH  z%FusedCFuncDefNode.analyse_expressionsi  sj   
 $(#< 	Q 	Q1AACC Q Q
+5+; Q Q'*5 Q+KKCPPPQQ
 < 	]"&"5"I"I#"N"ND<;;C@@DL,0,I,],]^a,b,bD))-)C)W)WX[)\)\D&#%%9> 		& 		&C{ &!k==cBB;) POODIck$:$:;;;; OOIck.H.H.M.M$N$NOOOO%%%% ,, 		o 		oGAt#'#;#;C#@#@@D4:a=$,, oT\1I1I$'	8$<$< o oLC*"- o*1*;*;CHc*J*JCKK*3G*<*<*P*PQT*U*U*_*_`c`hjm*n*nCK< 	HJJhJJJD"+DH4"@"@"@D"&"5"C"CCW["C"\"\"o"ops"t"tD"+D,?"@"@D6:J(1$2E(F(FJ%'(ABB H H
79@9N9Ns9S9SS$3A6)243F)G)G&&r5   c                 j   |D ]}d|j         j        _        d |D             }d t          ||          D             }d |D             }t          j                            | j        t          ||                    | _        || _	        |D ]	}d|_
        
t          |d                   | j        _        dS )zT
        Create the __signatures__ dict of PyCFunctionNode specializations.
        Fc                 @    g | ]}t          j        |j                  S r8   )r   r]   r   r;   r!   s     r4   r=   z9FusedCFuncDefNode.synthesize_defnodes.<locals>.<listcomp>  s6     ) ) ) %243TUU ) ) )r5   c                 J    g | ] \  }}t          j        |j        |           !S ))value)r   UnicodeNoder   )r;   r!   sigs      r4   r=   z9FusedCFuncDefNode.synthesize_defnodes.<locals>.<listcomp>  s>     9 9 9D# %dhc::: 9 9 9r5   c                 P    g | ]#}t           j                            |d           $S )T)binding)r   PyCFunctionNodefrom_defnoderX  s     r4   r=   z9FusedCFuncDefNode.synthesize_defnodes.<locals>.<listcomp>  s>     % % % +88t8LL % % %r5   Tr   N)r%   rQ   use_fastcallr\   r   DictNode
from_pairsr   r   rP  is_specializationr   rb   rT   )r/   r    r!   
signatureskeysvaluespycfuncnodes          r4   r>  z%FusedCFuncDefNode.synthesize_defnodes  s    
  	6 	6D05DJ --) )"') ) )
9 9!$UJ!7!79 9 9% %#% % % (0;;DHc$PVFWFWXX$*!! 	1 	1K,0K))#1%(#;#;   r5   c                 R   | j         r'd| j         _        | j                            ||           ddlm} | j        D ]j}t          |t                    rS|j	        j
        s|j        r@|j	        j        dk    s0|                    |j                   |                    ||           kd S )NTr   )Optionsextern)rb   pymethdef_requiredr   generate_function_definitionsr?   rj  r.   r"   r   r%   rY   cimport_from_pyx
visibilitymark_posr   )r/   r0   coderj  rS  s        r4   rm  z/FusedCFuncDefNode.generate_function_definitions  s    < 	P.2DL+&DDS$OOOJ 	> 	>D$,, >JO>->6:j6Kx6W6Wdh'''223===	> 	>r5   c                    | j         D ]}||                    |           | j        r| j                            |           t	                                          |           | j        rN| j                            |           | j                            |           |                    d| j        	                                d| j        	                                d           | j        
                    |           | j                            |           | j                            |           | j                            |           | j                            |           | j                            |           | j                            |           | j                            |           | j         D ].}|*|                    |           |                    |           /d S )Nz((__pyx_FusedFunctionObject *) z)->__signatures__ = ;)rI  generate_evaluation_coderb   rM  r   generate_execution_coder   r   r   r|   generate_giverefgenerate_post_assignment_code
free_tempsr   generate_disposal_code)r/   rq  r  r3   s      r4   ru  z)FusedCFuncDefNode.generate_execution_code  s    } 	7 	7G"00666< 	?88>>>''--- 	188>>>)BB4HHHJJJ%)%B%I%I%K%K%K%K%)%8%?%?%A%A%A%ACD D D 00666==dCCC**4000&>>tDDD )@@FFF)44T:::66t<<<**4000} 	) 	)G"..t444""4(((	) 	)r5   c                 D    | j         D ]}|                    |           d S r   )r.   annotate)r/   rq  rS  s      r4   r{  zFusedCFuncDefNode.annotate  s2    J 	  	 DMM$	  	 r5   )*__name__
__module____qualname____doc__r   r   r   rb   rM  
decoratorsr   child_attrsr   r#   r$   rJ   rR   rV   rW   r_   r   r   r   r   r   r   r%  r   r   r   r   r   r   r  ra   rB  rH  r>  rm  ru  r{  __classcell__)r3   s   @r4   r   r      s>        4 N# GNJ* .O .O .O OK# # # # #:.J .J .J`Z( Z( Z(x	 	 		2 	2 	2     "2 2 2   (  $    
: : :< < < GE2H%. %. %.N+ + +ZTD TD TDl? ? ?BN N N:  *!
 !
 !
Fj j jX#, #, #,J5 5 5n< < <.> > >#) #) #) #) #)J             r5   r   )rO   r?   r   r   r   r   r   r	   r
   r   r   r   r   Nodesr   r   r   Utilsr   r   r   r   r8   r5   r4   <module>r     s                     G F F F F F F F F F F F 5 5 5 5 5 5 5 5 5 5       + + + + + + + +_  _  _  _  _  _  _  _  _  _ r5   