U
    {h?                  	   @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZm	Z	 d dl
mZ d dlZddlmZ ddlmZmZmZ ddlmZmZ ddlmZ dd	lmZ d
dlmZmZmZ d
dlmZ ddl m!Z! d dl"Z#d dl$Z%d dl&m'Z' dd Z(G dd deeZ)ed4ddZ*d5ddZ+d6ddZ,dd Z-edd Z.i Z/e.dZ0d7ddZ1d d! Z2e+ej34e d"ddd#d#dddf	d$d%Z5d&Z6dddej7d'fd(d)Z8de5_9e:d*j;Z<d+d, Z=e:d-Z>d.d/ Z?d0d1 Z@G d2d3 d3ZAdS )8    N)Distribution	Extension)	build_ext   )Context)default_optionsCompilationOptionsget_directive_defaults)CythonTransformEnvTransform)SkipDeclarations)parse_from_strings   )strip_string_literals	cythonizecached_function)get_cython_cache_dir)Pipeline)ExtensionFileLoaderc                 C   s2   t jj| t| |d}t j|}|j| |S )N)loader)	importlibutilspec_from_file_locationr   module_from_specr   exec_module)namepathspecmodule r   7/tmp/pip-unpacked-wheel-fhl22ezh/Cython/Build/Inline.pyload_dynamic   s    r!   c                       s0   e Zd Z fddZdd Z fddZ  ZS )UnboundSymbolsc                    s   t t| jd d t | _d S )N)context)superr   __init__setunbound)self	__class__r   r    r%   $   s    zUnboundSymbols.__init__c                 C   s"   |   |js| j|j |S N)Zcurrent_envlookupr   r'   addr(   noder   r   r    visit_NameNode'   s    zUnboundSymbols.visit_NameNodec                    s   t  | | jS r+   )r$   __call__r'   r.   r)   r   r    r1   +   s    zUnboundSymbols.__call__)__name__
__module____qualname__r%   r0   r1   __classcell__r   r   r)   r    r"   #   s   r"   c                 C   s   |d krt g t ttd}ddlm} td| }t|dD ]$}|d krLq>||}t	||r> qdq>dd l
}tt |tt| S )Noptionsr   )AnalyseDeclarationsTransformz(tree fragment)Zpyxr   )r   r	   r   r   Compiler.ParseTreeTransformsr8   r   r   Zcreate_pipeline
isinstancebuiltinstupler"   r&   dir)coder#   r8   treephaser;   r   r   r    unbound_symbols0   s    

rA   c                 C   s"   t | }|tkrdS t| |S d S )Nlong)typeint	safe_type)argr#   py_typer   r   r    unsafe_typeA   s    rH   c                 C   s   t | }|ttttfkr|jS |tkr*dS |tkr6dS |tkrBdS dt	j
krpt| t	j
d jrpd| jj| jf S |jD ]N}|jdkr dS |j|jdd	}|rv||j}|jrvd
|j|jf   S qvdS d S )Nzdouble complexdoubleZbintnumpyz"numpy.ndarray[numpy.%s_t, ndim=%s])__builtin__r;   objectF)Zneed_pxdz%s.%s)rC   listr<   dictstrr2   complexfloatboolsysmodulesr:   ZndarrayZdtyper   ndim__mro__r3   find_moduler,   Zis_type)rF   r#   rG   Z	base_typer   entryr   r   r    rE   I   s(    

rE   c                  C   s,   t  } |  }| | t| }|  |S r+   )r   find_config_filesparse_config_filesr   finalize_options)distconfig_filesbuild_extensionr   r   r    _get_build_extensiona   s    
r_   c                 C   s   t t| t ttdS )Nr6   )r   rM   r	   r   r   )cython_include_dirsr   r   r    _create_contextl   s
    ra   ).c                 C   s   |D ]}|| kr|d ks |d krJt  jjj}|d kr<|j}|d krJ|j}t|ts\t|}||krr|| | |< q||kr|| | |< qtd|  qd S )NzCouldn't find %r)inspectcurrentframef_backf_locals	f_globalsr:   rN   print)kwdsrA   localsglobalssymbolZcalling_framer   r   r    _populate_unboundy   s    
rm   c                 C   s.   | |t jt j|tjf}tt|d	 S )Nzutf-8)
rS   version_info
executableCython__version__hashlibsha256rO   encode	hexdigest)	orig_codearg_sigslanguage_levelkeyr   r   r    _inline_key   s    rz   inlineFc
           ,   	      s^  d krdd |r t t|nt |r0t|ni }|	d krHd|krHd}	|	d k	rX|	|d< d }t| }|d k	rt||| t }t fdd|D }t	| ||	}t| ||f}|d k	rdd |D }|| S | }t
| \} }t| } |d kr
t jjj}|d kr"t jjj}z"t|  t|< }t||| W n$ tk
rh   |sdtd Y nX g }t D ](\}}|tkrz|d	|  |= qzt}t fd
d|D }|d krt	|||	}d| }|tjkrtj| }n4d }tjd kr t }|dt_tj|}tj ||tj }tj!|sXt"| |sltj#|sg }g }g }t$%d}|D ]b\}} |&|}!|!r|d|!' d   |!' d dkrdd l(}"||")  |d qt*| \}#}$d dd |D }%dd ||#|%|$d }&| D ]\}'}(|&+|'|(}&q*tj ||d })t,|)d}*z|*.|& W 5 |*-  X t/||)g|pd |pd |pd d}+|d krt }t0|+g|pdg||d|_1tj2|)|_3||_4|5  tj6dkr(tj7dkr(t8tj| t9||}W 5 Q R X n
t9||}|j:t|||f< fdd|D }|j:| S )Nc                 S   s   dS )NrL   r   )xr   r   r    <lambda>       zcython_inline.<locals>.<lambda>rx   3c                    s   g | ]\}}| |fqS r   r   ).0rF   value)ctxget_typer   r    
<listcomp>   s     z!cython_inline.<locals>.<listcomp>c                 S   s   g | ]}|d  qS )r   r   r   rF   r   r   r    r      s     z>Could not parse code as a string (to extract unbound symbols).z
cimport cython as %sc                    s   g | ]}|  |fqS r   r   r   r   r   ri   r   r    r      s     Z_cython_inline_ z([.\w]+)[.]z
cimport %sr   rJ   )ZNPY_NO_DEPRECATED_APIZNPY_1_7_API_VERSIONz, c                 S   s   g | ]}d | qS )z%s %sr   )r   ar   r   r    r      s     zf
%(module_body)s
%(cimports)s
def __invoke(%(params)s):
%(func_body)s
    return locals()
            
)cimportsmodule_bodyparams	func_bodyz.pyxw)r   sourcesinclude_dirsextra_compile_argsdefine_macrosrb   )Zinclude_pathZcompiler_directivesquietwin32)      c                    s   g | ]} | qS r   r   r   )ri   r   r    r     s     );ra   r<   _cython_inline_default_contextrN   _cython_inline_cachegetrm   sorteditemsrz   r   strip_common_indentrc   rd   re   rf   rg   rA   AssertionErrorrh   rM   cython_moduleappendrS   rT   cython_inlineso_extr_   Zget_ext_filenameosr   abspathjoinexistsmakedirsisfilerecompilematchgroupsrJ   Zget_includeextract_func_codereplaceopenclosewriter   r   
extensionsdirname
build_temp	build_librunplatformrn   Zadd_dll_directoryr!   Z__invoke),r>   r   lib_dirr`   cython_compiler_directivesforcer   rj   rk   rx   ri   Zkey_hashZ_unbound_symbolsargsrw   Zinvokearg_listrv   literalsr   r   rF   	arg_namesmodule_namer   r^   module_pathcflagsr   Zc_include_dirsZ	qualifiedrC   _mrJ   r   r   r   Zmodule_codery   r   Zpyx_filefh	extensionr   r   r    r      s    














r   a=  
def __PYX_repeat_benchmark(benchmark, timer, size_t number):
    cdef size_t i

    t0 = timer()
    for i in range(number):
        benchmark()
    t1 = timer()
    return t1 - t0

def __PYX_make_benchmark():
    {setup_code}

    def __PYX_run_benchmark():
        {benchmark_code}

    return __PYX_run_benchmark
	   c                    s  ddl }|rt|nd}|  r(t| nd} |r:t|jnd}tj||d || d d}t|||d}	|	d	 |	d
 fddt	 t
rdnd}
r|
d n|
d fdd}|  | fddt|D }d   fdd|D }|fS )a  Benchmark a Cython code string similar to 'timeit'.

    'setup_code': string of setup code that will be run before taking the timings.

    'import_module': a module namespace to run the benchmark in
                     (usually a compiled Cython module).

    'directives': Cython directives to use when compiling the benchmark code.

    'timer': The timer function. Defaults to 'time.perf_counter', returning float seconds.
             Nanosecond timers are detected (and can only be used) if they return integers.

    'repeat': The number of timings to take and return.

    Returns a tuple: (list of single-loop timings, number of loops run for each)
    r   Nr   pass    z        )
setup_codeZbenchmark_code)r   rj   Z__PYX_make_benchmarkZ__PYX_repeat_benchmarkc                    s:     }t  }t   z|| }W 5 |r4t   X |S r+   )gc	isenableddisableenable)numberZ	benchmarkZgcoldtiming)make_benchmarkrepeat_benchmarktimerr   r    timeit\  s    
zcymeit.<locals>.timeiti ʚ;g      ?   c                     st   d} dD ]\}| | }|}t |r(tnts2t| krB|  S r|dk r|dkrtd q| d9 } qd S )Nr   )r   r   r   
   z&Timer seems to return non-ns timings: )r:   rD   rQ   r   RuntimeError)ijr   Z
time_taken)min_runtimer   r   timer_returns_nanosecondsr   r    	autorangep  s    zcymeit.<locals>.autorangec                    s   g | ]} qS r   r   )r   r   )r   r   r   r    r     s   zcymeit.<locals>.<listcomp>r   c                    s$   g | ]}r|   n| qS r   r   )r   r   )halfr   r   r   r    r     s   )textwrapr   strip
__import____dict___CYMEIT_TEMPLATEformatindentr   r:   rD   range)r>   r   import_moduleZ
directivesr   repeatr   Zmodule_namespaceZcymeit_code	namespaceZ
one_secondr   Ztimingsr   )r   r   r   r   r   r   r   r   r    cymeit1  s<    r   z\Sc                 C   s   d }|   }|D ]<}t|}|s"q| }|| dkr8q|d ksH||kr|}qt|D ]>\}}t|}|rV|rV|||d  dkrqV||d  ||< qVd|S )N#r   r   )
splitlines_find_non_spacestart	enumerater   )r>   Z
min_indentlinesliner   r   ixr   r   r    r     s"    r   zI^((cdef +(extern|class))|cimport|(from .+ cimport)|(from .+ import +[*]))c                 C   sl   g }g }|}|  dd} | d}|D ],}|dsHt|rD|}n|}|| q&d|dd| fS )N	 r   r   z
    )r   split
startswithmodule_statementr   r   r   )r>   r   functioncurrentr   r   r   r   r    r     s    


r   c                 C   sB   |  d}| d d dkr.d| |d d   S | |d d  S d S )N:r   lambdaz	return %sr   )index)sourcer   r   r   r    get_body  s    
r   c                   @   s   e Zd Zdd Zdd ZdS )RuntimeCompiledFunctionc                 C   s   || _ tt|| _d S r+   )_fr   rc   	getsource_body)r(   fr   r   r    r%     s    z RuntimeCompiledFunction.__init__c                 O   s4   t j| jf||}t| jf| jj| jjd|S )N)rj   rk   )rc   getcallargsr   r   r   __globals__)r(   r   ri   allr   r   r    r1     s    z RuntimeCompiledFunction.__call__N)r2   r3   r4   r%   r1   r   r   r   r    r     s   r   )N)N)N)NN)Br   rr   rc   r   r   rS   timedistutils.corer   r   Zdistutils.command.build_extr   rp   ZCompiler.Mainr   ZCompiler.Optionsr   r   r	   ZCompiler.Visitorr
   r   r9   r   ZCompiler.TreeFragmentr   ZDependenciesr   r   r   Cacher   ZCompilerr   Zcythonr   importlib.utilr   Zimportlib.machineryr   r!   r"   rA   rH   rE   r_   ra   r   r   rm   rz   r   r   r   r   perf_counterr   r   r   searchr   r   r   r   r   r   r   r   r   r    <module>   sj   



     
 
b

