o
    f:                    @   s8  d dl mZ d dlZejdai dedededededed	ed
edededededededede 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 d dlmZ d dlmZ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 zd d lmZ W n ey   d d!l m!Z Y nw d"d#d#d$d%d&Z"d'd(d)d*d+Z#d,d-iZ$g d.Z%ee&e&d/Z'd0d1ij(Z)G d2d3 d3eZ*d4d5 Z+dZ,	 d6d7 Z-e-Z,G d8d9 d9eZ.G d:d; d;e.Z/ddi fd<d=Z0G d>d? d?e/Z1G d@dA dAe.Z2G dBdC dCeZ3G dDdE dEeZ4G dFdG dGeZ5ejeeeedH e6dI7dJej8j9Z:e6dK;dLj9Z<e6dMj=Z>e6dNj?Z@G dOdP dPeZAG dQdR dReZBG dSdT dTeZCdUdV ZDG dWdX dXeZEG dYdZ dZeZFG d[d\ d\eZGG d]d^ d^eZHG d_d` d`eZIdS )b    )absolute_importNosreoperatortextwrapTemplateNamingOptionsStringEncodingUtilsSourceDescriptorStringIOTree
DebugFlags
basestringdefaultdictclosingpartialr   )r   )r   contextmanager)r      )r   )r	   )r   )r
      )r   )r   )r   )r   )str)zPY_MAJOR_VERSION < 3r   )PY_MAJOR_VERSION >= 3r   )r   range)r   input)bytesunicoder   xrange	raw_inputz&PyInt_Typez&PyLong_Typez&PyFloat_Typez&PyWrapperDescr_Type)py_intpy_longpy_floatwrapper_descriptorPyTypeObjectPyHeapTypeObject) _IncompleteInputErrorPythonFinalizationErrorBaseExceptionGroupExceptionGroupaiteranextEncodingWarning
breakpoint
__loader____spec__BlockingIOErrorBrokenPipeErrorChildProcessErrorConnectionAbortedErrorConnectionErrorConnectionRefusedErrorConnectionResetErrorFileExistsErrorFileNotFoundErrorInterruptedErrorIsADirectoryErrorModuleNotFoundErrorNotADirectoryErrorPermissionErrorProcessLookupErrorRecursionErrorResourceWarningTimeoutError__build_class__asciiWindowsError_)	__cinit____dealloc____richcmp____next__	__await__	__aiter__	__anext____getreadbuffer____getwritebuffer____getsegcount____getcharbuffer____getbuffer____releasebuffer__inlineCYTHON_INLINEc                   @   sJ   e Zd ZdZdZdZdZdZddd	Zd
d Z	dd Z
dd Zdd ZdS )IncludeCodez]
    An include file and/or verbatim C code to be included in the
    generated sources.
    r   r   r   NTFc                 C   s   | j | _t|  j d7  _ i | _|r1|d dkr)|d dkr)d|| jd< d}nd|| jd< |r9|| j| j< |rA| j| _d S |rI| j| _d S | j| _d S )	Nr   r   <>z#include {0}Fz#include "{0}")	counterordertypepiecesformatINITIALlocationLATEEARLY)selfincludeverbatimlateinitial rf   P/var/www/html/mig_web/myenv/lib/python3.10/site-packages/Cython/Compiler/Code.py__init__   s   zIncludeCode.__init__c                 C   s>   ||v r|| }t | j|j|_|j| j dS | ||< dS )z
        Insert `self` in dict `d` with key `key`. If that key already
        exists, update the attributes of the existing value with `self`.
        N)minr^   r[   update)ra   dkeyotherrf   rf   rg   dict_update   s
   zIncludeCode.dict_updatec                 C   s   | j S N)rY   ra   rf   rf   rg   sortkey   s   zIncludeCode.sortkeyc                 C   s   | j dS )z
        Return the main piece of C code, corresponding to the include
        file. If there was no include file, return None.
        r   )r[   getrp   rf   rf   rg   	mainpiece   s   zIncludeCode.mainpiecec                 C   s$   t | jD ]
}|| j|  qd S ro   )sortedr[   putln)ra   codekrf   rf   rg   write   s   zIncludeCode.write)NNTF)__name__
__module____qualname____doc__r]   r`   r_   rX   rh   rn   rq   rs   rx   rf   rf   rf   rg   rT   |   s    
rT   c                  C   s*   t jt jt jt} t j| dS )NUtility)r   pathdirnameabspath__file__join)
Cython_dirrf   rf   rg   get_utility_dir   s   r   c                 C   sN   t jt | }ttj|dd}| W  d   S 1 s w   Y  dS )zh
    Read all lines of the file at the provided path from a path relative
    to get_utility_dir().
    UTF-8)encodingN)r   r~   r   r   r   r   open_source_file	readlines)r~   filenamefrf   rf   rg   read_utilities_from_utility_dir   s   $r   c                   @   s   e Zd ZdZdZi ZedddZedd Zedd	 Z	ei fd
dZ
edd ZedjfddZdd Zdd ZdddZdS )UtilityCodeBasea(  
    Support for loading utility code from a file.

    Code sections in the file can be specified as follows:

        ##### MyUtility.proto #####

        [proto declarations]

        ##### MyUtility.init #####

        [code run at module initialization]

        ##### MyUtility #####
        #@requires: MyOtherUtility
        #@substitute: naming

        [definitions]

        ##### MyUtility #####
        #@substitute: tempita

        [requires tempita substitution
         - context can't be specified here though so only
           tempita utility that requires no external context
           will benefit from this tag
         - only necessary when @required from non-tempita code]

    for prototypes and implementation respectively.  For non-python or
    -cython files backslashes should be used instead.  5 to 30 comment
    characters may be used on either side.

    If the @cname decorator is not used and this is a CythonUtilityCode,
    one should pass in the 'name' keyword argument to be used for name
    mangling of such entries.
    FNc              
   C   s   |d u rd S d |}|r:d|v r:d|d v r:zt|tt}W n ttfy9 } z	td|||f d }~ww d| | }|dkrI||d< n|dkrR||d< n|d	 }|||< |rs|d	 }| D ]\}	}
|	|	t
 |
 qdd S d S )
N

substitutenamingz@Error parsing templated utility code of type '%s' at line %d: %sprotor   implr   r   )r   r   r   varsr   KeyError
ValueErrorRuntimeErroritems
setdefaultsetrj   )clsutilityrZ   linesbegin_linenotagsrv   eall_tagsnamevaluesrf   rf   rg   _add_utility  s2   


zUtilityCodeBase._add_utilityc                 C   s  | j |}|r
|S tj|\}}|dv r&d}ttdjd}t	j
j}nd}ttdjd}ttdjd}td	d
|i j}tdj}	t|}
tdd }g }tt}d  }}d}t|
D ]Z\}}||}|r|dr| ||||| |d }|d d = |  |d}|	|}|r| \}}nd}|| }qd||d |d |d qd|||| qd|d u rtd| ||||| t|}|| j |< |S )N)z.pyxz.pyz.pxdz.pxi#z^\s*#(?!\s*cython\s*:).* /z^\s*//.*|/\*[^*]*\*/z	\s+(\\?)$z\1zd^%(C)s{5,30}\s*(?P<name>(?:\w|\.)+)\s*%(C)s{5,30}|^%(C)s+@(?P<tag>\w+)\s*:\s*(?P<value>(?:\w|[.:])+)Cz,(.+)[.](proto(?:[.]\S+)?|impl|init|cleanup)$c                   S   s
   d d i gS ro   rf   rf   rf   rf   rg   <lambda>B     
 z:UtilityCodeBase.load_utilities_from_file.<locals>.<lambda>r   r   r   r   tagvaluezEmpty utility code file)_utility_cacherr   r   r~   splitextr   r   compilesubr
   _unicoderstripmatchread_utilities_hookr   r   	enumerategroupr   cleargroupsaddappendr   dict)r   r~   	utilitiesrD   extcommentstrip_commentsr   match_special
match_type	all_linesr   r   r   rZ   r   linenolinemr   mtyperf   rf   rg   load_utilities_from_file+  s`   





z(UtilityCodeBase.load_utilities_from_filec           
         sl  d|v r| dd\}sJ  }|| \}}}|rd|v r7d|d v r7t ts7tj|fi |S | | D ]M\}}	||v rHq?|dkrir\ fddt|	D }	n, fddt|	D }	n|dkrw|	d	dh }	|	svq?n|	s|d
}	nt|	dkrt	|	d }	|	||< q?|d
ur||d< |d
ur||d< d|vr||d< d|vrr|d<  di |S )z
        Load utility code from a file specified by from_file (relative to
        Cython/Utility) and name util_code_name.
        z::r   r   tempitarequiresc                    s    g | ]} j |fi qS rf   )load.0depr   	from_fileorig_kwargsrf   rg   
<listcomp>  s    z(UtilityCodeBase.load.<locals>.<listcomp>c                    s   g | ]}  |qS rf   )load_cachedr   )r   r   rf   rg   r     s    r   Nr   r   r   r   filerf   )
rsplitr   
issubclassTempitaUtilityCoder   copyr   rt   lenlist)
r   util_code_namer   kwargsr   r   r   r   r   r   rf   r   rg   r   i  sP   


zUtilityCodeBase.loadc                 C   s@   ||| f}z|| W S  t y   Y nw | || }||< |S )z`
        Calls .load(), but using a per-type cache based on utility name and file name.
        )r   r   )r   utility_code_namer   _UtilityCodeBase__cacherl   rv   rf   rf   rg   r     s   

zUtilityCodeBase.load_cachedc                 K   s6   | j ||fi |}|j|j}}||||fS )zR
        Load a utility code as a string. Returns (proto, implementation)
        )r   r   r   format_code)r   r   r   r   utilr   r   rf   rf   rg   load_as_string  s   zUtilityCodeBase.load_as_stringz\n\n+c                 C   s   |r|d|  d }|S )z3
        Format a code section for output.
        r   z

strip)ra   code_stringreplace_empty_linesrf   rf   rg   r     s   zUtilityCodeBase.format_codec                 C   s   dt | j| jf S )Nz<%s(%s)>)rZ   ry   r   rp   rf   rf   rg   __repr__     zUtilityCodeBase.__repr__c                 K      d S ro   rf   )ra   r   rf   rf   rg   get_tree     zUtilityCodeBase.get_treec                 C   s   | S ro   rf   )ra   memodictrf   rf   rg   __deepcopy__  s   zUtilityCodeBase.__deepcopy__ro   )ry   rz   r{   r|   is_cython_utilityr   classmethodr   r   r   r   r   r   r   r   r   r   r   r   rf   rf   rf   rg   r      s$    %
=
5
r   c                   @   s`   e Zd ZdZ		dddZdd Zdd	 Zd
d ZdddZdd Z	dd Z
dd Zdd ZdS )UtilityCodeaF  
    Stores utility code to add during code generation.

    See GlobalState.put_utility_code.

    hashes/equals by instance

    proto           C prototypes
    impl            implementation code
    init            code to call on module initialization
    requires        utility code dependencies
    proto_block     the place in the resulting file where the prototype should
                    end up
    name            name of the utility code (or None)
    file            filename of the utility code file this utility was loaded
                    from (or None)
    Nutility_code_protoc	           	      C   s@   || _ || _|| _|| _|| _i | _g | _|| _|| _|| _	d S ro   )
r   r   initcleanupr   _cachespecialize_listproto_blockr   r   )	ra   r   r   r   r   r   r   r   r   rf   rf   rg   rh     s   
zUtilityCode.__init__c                 C   s   t | j| jfS ro   )hashr   r   rp   rf   rf   rg   __hash__     zUtilityCode.__hash__c                 C   s   | |u rdS t | t |}}||urt||st| |sdS t| dd }t|dd }t| dd }t|dd }||| jf|||jfkS )NTFr   r   )rZ   
isinstancegetattrr   )ra   rm   	self_type
other_type	self_init
other_init
self_protoother_protorf   rf   rg   __eq__  s   zUtilityCode.__eq__c                 C   s   |du rdS || S zY
        Format a string in this utility code with context. If None, do nothing.
        Nrf   ra   scontextrf   rf   rg   none_or_sub  s   zUtilityCode.none_or_subc                    s   | j }|d ur|  d< |  d< d| d f }tt  }z| j| W S  typ   | jd u r8d }n
 fdd| jD }t	| 
| j | 
| j | 
| j | 
| j || j| }| j|< | j| | Y S w )NrZ   	type_namez%s[%s]c                    s   g | ]}|  qS rf   )
specialize)r   rdatarf   rg   r         z*UtilityCode.specialize.<locals>.<listcomp>)r   empty_declaration_codespecialization_nametuplert   r   r   r   r   r   r  r   r   r   r   r   r   r   )ra   
pyrex_typer  r   rl   r   r  rf   r  rg   r    s0   

zUtilityCode.specializec                    sT   d|vrd|vrd|fS i  fdd}t d||}d|vr$d|vs&J d|fS )zHReplace 'PYIDENT("xyz")' by a constant Python identifier cname.
        zPYIDENT(z
PYUNICODE(Fc                    sV   |   }z| }W |S  ty*   |\}} jt||dkdj }|< Y |S w )NIDENT
identifier)r   r   get_py_string_constr
   EncodedStringcname)matchobjrl   r  str_typer   outputreplacementsrf   rg   externalise%  s   
z8UtilityCode.inject_string_constants.<locals>.externalisezPY(IDENT|UNICODE)\("([^"]+)"\)Tr   r   ra   r   r  r  rf   r  rg   inject_string_constants  s   
z#UtilityCode.inject_string_constantsc                    s>   d|vrd|fS  fdd}t d||}d|vsJ d|fS )zVReplace 'UNBOUND_METHOD(type, "name")' by a constant Python identifier cname.
        zCALL_UNBOUND_METHOD(Fc                    s`   |   \}}}}|rdd |dd  dD ng }t|dk s(J dt|  ||||S )Nc                 S   s   g | ]}|  qS rf   r   )r   argrf   rf   rg   r   ;  s    zKUtilityCode.inject_unbound_methods.<locals>.externalise.<locals>.<listcomp>r   ,   z8CALL_UNBOUND_METHOD() does not support %d call arguments)r   splitr   cached_unbound_method_call_code)r  
type_cnamemethod_name	obj_cnameargsr  rf   rg   r  9  s   $z7UtilityCode.inject_unbound_methods.<locals>.externalisezJCALL_UNBOUND_METHOD\(([a-zA-Z_]+),\s*"([^"]+)",\s*([^),]+)((?:,[^),]+)*)\)Tr  r  rf   r&  rg   inject_unbound_methods3  s   z"UtilityCode.inject_unbound_methodsc                 C   s2   d|vr|S dd }t d||}d|vsJ |S )z<Replace CSTRING('''xyz''') by a C compatible string
        zCSTRING(c                 S   s*   |  ddd}ddd | D S )Nr   "r   c                 s   s<    | ]}| d r| drd| nd|dd  V  qdS )\z\\z"%s\n"
z"%s"
NrV   )endswithr   r   rf   rf   rg   	<genexpr>R  s
    *
zCUtilityCode.wrap_c_strings.<locals>.split_string.<locals>.<genexpr>)r   replacer   
splitlines)r  contentrf   rf   rg   split_stringP  s   
z0UtilityCode.wrap_c_strings.<locals>.split_stringz)CSTRING\(\s*"""([^"]*(?:"[^"]+)*)"""\s*\)r  )ra   r   r0  rf   rf   rg   wrap_c_stringsJ  s   zUtilityCode.wrap_c_stringsc                 C   s  | j r| j D ]}|| q| jr+|| j }|d| j  || | jd| j  | jrf| | 	| j}| 
||\}}| ||\}}|d }|d| j  |sa|sa||d| j  n|| | jr|d }|d| j  t| jtr|| | j n| ||j |||j |  | jrtjr|d }|d	| j  t| jtr|| | jd
| j  d S | ||j d S d S d S )Nz/* %s.proto */z%s_protoutility_code_defz/* %s */z%s_implinit_globalsz/* %s.init */cleanup_globalsz/* %s.cleanup */z
%s_cleanup)r   use_utility_coder   r   ru   r   put_or_includer   r   r1  r  r'  putr   r   r   
module_poserror_goto_if_PyErrr   r	   generate_cleanup_code)ra   r  
dependencywriterr   is_specialised1is_specialised2rf   rf   rg   put_codeZ  sH   



zUtilityCode.put_code)NNNNNr   NNro   )ry   rz   r{   r|   rh   r   r   r  r  r  r'  r1  r?  rf   rf   rf   rg   r     s    

r   c                 C   sn   | sdS |rd||f }|r||d< z||  }W n t y1   ddlm} || |d }|| < Y nw ||S )z+Run tempita on string s with given context.Nz%s:%s__namer   r   r   )r   Tempitar   r   )r  r  r   r   __cachetemplater   rf   rf   rg   sub_tempita  s   
rE  c                       s:   e Zd Zd fdd	Zeddi fddZdd Z  ZS )	r   Nc                    s\   |d u ri }t ||||}t ||||}t ||||}tt| j||f|||d| d S )N)r   r   r   )rE  superr   rh   )ra   r   r   r   r   r   r  r   	__class__rf   rg   rh     s   

zTempitaUtilityCode.__init__c                 C   sn   |r
t t| nd }t|d usJ | |||f}z|| W S  ty(   Y nw | j|||d }||< |S )N)r  )r  rt   r   r   r   r   )r   r   r   r  _TempitaUtilityCode__cachecontext_keyrl   rv   rf   rf   rg   r     s   
zTempitaUtilityCode.load_cachedc                 C   s   |du rdS t ||| j| jS r   )rE  r   r   r   rf   rf   rg   r    s   zTempitaUtilityCode.none_or_sub)NNNNNN)ry   rz   r{   rh   r   r   r  __classcell__rf   rf   rG  rg   r     s
    	r   c                   @   s(   e Zd ZdZdZ dZdd Zdd ZdS )LazyUtilityCodez
    Utility code that calls a callback with the root code writer when
    available. Useful when you only have 'env' but not 'code'.
    z<lazy>Nc                 C   s
   || _ d S ro   )callback)ra   rM  rf   rf   rg   rh        
zLazyUtilityCode.__init__c                 C   s   |  |j}|| d S ro   )rM  
rootwriterr5  )ra   globalstater   rf   rf   rg   r?       zLazyUtilityCode.put_code)ry   rz   r{   r|   r   rh   r?  rf   rf   rf   rg   rL    s    rL  c                   @   s   e Zd Ze dfddZdd Zd2ddZd3d	d
Zd4ddZdd Z	dd Z
d4ddZdd Zdd Zdd Zdd Zdd Zd5d d!Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 ZdS )6FunctionStateNc                 C   s   || _ || _|| _d | _d| _t | _|  | _| 	  d | _
d | _g | _d| _d | _d | _d| _d| _g | _i | _i | _t | _d| _d | _g | _d| _d| _d| _d| _d S )Nr   FT)names_takenownerscopeerror_labellabel_counterr   labels_used	new_labelreturn_labelnew_error_labelcontinue_labelbreak_labelyield_labelsin_try_finallyexc_varscurrent_except	can_trace	gil_ownedtemps_allocated
temps_freetemps_used_typezombie_tempstemp_counterclosure_tempscollect_temps_stackshould_declare_error_indicatoruses_error_indicatorerror_without_exceptionneeds_refnanny)ra   rT  rS  rU  rf   rf   rg   rh     s6   

zFunctionState.__init__c                 C   sF   | j r|  }|r!d| jjddd t|D f }t|d S d S )Nz-TEMPGUARD: Temps left over at end of '%s': %s, c                 S   s   g | ]\}}}d ||f qS )z%s [%s]rf   )r   r   ctype	is_pytemprf   rf   rg   r     s    
z/FunctionState.validate_exit.<locals>.<listcomp>)rd  temps_in_userU  r   r   rt   r   )ra   	leftoversmsgrf   rf   rg   validate_exit   s   zFunctionState.validate_exitc                 C   s6   | j }|d | _ dtj|f }|d ur|d| 7 }|S )Nr   %s%drD   )rW  r   label_prefix)ra   r   nlabelrf   rf   rg   rY    s   
zFunctionState.new_labelyieldc                 C   s0   |  d| }t| jd |f}| j| |S )Nzresume_from_%sr   )rY  r   r^  r   )ra   	expr_typery  num_and_labelrf   rf   rg   new_yield_label  s   zFunctionState.new_yield_labelr   c                 C   s   | j }| |d | _ |S )Nerror)rV  rY  )ra   prefixold_err_lblrf   rf   rg   r[    s   zFunctionState.new_error_labelc                 C   s   | j | jfS ro   r\  r]  rp   rf   rf   rg   get_loop_labels!  s   zFunctionState.get_loop_labelsc                 C   s   |\| _ | _d S ro   r  ra   labelsrf   rf   rg   set_loop_labels&  s   zFunctionState.set_loop_labelsc                 C   s.   |   }| | |d | |d f |S )Ncontinuebreak)r  r  rY  )ra   r  
old_labelsrf   rf   rg   new_loop_labels*  s   zFunctionState.new_loop_labelsc                 C   s   | j | j| j| jfS ro   r\  r]  rZ  rV  rp   rf   rf   rg   get_all_labels1  s
   zFunctionState.get_all_labelsc                 C   s   |\| _ | _| _| _d S ro   r  r  rf   rf   rg   set_all_labels8  s
   zFunctionState.set_all_labelsc                 C   sR   |   }g }t|g dD ]\}}|r|| | q|| q| | |S )N)r  r  returnr~  )r  zipr   rY  r  )ra   r  
new_labels	old_labelr   rf   rf   rg   all_new_labels>  s   
zFunctionState.all_new_labelsc                 C      | j | d S ro   )rX  r   ra   lblrf   rf   rg   	use_labelI  r   zFunctionState.use_labelc                 C   s
   || j v S ro   )rX  r  rf   rf   rg   
label_usedL  rN  zFunctionState.label_usedFTc                 C   s^  |j r
|js
|j}n/|jr|js|j}n%|jr#ddlm} ||}n|j	r9|js9| j
jd r9| j
tdd |js>d}| j||f}|r^|dur^|d r^|d  }|d | n)	 |  jd7  _d
tj| jf }|| jvrtnq_| j||||f |s| j| ||f| j|< tjr| j d|||rdndf  | j!r| j!d ||f |S )a
  
        Allocates a temporary (which may create a new one or get a previously
        allocated and released one of the same type). Type is simply registered
        and handed back, but will usually be a PyrexType.

        If type.needs_refcounting, manage_ref comes into play. If manage_ref is set to
        True, the temp will be decref-ed on return statements and in exception
        handling clauses. Otherwise the caller has to deal with any reference
        counting of the variable.

        If not type.needs_refcounting, then manage_ref will be ignored, but it
        still has to be passed. It is recommended to pass False by convention
        if it is known that type will never be a reference counted type.

        static=True marks the temporary declaration with "static".
        This is only used when allocating backing store for a module-level
        C array literals.

        if reusable=False, the temp will not be reused after release.

        A C string referring to the variable is returned.
        r   )
PyrexTypes
cpp_localsOptionalLocalszCppSupport.cppFNr   Trv  z/* %s allocated (%s)%s */r   	 - zombierV   )"is_cv_qualifiedis_referencecv_base_typeis_fake_referenceref_base_typeis_cfunctionr   r  
c_ptr_typeis_cpp_classrU  
directivesr5  r   r   needs_refcountingre  rr   popremoverh  r   codewriter_temp_prefixrS  rd  r   rg  r   rf  r   debug_temp_code_commentsrT  ru   rj  )ra   rZ   
manage_refstaticreusabler  freelistresultrf   rf   rg   allocate_tempQ  s:   zFunctionState.allocate_tempc                 C   s   | j | \}}| j||f}|du rg t f}|| j||f< ||d v r+td| || jvr7|d | |d | tj	rT| j
d||| jv rMdndf  dS dS )zv
        Releases a temporary so that it can be reused by other code needing
        a temp of the same type.
        Nr   zTemp %s freed twice!r   z/* %s released %s*/r  r   )rf  re  rr   r   r   rg  r   r   r   r  rT  ru   )ra   r   rZ   r  r  rf   rf   rg   release_temp  s   

zFunctionState.release_tempc                 C   sV   g }| j D ]#\}}}}| j||f}|du s||d vr(||||o%|jf q|S )zxReturn a list of (cname,type,manage_ref) tuples of temp names and their type
        that are currently in use.
        Nr   )rd  re  rr   r   r  )ra   usedr   rZ   r  r  r  rf   rf   rg   rr    s   zFunctionState.temps_in_usec                 C   s   dd |   D S )zReturn a list of (cname,type) tuples of temp names and their type
        that are currently in use. This includes only temps
        with a reference counted type which owns its reference.
        c                 S   s$   g | ]\}}}|r|j r||fqS rf   )r  )r   r   rZ   r  rf   rf   rg   r     s    z9FunctionState.temps_holding_reference.<locals>.<listcomp>)rr  rp   rf   rf   rg   temps_holding_reference  s   z%FunctionState.temps_holding_referencec                 C   s   dd | j D S )zRReturn a list of (cname, type) tuples of refcount-managed Python objects.
        c                 S   s    g | ]\}}}}|r||fqS rf   rf   )r   r  rZ   r  r  rf   rf   rg   r     s    
z3FunctionState.all_managed_temps.<locals>.<listcomp>)rd  rp   rf   rf   rg   all_managed_temps  s   zFunctionState.all_managed_tempsc                 C   s   t dd | j D S )zReturn a list of (cname, type) tuples of refcount-managed Python
        objects that are not currently in use.  This is used by
        try-except and try-finally blocks to clean up temps in the
        error case.
        c                 S   s.   g | ]\\}}}|r|d  D ]}||fqqS r   rf   )r   rZ   r  r  r  rf   rf   rg   r     s    z8FunctionState.all_free_managed_temps.<locals>.<listcomp>)rt   re  r   rp   rf   rf   rg   all_free_managed_temps  s   z$FunctionState.all_free_managed_tempsc                 C   s   | j t  dS )zJ
        Useful to find out which temps were used in a code block
        N)rj  r   r   rp   rf   rf   rg   start_collecting_temps  s   z$FunctionState.start_collecting_tempsc                 C   
   | j  S ro   )rj  r  rp   rf   rf   rg   stop_collecting_temps  rN  z#FunctionState.stop_collecting_tempsc                 C   s   t || _d S ro   )ClosureTempAllocatorri  ra   rU  rf   rf   rg   init_closure_temps     z FunctionState.init_closure_tempsro   )rz  r   )FT)ry   rz   r{   r   rh   ru  rY  r}  r[  r  r  r  r  r  r  r  r  r  r  rr  r  r  r  r  r  r  rf   rf   rf   rg   rR    s.    ,




:	rR  c                   @   s   e Zd ZdZdddZdS )NumConstzGlobal info about a Python number constant held by GlobalState.

    cname       string
    value       string
    py_type     string     int, long, float
    value_code  string     evaluation code if different from value
    Nc                 C   s    || _ || _|| _|p|| _d S ro   )r  r   py_type
value_code)ra   r  r   r  r  rf   rf   rg   rh     s   zNumConst.__init__ro   ry   rz   r{   r|   rh   rf   rf   rf   rg   r    s    r  c                   @   s   e Zd ZdZdd ZdS )PyObjectConstz>Global info about a generic constant held by GlobalState.
    c                 C   s   || _ || _d S ro   )r  rZ   ra   r  rZ   rf   rf   rg   rh     s   
zPyObjectConst.__init__Nr  rf   rf   rf   rg   r    s    r  )possible_unicode_identifierpossible_bytes_identifierreplace_identifierfind_alphanumss   (?![0-9])\w+$rB   z(?![0-9])\w+$ASCIIz[^a-zA-Z0-9_]+z([a-zA-Z0-9]+)c                   @   s.   e Zd ZdZdd Zdd Z		d
dd	ZdS )StringConstz?Global info about a C string constant held by GlobalState.
    c                 C   s(   || _ || _t|| _d | _g | _d S ro   )r  textr
   escape_byte_stringescaped_value
py_stringspy_versions)ra   r  r  byte_stringrf   rf   rg   rh     s
   
zStringConst.__init__c                 C   s0   |s	ddg| _ d S || j vr| j | d S d S )Nr   r  )r  r   )ra   versionrf   rf   rg   add_py_version  s
   
zStringConst.add_py_versionNFc                 C   sH  | j }| j}t|p
|}|d u o| }|d u rd }n| }|dv r'd }d }ndt|}||||f}	|d urGz||	 W S  tyF   Y nw i | _ |rOd}
n|d u rft|tr_tt	|}
n	tt
|}
nd}
|
rptjd }ntj}|rzd| }nd}d||rdp|rd	pd
|| jttjd  f }t||||||
}|| j |	< |S )N)utf8zutf-8rB   usasciizus-asciir   TFr   z_%sz	%s%s%s_%sr  ub)r  r  boollowerr   r  r   r   r   r  r  r   interned_prefixespy_const_prefixr  r   const_prefixPyStringConst)ra   r   r  is_strpy3str_cstringr  r  
is_unicodeencoding_keyrl   internr  encoding_prefixpystring_cname	py_stringrf   rf   rg   r    sV   



zStringConst.get_py_string_constNFN)ry   rz   r{   r|   rh   r  r  rf   rf   rf   rg   r    s    r  c                   @   s&   e Zd ZdZ		dddZdd ZdS )	r  zDGlobal info about a Python string constant held by GlobalState.
    FNc                 C   s(   || _ || _|| _|| _|| _|| _d S ro   )r  r  r   r  r  r  )ra   r  r   r  r  r  r  rf   rf   rg   rh   M  s   
zPyStringConst.__init__c                 C   s   | j |j k S ro   )r  ra   rm   rf   rf   rg   __lt__V     zPyStringConst.__lt__)FNF)ry   rz   r{   r|   rh   r  rf   rf   rf   rg   r  C  s    	
	r  c                   @   sV  e Zd Zi Zg dZg dZdNddZdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdNddZdOddZdd ZdPddZdNddZdd Z		dQd d!Zd"d# Zd$d% ZdNd&d'ZdRd(d)Zd*d+ Zd,d- Zd.d/ ZdSd0d1Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!d>d? Z"d@dA Z#dBdC Z$dDdE Z%dFdG Z&dHdI Z'dJdK Z(dLdM Z)dS )TGlobalState) h_codefilename_tableutility_code_proto_before_typesnumeric_typedefscomplex_type_declarationstype_declarationsr   module_declarationstypeinfobefore_global_var
global_varstring_declsdeclslate_includesmodule_statemodule_state_clearmodule_state_traversemodule_state_definesmodule_codepystring_tablecached_builtinscached_constantsinit_constantsr3  init_moduler4  cleanup_modulemain_methodutility_code_pragmasr2  utility_code_pragmas_endend)r  r  r  r   r  Nc                 C   s   i | _ g | _i | _t | _i | _d| _|| _|| _i | _	|| _
i | _i | _i | _i | _i | _g | _i | _t | _||  || _d S )NF)r  filename_listinput_file_contentsr   utility_codesdeclared_cnamesin_utility_code_generationcode_configcommon_utility_include_dirpartsmodule_nodeconst_cnames_usedstring_const_indexdedup_const_indexpyunicode_ptr_const_indexnum_const_indexpy_constantscached_cmethodsinitialised_constantsset_global_staterO  )ra   r<  r  r	  r
  rf   rf   rg   rh     s(   

zGlobalState.__init__c                 C   s  | j }t| jD ]\}}|  }| j|< |dkr |d|  qtjs)| jd= n| jd }|  |d | jd }|  |d |d |	  |
td | jd	 }|  |d |d
 | jd }|  |d |d tjs| jd= n| jd }|  |d |d | jd }|d |d | jd }| jjr|d |d |d d S )Nr   z/* #### Code section: %s ### */r  z=static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) {r  r   z>static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {__Pyx_InitCachedConstantsr3  z6static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {r  z8static CYTHON_SMALL_CODE int __Pyx_InitConstants(void) {r4  z:static CYTHON_SMALL_CODE void __Pyx_CleanupGlobals(void) {r   z)/* --- Runtime support code (head) --- */r2  z
#line 1 "cython_utility"
z"/* --- Runtime support code --- */)rO  r   code_layoutinsertion_pointr  ru   r	   cache_builtinsenter_cfunc_scopeput_declare_refcount_contextput_setup_refcount_contextr
   r  r:  r	  emit_linenumsrx   )ra   rO  ipartwrv   rf   rf   rg   initialize_main_c_code  sN   





















z"GlobalState.initialize_main_c_codec                 C   s$   | j }| jD ]	}| | j|< qd S ro   )rO  h_code_layoutr  r  )ra   rO  r  rf   rf   rg   initialize_main_h_code  s   
z"GlobalState.initialize_main_h_codec                 C   s   |    | jd }tdd}|||j |d | jd }tdd}|||j |d | jd }td	d}|||j |d d S )
Nr2  TypeConversionszTypeConversion.cr   r  UtilityCodePragmasModuleSetupCode.cr  UtilityCodePragmasEnd)	close_global_declsr  r   r   r7  r   r   ru   r   )ra   rv   r   rf   rf   rg   finalize_main_c_code  s   




z GlobalState.finalize_main_c_codec                 C   s
   | j | S ro   )r  )ra   rl   rf   rf   rg   __getitem__  rN  zGlobalState.__getitem__c                 C   sL  |    tjr+| jd }|d ||jr"||j |d |d |  | jd }|	  |d ||jrN||j |	  |d |d |  dD ]&}| j| }|d ||jrv||j |d |d |  qYtj
r| jd }|d |  tj
r| jd }|d |  d S d S )	Nr  z	return 0;z
return -1;}r  )r3  r  r4  r  )generate_const_declarationsr	   r  r  ru   r  rV  	put_labelexit_cfunc_scopeput_finish_refcount_contextr:  )ra   r   r  rf   rf   rg   r(    sF   
















zGlobalState.close_global_declsc                 C   s   | d  d|j  d S )Nr  zstatic PyObject *%s;)ru   r  ra   entryrf   rf   rg   put_pyobject_decl;     zGlobalState.put_pyobject_declc                 C   s,   |d ur|| j v rd S | j | | jd S )Nr  )r  r   r  ra   targetrf   rf   rg   get_cached_constants_writer@  s
   

z'GlobalState.get_cached_constants_writerFc                 C   sB   |rdpd}z
| j ||f }W |S  ty    | ||}Y |S w )Nlongintr  r   new_num_const)ra   	str_valuelongnessr  crf   rf   rg   get_int_constH  s   zGlobalState.get_int_constc                 C   s8   z
| j |df }W |S  ty   | |d|}Y |S w )Nfloatr9  )ra   r;  r  r=  rf   rf   rg   get_float_constP  s   zGlobalState.get_float_constr   c                 C   st   |d ur| j |}|d ur|S | ||}|d ur/|tjkr/|jr/| jd }|d|j  |d ur8|| j |< |S )Nr4  zPy_CLEAR(%s);)	r  rr   new_py_constr	   r:  r  r  ru   r  )ra   rZ   r  cleanup_level	dedup_keyconstcleanup_writerrf   rf   rg   get_py_constW  s   


zGlobalState.get_py_constc                 C   sT   |j r| }n| }z| j| }W n ty"   | ||}Y nw || |S ro   )r  
utf8encode
byteencoder  r   new_string_constr  )ra   r  
py_versionr  r=  rf   rf   rg   get_string_consti  s   

zGlobalState.get_string_constc                 C   sB   |j sJ z| j| }W |S  ty    |   }| j|< Y |S w ro   )r  r  r   new_const_cname)ra   r  r=  rf   rf   rg   get_pyunicode_ptr_constv  s   
z#GlobalState.get_pyunicode_ptr_constc                 C   s^   d }|r|d ur|  | kr| j|dd}| j|dd}n| |}||j|||}|S )Nr  )rJ  r   )rG  rH  rK  r  r   )ra   r  r  r  unicode_valuer  c_stringr  rf   rf   rg   r    s   

zGlobalState.get_py_string_constc                 C      | j |ddS NTr  r  ra   r  rf   rf   rg   get_interned_identifier  r  z#GlobalState.get_interned_identifierc                 C   s$   |  |}t|||}|| j|< |S ro   )new_string_const_cnamer  r  )ra   r  r  r  r=  rf   rf   rg   rI    s   

zGlobalState.new_string_constc                 C   s,   |  ||}t||||}|| j||f< |S ro   )new_num_const_cnamer  r  )ra   r   r  r  r  r=  rf   rf   rg   r:    s   zGlobalState.new_num_constc                 C   s$   |  |}t||}| j| |S ro   )rL  r  r  r   )ra   rZ   r  r  r=  rf   rf   rg   rA       

zGlobalState.new_py_constc                 C   s   | dd}| j|dS )Nr  ignore)r   )decoderL  )ra   bytes_valuer   rf   rf   rg   rU    s   z"GlobalState.new_string_const_cnamec                 C   sV   | j }|jddd }}||v r%|| d  }||< |jd|d}||v sd||< |S )Nr   )seprX   r   rD   )r  r\   )ra   
format_strr  r  r   rX   rf   rf   rg   unique_const_cname  s   zGlobalState.unique_const_cnamec                 C   s   |dkr
|d7 }d}t j| }|dddddd}t|d	kr:| |d
 |d d  d |dd   }|S d||f }|S )Nr7  Lr8  .rD   +-neg_*   zlarge{counter}_   _xxx_i%s%s)r   r  r-  r   r]  )ra   r   r  r  r  rf   rf   rg   rV    s   
"zGlobalState.new_num_const_cnamec                 C   sH   t d|d d d}| |d }|rtj| }ntj}d||f S )NrD       z{sep}{counter}rf  )r  r   r]  r   r  r  )ra   r  r   name_suffixrf   rf   rg   rL    s   zGlobalState.new_const_cnamec              	   C   sL   ||f}z| j | }W |S  ty%   | dd||f  }| j |< Y |S w )Numethodz%s_%s)r  r   rL  )ra   r"  r#  rl   r  rf   rf   rg   get_cached_unbound_method  s   z%GlobalState.get_cached_unbound_methodc                 C   sH   dt | }| t|d | ||}|g| }d||d|f S )NzCallUnboundCMethod%dObjectHandling.cz__Pyx_%s(&%s, %s)ro  )r   r5  r   r   rj  r   )ra   r$  r"  r#  
arg_cnamesr   cache_cnamer%  rf   rf   rg   r!    s   
z+GlobalState.cached_unbound_method_call_codec                 C   s   |j rS|jrU| |j|rW| | | jd }d }|jtv r=t|j \}}|d|  | 	|j
t||j |d | 	|j
t|j|j |rY|d d S d S d S d S d S )Nr  #if %s#else#endif)
is_builtinis_constshould_declarer  r2  r  r   non_portable_builtins_mapru   put_cached_builtin_initposr
   r  )ra   r1  r   	conditionreplacementrf   rf   rg   add_cached_builtin_decl  s,   



z#GlobalState.add_cached_builtin_declc              	   C   sH   | j d }| |j}| tdd |d|||||f  d S )Nr  GetBuiltinNamerk  z*%s = __Pyx_GetBuiltinName(%s); if (!%s) %s)r  rT  r  r5  r   r   ru   
error_goto)ra   rv  r   r  r   interned_cnamerf   rf   rg   ru    s   

z#GlobalState.put_cached_builtin_initc                 C   s$   |    |   |   |   d S ro   )generate_cached_methods_declsgenerate_string_constantsgenerate_num_constantsgenerate_object_constant_declsrp   rf   rf   rg   r,    s   z'GlobalState.generate_const_declarationsc                 C   s   dd | j D }|  |D ]G\}}}| jd d|j|  | jd d|tj|f  |jjs4q| jd j	d| |jd	d
d |jj
rK|d7 }| jd d|  qd S )Nc                 S      g | ]}t |j|j|fqS rf   r   r  r   r=  rf   rf   rg   r     s    z>GlobalState.generate_object_constant_decls.<locals>.<listcomp>r  z%s;r  #define %s %s->%sr  zclear_module_state->%sTF)clear_before_decrefnannyz	->memviewr  $Py_VISIT(traverse_module_state->%s);)r  sortr  ru   rZ   declaration_coder   modulestateglobal_cnamer  put_xdecref_clearis_memoryviewslice)ra   constsrD   r  r=  rf   rf   rg   r    s.   


z*GlobalState.generate_object_constant_declsc           	      C   s   | j sd S | jd }| jd }g }t| j  D ]-\\}}}|| | t|j}|	d|  |	d||f  |	d||f  qt
jrZ| jd }|D ]}|	d|  qPd S d S )Nr  r  z2static __Pyx_CachedCFunction %s = {0, 0, 0, 0, 0};z%s.type = (PyObject*)&%s;z%s.method_name = &%s;r4  zPy_CLEAR(%s.method);)r  r  rt   r   r   rT  r
   r  r  ru   r	   r:  )	ra   declr   cnamesr"  r#  r  method_name_cnamer   rf   rf   rg   r}    s.   




z)GlobalState.generate_cached_methods_declsc                 C   s  dd | j  D }|  g }| jd }|D ]S\}}}d}|jr;d|jvs+d|jvr;d}|dd|jv r7d	p8d
  |jd|t|jf dd |rQ|d |j	d urj|j	 D ]}|
|jt|j|f q[qt| j D ]0\}}t|\}	}
|	r|d |d||
f  |	r|d |d||	f  |d qr| jd }|r| tdd |  | jd }|d |d |dtj  |D ]}|\}}}|jr|jr|jdv rd}nd|j  }| jd d|j  | jd d|jtj|jf  | jd d |j  | jd! d"|j  |jr@|d# |d$|j|jj|jjdd%d&|jf  |d |d$|j||||j|j|jf  |jr[|d q|d' |d( |d)tj  |d* |d+|| j  d S d S ),Nc                 S   r  rf   r  r  rf   rf   rg   r   6  s    z9GlobalState.generate_string_constants.<locals>.<listcomp>r  Fr   r  Tz#if PY_MAJOR_VERSION %s 3rU   z>=zstatic const char %s[] = "%s";)saferp  z#ifdef Py_UNICODE_WIDEz static Py_UNICODE %s[] = { %s };ro  r  InitStringszStringTools.cr  r   z6static int __Pyx_CreateStringTabAndInitStrings(void) {z__Pyx_StringTabEntry %s[] = {)r  USASCIIzUS-ASCIIUTF8r   0z"%s"r  PyObject *%s;r  r  r  !Py_CLEAR(clear_module_state->%s);r  r  z#if PY_MAJOR_VERSION >= 3z&{&%s, %s, sizeof(%s), %s, %d, %d, %d},r   r   z{0, 0, 0, 0, 0, 0, 0}z};zreturn __Pyx_InitStrings(%s);r+  z2if (__Pyx_CreateStringTabAndInitStrings() < 0) %s;)r  r   r  r  r  ru   r
   split_string_literalr  r  r   r  r   rt   r  r   encode_pyunicode_stringr5  r   r   r   stringtab_cnamer  r   r  r  r  r  r  r{  r8  )ra   c_constsr  decls_writerrD   r  r=  conditionalr  utf16_arrayutf32_arrayr  r   py_string_argsc_cnamer   rf   rf   rg   r~  5  s   













	




z%GlobalState.generate_string_constantsc           
   
   C   s  dd | j  D }|  | jd }|D ]l\}}}}}}|j}| jd d|  | jd d|tj|f  | jd d	|  | jd
 d|  |dkrSd}	n|dkrZd}	nt	|rbd}	nt
|ddkrnd}	nd}	|d||	| ||| jf  qd S )Nc                 S   s2   g | ]}|j |jd  dkt|j|j|j|fqS )r   ra  )r  r   r   r  r  rf   rf   rg   r     s    *z6GlobalState.generate_num_constants.<locals>.<listcomp>r  r  r  r  r  r  r  r  r  r?  zPyFloat_FromDouble(%s)r7  z%PyLong_FromString((char *)"%s", 0, 0)z$PyInt_FromString((char *)"%s", 0, 0)ra     zPyInt_FromLong(%sL)zPyInt_FromLong(%s)z%s = %s; %s)r  r   r  r  r  ru   r   r  r   long_literalr   lstriperror_goto_if_nullr8  )
ra   r  r  r  rD   r   r  r=  r  functionrf   rf   rg   r    s>   




z"GlobalState.generate_num_constantsc                 C   sN   || j v r | j | }t|jt|jksJ |j|jksJ dS || j |< dS )NFT)r  r   rZ   r   )ra   r  r1  rm   rf   rf   rg   rs    s   


zGlobalState.should_declarec                 C   sN   |  }z| j| }W |S  ty&   t| j}| j| || j|< Y |S w ro   )get_filenametable_entryr  r   r   r  r   )ra   source_descr1  indexrf   rf   rg   lookup_filename  s   
zGlobalState.lookup_filenamec              	   C   s   z| j | W S  ty   Y nw |jddd}zdd |D }W t|dr)|  nt|dr4|  w w |s<|d || j |< |S )Nr  rX  )r   error_handlingc                 S   s(   g | ]}d |  dddd qS )z * z*/z.*[inserted by cython to avoid comment closer]/z/*z-/[inserted by cython to avoid comment start]*)r   r-  r+  rf   rf   rg   r     s    
z7GlobalState.commented_file_contents.<locals>.<listcomp>closer   )r  r   	get_lineshasattrr  r   )ra   r  source_fileFrf   rf   rg   commented_file_contents  s*   



z#GlobalState.commented_file_contentsc                 C   s0   |r|| j vr| j | ||  dS dS dS )a  
        Adds code to the C file. utility_code should
        a) implement __eq__/__hash__ for the purpose of knowing whether the same
           code has already been included
        b) implement put_code, which takes a globalstate instance

        See UtilityCode.
        N)r  r   r?  )ra   utility_coderf   rf   rg   r5    s   	zGlobalState.use_utility_codec                 C   s8   |d u rd S |j r| |j  |jr| |j d S d S ro   )r  r5  utility_code_definitionr0  rf   rf   rg   use_entry_utility_code  s   z"GlobalState.use_entry_utility_codero   Fr   NNr  r  )r   r   )*ry   rz   r{   r  r  r"  rh   r!  r#  r)  r*  r(  r2  r6  r>  r@  rF  rK  rM  r  rT  rI  r:  rA  rU  r]  rV  rL  rj  r!  ry  ru  r,  r  r}  r~  r  rs  r  r  r5  r  rf   rf   rf   rg   r  Z  sT    $
1*



	


	
		Z!
r  c                    s2   | j t  fdd}fdd}t||S )Nc                    s
    | j S ro   )	funcstaterp   )attribute_ofrf   rg   rr     rN  z!funccontext_property.<locals>.getc                    s   t | j | d S ro   )setattrr  )ra   r   rA  rf   rg   r        z!funccontext_property.<locals>.set)ry   r   
attrgetterproperty)funcrr   r   rf   )r  r   rg   funccontext_property  s
   

r  c                   @   s   e Zd ZdddZdS )CCodeConfigTc                 C   s   || _ || _|| _d S ro   )emit_code_commentsr  c_line_in_traceback)ra   r  r  r  rf   rf   rg   rh     s   
zCCodeConfig.__init__N)TTT)ry   rz   r{   rh   rf   rf   rf   rg   r    s    r  c                   @   s  e Zd ZdZejd ddddZdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zedd Zedd Zedd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zdd,d-Zd	d.d/Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Z d:d; Z!d<d= Z"d>d? Z#d@dA Z$dBdC Z%d	dDdEZ&dFdG Z'dHdI Z(dJdK Z)d
dMdNZ*dOdP Z+dQdR Z,		ddSdTZ-dUdV Z.dWdX Z/dYdZ Z0d	d[d\Z1dd]d^Z2dd_d`Z3dadb Z4dcdd Z5dedf Z6dgdh Z7didj Z8dkdl Z9dmdn Z:dodp Z;dqdr Z<dsdt Z=dudv Z>dwdx Z?dydz Z@	L	+dd{d|ZAd}d~ ZBdd ZCdd ZDdd ZEeFfddZGdd ZHdd ZIdd ZJdd ZKdd ZLdd ZMdddZNdddZOdddZPdddZQdddZRdddZSdd ZTdd ZUdd ZVdd ZWdd ZXdd ZYdd ZZdd Z[dd Z\dd Z]dd Z^dd Z_dd Z`dd Zadd Zbdd ZcdddZdddÄ Zeddń ZfdddǄZgdddʄZhddd̄Zidd΄ ZjddЄ Zkddd҄Zld	ddԄZmdddքZnddd؄Zoddڄ Zpdd܄ ZqdddބZrdddZsdddZtdd Zudd Zvdd Zwdd Zxdd Zydd ZzdddZ{dddZ|dddZ}dddZ~dd Zd	ddZdddZdd Zddd Zdd Zdd Zdd ZdS (  CCodeWritera  
    Utility class to output C code.

    When creating an insertion point one must care about the state that is
    kept:
    - formatting state (level, bol) is cloned and used in insertion points
      as well
    - labels, temps, exc_vars: One must construct a scope in which these can
      exist by calling enter_cfunc_scope/exit_cfunc_scope (these are for
      sanity checking and forward compatibility). Created insertion points
      looses this scope and cannot access it.
    - marker: Not copied to insertion point
    - filename_table, filename_list, input_file_contents: All codewriters
      coming from the same root share the same instances simultaneously.
    create_fromNFc                 C   s   |d u rt  }|| _d | _d | _g | _d | _d | _d | _d| _d| _	d| _
|d urK| |j |j| _|rA|j| _|j
| _
|j	| _	|j| _|j| _d S d S )Nr   r   )r   bufferlast_poslast_marked_pospyclass_stackr  rP  r	  level
call_levelbolr  )ra   r  r  copy_formattingrf   rf   rg   rh   +  s*   zCCodeWriter.__init__c                 C   s   t |||}|S ro   r  )ra   r  r  r  r  rf   rf   rg   
create_newF  s   zCCodeWriter.create_newc                 C   s    | j d u sJ || _ |j| _d S ro   )rP  r	  )ra   global_staterf   rf   rg   r  L  s   zCCodeWriter.set_global_statec                 C   r  ro   )r  copyto)ra   r   rf   rf   rg   r  Q  r   zCCodeWriter.copytoc                 C   r  ro   )r  getvaluerp   rf   rf   rg   r  T  rN  zCCodeWriter.getvaluec                 C   s$   d|v r|  | d S | | d S )Nr   )_write_lines_write_to_bufferra   r  rf   rf   rg   rx   W  s   zCCodeWriter.writec                 C   s@   | j r
| j d d nd}| jj|g|d  | | d S )Nr   Nr   r   )r  r  markersextendcountr  )ra   r  filename_linerf   rf   rg   r  ]  s   zCCodeWriter._write_linesc                 C   r  ro   )r  rx   r  rf   rf   rg   r  f  r   zCCodeWriter._write_to_bufferc                 C   s   | j | | j dd}|S )NT)r  r  r  )r  r  r  r  rf   rf   rg   r  i  s   zCCodeWriter.insertion_pointc                 C   s
   t | dS )z
        Creates a new CCodeWriter connected to the same global state, which
        can later be inserted using insert.
        r  r  rp   rf   rf   rg   
new_writerm  s   
zCCodeWriter.new_writerc                 C   s"   |j | j u sJ | j|j dS )z
        Inserts the contents of another code writer (created with
        the same global state) in the current location.

        It is ok to write to the inserted writer also after insertion.
        N)rP  r  insert)ra   r<  rf   rf   rg   r  t  s   zCCodeWriter.insertc                 C   r   ro   rf   rp   rf   rf   rg   rW    r   zCCodeWriter.label_counterc                 C   r   ro   rf   rp   rf   rf   rg   rZ    r   zCCodeWriter.return_labelc                 C   r   ro   rf   rp   rf   rf   rg   rV    r   zCCodeWriter.error_labelc                 C   r   ro   rf   rp   rf   rf   rg   rX    r   zCCodeWriter.labels_usedc                 C   r   ro   rf   rp   rf   rf   rg   r\    r   zCCodeWriter.continue_labelc                 C   r   ro   rf   rp   rf   rf   rg   r]    r   zCCodeWriter.break_labelc                 C   r   ro   rf   rp   rf   rf   rg   return_from_error_cleanup_label  r   z+CCodeWriter.return_from_error_cleanup_labelc                 C   r   ro   rf   rp   rf   rf   rg   r^    r   zCCodeWriter.yield_labelsTc                 c   sl    t ||D ]-\}}| |sq|r| | d}|dur$| j||d | | ||fV  | | qdS )a  
        Helper for generating multiple label interceptor code blocks.

        @param new_labels: the new labels that should be intercepted
        @param orig_labels: the original labels that we should dispatch to after the interception
        @param skip_to_label: a label to skip to before starting the code blocks
        @param pos: the node position to mark for each interceptor block
        @param trace: add a trace line for the pos marker or not
        N)trace)r  r  put_gotomark_posr-  )ra   r  orig_labelsskip_to_labelrv  r  ry  
orig_labelrf   rf   rg   label_interceptor  s   




zCCodeWriter.label_interceptorc                 C      | j |S ro   )r  rY  ra   r   rf   rf   rg   rY        zCCodeWriter.new_labelc                 G      | j j| S ro   )r  r[  ra   r%  rf   rf   rg   r[    r  zCCodeWriter.new_error_labelc                 G   r  ro   )r  r}  r  rf   rf   rg   r}    r  zCCodeWriter.new_yield_labelc                 C   r  ro   )r  r  rp   rf   rf   rg   r    r   zCCodeWriter.get_loop_labelsc                 C   r  ro   )r  r  r  rf   rf   rg   r    r  zCCodeWriter.set_loop_labelsc                 G   r  ro   )r  r  r  rf   rf   rg   r    r  zCCodeWriter.new_loop_labelsc                 C   r  ro   )r  r  rp   rf   rf   rg   r    r   zCCodeWriter.get_all_labelsc                 C   r  ro   )r  r  r  rf   rf   rg   r    r  zCCodeWriter.set_all_labelsc                 C   r  ro   )r  r  rp   rf   rf   rg   r    r   zCCodeWriter.all_new_labelsc                 C   r  ro   )r  r  r  rf   rf   rg   r    r  zCCodeWriter.use_labelc                 C   r  ro   )r  r  r  rf   rf   rg   r    r  zCCodeWriter.label_usedc                 C   s   t | |d| _d S )N)rU  )rR  r  r  rf   rf   rg   r    r  zCCodeWriter.enter_cfunc_scopec                 C   s   | j   d | _ d S ro   )r  ru  rp   rf   rf   rg   r.    s   

zCCodeWriter.exit_cfunc_scopec                 C      | j ||jS ro   )rP  r>  r  )ra   r;  r<  rf   rf   rg   
get_py_int  r   zCCodeWriter.get_py_intc                 C   r  ro   )rP  r@  r  )ra   r;  r  rf   rf   rg   get_py_float  r   zCCodeWriter.get_py_floatr   c                 C      | j ||||jS ro   rP  rF  r  )ra   rZ   r  rB  rC  rf   rf   rg   rF    r   zCCodeWriter.get_py_constc                 C      | j |jS ro   )rP  rK  r  rS  rf   rf   rg   rK    r  zCCodeWriter.get_string_constc                 C   r  ro   )rP  rM  rS  rf   rf   rg   rM    r  z#CCodeWriter.get_pyunicode_ptr_constc                 C   r  ro   )rP  r  r  )ra   r  r  r  rN  rf   rf   rg   r    s
   zCCodeWriter.get_py_string_constc                 C   r  ro   r  )ra   rZ   rf   rf   rg   get_argument_default_const  r  z&CCodeWriter.get_argument_default_constc                 C   s
   |  |S ro   rR  rS  rf   rf   rg   r    rN  zCCodeWriter.internc                 C   rP  rQ  rR  rS  rf   rf   rg   intern_identifier  r  zCCodeWriter.intern_identifierc                 C   r  ro   )rP  r6  r4  rf   rf   rg   r6    r  z'CCodeWriter.get_cached_constants_writerc                 C   sv   | j r
| jr
|   | jjr"| jr"| j\}}}| d|| f  |r1|r,| | n| 	| | d d| _d S )Nz
#line %s "%s"
r   r   )
r  r  emit_markerr	  r  r  r  get_escaped_descriptionput_safer7  )ra   rv   r  r  r   rD   rf   rf   rg   ru     s   


zCCodeWriter.putlnc                 C   s>   |d u rd S | j r| j d d |d d krd S ||f| _d S )Nr   )r  r  ra   rv  r  rf   rf   rg   r    s
    zCCodeWriter.mark_posc                 C   s   | j \}}|| _d | _ | d | jjr"|   | d| |  |rI| jrK| jjrM| j	j
d rO|   | d|d | jj | |f  d S d S d S d S d S )Nr   z	/* %s */
	linetracez__Pyx_TraceLine(%d,%d,%s)
r   )r  r  r  r	  r  indent_build_markerr  rb  rP  r  rc  r{  r  rf   rf   rg   r    s   

zCCodeWriter.emit_markerc                 C   sv   |\}}}t |tsJ | j|}|td|d | }|d  d7  < ||||d  7 }d| |d|f S )Nr   r  rV   z             # <<<<<<<<<<<<<<r   z"%s":%d
%s
r   )r   r   rP  r  maxr  r   )ra   rv  r  r   colcontentsr   rf   rf   rg   r    s   
zCCodeWriter._build_markerc                 C   s   |  | d| _d S r  )rx   r  ra   rv   rf   rf   rg   r    s   

zCCodeWriter.put_safec                 C   s   | j j}|rUt|dkrUd|t|d f }tj	||}tj
|sQd|t f }tt|}|| W d    n1 sFw   Y  t|| d| }| | d S )Ni   z%s_%s.hr  z%s.tmp%sz#include "%s"
)rP  r
  r   hashlibsha1encode	hexdigestr   r~   r   existsgetpidr   r   open_new_filerx   shutilmover7  )ra   rv   r   include_dirinclude_filer~   tmp_pathr   rf   rf   rg   r6    s   zCCodeWriter.put_or_includec                 C   s   d}d|v r| d}nd}d|v r8|| d8 }|dk r%|  j|7  _n|dkr8|d dkr8d}|  jd8  _| jr?|   | | d| _|dkrT|  j|7  _d S |r_|  jd7  _d S d S )NF{r   r+  Tr   )r  r  r  r  rx   )ra   rv   
fix_indentdlrf   rf   rg   r7    s(   
zCCodeWriter.putc                 C      |  j d7  _ d S Nr   r  rp   rf   rf   rg   increase_indent6  r  zCCodeWriter.increase_indentc                 C      |  j d8  _ d S r  r  rp   rf   rf   rg   decrease_indent9  r  zCCodeWriter.decrease_indentc                 C   s   |  d |   d S )Nr  )ru   r  rp   rf   rf   rg   begin_block<  s   
zCCodeWriter.begin_blockc                 C   s   |    | d d S )Nr+  )r  ru   rp   rf   rf   rg   	end_block@  s   zCCodeWriter.end_blockc                 C   s   |  d| j  d S )Nz  )r  r  rp   rf   rf   rg   r  D  r   zCCodeWriter.indentc                 C   s   dt |d d d  S )Nz0x%02X%02X%02X%02X)r   r   r   r   r  )r  )ra   	pyversionrf   rf   rg   get_py_version_hexG  r3  zCCodeWriter.get_py_version_hexc                 C   s"   || j jv r| d|  d S d S )Nz%s:;)r  rX  ru   r  rf   rf   rg   r-  J  s   zCCodeWriter.put_labelc                 C   s   | j | | d|  d S )Ngoto %s;)r  r  ru   r  rf   rf   rg   r  N  s   zCCodeWriter.put_gotoc                 C   s   |j dkr|s|jsd S |j dkr|jsd S |js| d |r'| d|  |jr7| |jj|j|d n| |jj	|j|d |j
d urU| d|j|j
  n	|jjr^| d | d | jj| d S )NprivateCYTHON_UNUSED %s )dll_linkagez = %sz = NULL;)
visibilitydefined_in_pxdr  cf_usedr7  is_cpp_optionalrZ   cpp_optional_declaration_coder  r  r   r  literal_codeis_pyobjectru   r  rU  r  )ra   r1  storage_classr  
definitionrf   rf   rg   put_var_declarationR  s*   






zCCodeWriter.put_var_declarationc                 C   s   |j D ]F\}}}}|jr|js|jjd r||}n||}|jr+| d|  q|j	r<| d||
|jf  q| d|rCdpDd|f  q|jrv| jjrTd}nd}| d|tjf  | d	|tjf  | d|tjf  d S d S )
Nr  z
%s = NULL;z%s = %s;z%s%s;zstatic r   r  z%sint %s = 0;z%sconst char *%s = NULL;)rd  r  r  rU  r  r  r  r!  ru   r  r   default_valuerk  r  rl  r   lineno_cnamefilename_cnameclineno_cname)ra   func_contextr   rZ   r  r  r  unusedrf   rf   rg   put_temp_declarationsl  s"   
z!CCodeWriter.put_temp_declarationsc                 C   s   |  tj |  d d S )Nr   )ru   r   GENERATED_BY_MARKERrp   rf   rf   rg   put_generated_by  rQ  zCCodeWriter.put_generated_byc                 C   s    |  d|  |  d|  d S )Nz
#ifndef %sz
#define %sru   )ra   guardrf   rf   rg   put_h_guard  s   zCCodeWriter.put_h_guardc                 C   s   t jrd| S |S )Nzunlikely(%s))r	   gcc_branch_hintsra   condrf   rf   rg   unlikely  s   zCCodeWriter.unlikelyc                    s$   |sdS dd  fdd|D  S )Nr   r   c                    s   g | ]} ||qS rf   rf   )r   r   mapperrf   rg   r     r	  z8CCodeWriter.build_function_modifiers.<locals>.<listcomp>)r   )ra   	modifiersr7  rf   r6  rg   build_function_modifiers  s   z$CCodeWriter.build_function_modifiersc                 C   s.   |j }|js|j  r|j jrd|j S |jS )Nz(PyObject *))rZ   is_self_argis_completeis_extension_typer  )ra   r1  rZ   rf   rf   rg   entry_as_pyobject  s   
zCCodeWriter.entry_as_pyobjectc                 C   s   ddl m}m} ||||S )Nr   py_object_typetypecast)r  r?  r@  )ra   r  rZ   r?  r@  rf   rf   rg   as_pyobject  s   zCCodeWriter.as_pyobjectc                 C      | | | d S ro   )generate_gotrefr  rf   rf   rg   
put_gotref  r   zCCodeWriter.put_gotrefc                 C   rB  ro   )generate_giverefr  rf   rf   rg   put_giveref  r   zCCodeWriter.put_giverefc                 C   rB  ro   )generate_xgiverefr  rf   rf   rg   put_xgiveref  r   zCCodeWriter.put_xgiverefc                 C   rB  ro   )generate_xgotrefr  rf   rf   rg   put_xgotref  r   zCCodeWriter.put_xgotrefc                 C      |j | ||d d S N)r  )generate_increfra   r  rZ   r  rf   rf   rg   
put_incref  s   zCCodeWriter.put_increfc                 C   rK  rL  )generate_xincrefrN  rf   rf   rg   put_xincref  r   zCCodeWriter.put_xincrefc                 C      |j | |||d d S N)r  have_gil)generate_decrefra   r  rZ   r  rT  rf   rf   rg   
put_decref     zCCodeWriter.put_decrefc                 C   rR  rS  )generate_xdecrefrV  rf   rf   rg   put_xdecref  rX  zCCodeWriter.put_xdecrefc                 C      |j | ||||d d S N)r  r  rT  )generate_decref_clearra   r  rZ   r  r  rT  rf   rf   rg   put_decref_clear     

zCCodeWriter.put_decref_clearc                 C   r[  r\  )generate_xdecref_clearr^  rf   rf   rg   r    r`  zCCodeWriter.put_xdecref_clearc                 C      | | || d S ro   )generate_decref_setra   r  rZ   	rhs_cnamerf   rf   rg   put_decref_set  r  zCCodeWriter.put_decref_setc                 C   rb  ro   )generate_xdecref_setrd  rf   rf   rg   put_xdecref_set  r  zCCodeWriter.put_xdecref_setc                 C   rK  N)rT  )generate_incref_memoryviewslice)ra   slice_cnamerZ   rT  rf   rf   rg   put_incref_memoryviewslice  s   z&CCodeWriter.put_incref_memoryviewslicec                 C   s   | j |j|j|d d S ri  )rl  r  rZ   )ra   r1  rT  rf   rf   rg   put_var_incref_memoryviewslice  r3  z*CCodeWriter.put_var_incref_memoryviewslicec                 C      |  |j|j d S ro   )rD  r  rZ   r0  rf   rf   rg   put_var_gotref  r   zCCodeWriter.put_var_gotrefc                 C   rn  ro   )rF  r  rZ   r0  rf   rf   rg   put_var_giveref  r   zCCodeWriter.put_var_giverefc                 C   rn  ro   )rJ  r  rZ   r0  rf   rf   rg   put_var_xgotref  r   zCCodeWriter.put_var_xgotrefc                 C   rn  ro   )rH  r  rZ   r0  rf   rf   rg   put_var_xgiveref  r   zCCodeWriter.put_var_xgiverefc                 K      | j |j|jfi | d S ro   )rO  r  rZ   ra   r1  kwdsrf   rf   rg   put_var_incref     zCCodeWriter.put_var_increfc                 K   rs  ro   )rQ  r  rZ   rt  rf   rf   rg   put_var_xincref  rw  zCCodeWriter.put_var_xincrefc                 K   rs  ro   )rW  r  rZ   rt  rf   rf   rg   put_var_decref  rw  zCCodeWriter.put_var_decrefc                 K   rs  ro   )rZ  r  rZ   rt  rf   rf   rg   put_var_xdecref  rw  zCCodeWriter.put_var_xdecrefc                 K   "   | j |j|jfd|ji| d S Nr  )r_  r  rZ   
in_closurert  rf   rf   rg   put_var_decref_clear     "z CCodeWriter.put_var_decref_clearc                 K      | j |j|j|fi | d S ro   )rf  r  rZ   ra   r1  re  ru  rf   rf   rg   put_var_decref_set     zCCodeWriter.put_var_decref_setc                 K   r  ro   )rh  r  rZ   r  rf   rf   rg   put_var_xdecref_set  r  zCCodeWriter.put_var_xdecref_setc                 K   r{  r|  )r  r  rZ   r}  rt  rf   rf   rg   put_var_xdecref_clear  r  z!CCodeWriter.put_var_xdecref_clearr   c                 C   s4   |D ]}|r	|j r|jr| | q| | qd S ro   )r  xdecref_cleanuprz  ry  )ra   entries	used_onlyr1  rf   rf   rg   put_var_decrefs  s   

zCCodeWriter.put_var_decrefsc                 C      |D ]}|  | qd S ro   )rz  ra   r  r1  rf   rf   rg   put_var_xdecrefs 	     zCCodeWriter.put_var_xdecrefsc                 C   r  ro   )r  r  rf   rf   rg   put_var_xdecrefs_clear	  r  z"CCodeWriter.put_var_xdecrefs_clearc                 C   sL   ddl m}m} |||d}|r| d||f  d S | d||f  d S )Nr   r>  Py_Nonez%s = %s; __Pyx_INCREF(Py_None);z%s = %s; Py_INCREF(Py_None);)r  r?  r@  ru   )ra   r  rZ   r  r?  r@  py_nonerf   rf   rg   put_init_to_py_none	  s
   zCCodeWriter.put_init_to_py_none%sc                 C   s2   ||j  }| ||j| |jr| d d S d S )Nr  )r  r  rZ   r}  rF  )ra   r1  rD  r  rv   rf   rf   rg   put_init_var_to_py_none	  s
   
z#CCodeWriter.put_init_var_to_py_nonec                 C   s2  d}|j s
|jdkr-ddlm} d}|jtvr-||js-|jdkr)| jjd s)n|r-d S |j	 }|s6d S |j r?||j
g7 }|rF||n|j}|j }	|	dkrXd	|	|f }|j }
|ru|| jj|j}| }|ru| | | d
|
|d||jr|jnd|f  |r|r| d d S d S d S )NF__getattribute__r   )	TypeSlotsT__getattr__fast_getattrPyCFunctionz(void*)(%s)%sz{%s, (PyCFunction)%s, %s, %s}%s|r  rp  )
is_specialr   r   r  special_py_methodsis_reverse_number_slotrP  r  	signaturemethod_flagsmethod_coexistput_pymethoddef_wrapper
func_cnamemethod_function_typeas_c_string_literalget_slot_tableget_slot_by_method_namepreprocessor_guard_coderu   r   doc	doc_cname)ra   r1  term
allow_skipwrapper_code_writerr  r  r  func_ptrcast
entry_nameslotpreproc_guardrf   rf   rg   put_pymethoddef	  sH   



zCCodeWriter.put_pymethoddefc                 C   s   |j }|jrK|j pg }ddlm} ||v rKtj| }| d|  d|j  }|j	dkr?| d|  | d | d n| d	|  | d
 |S )Nr   )method_noargszBstatic PyObject *%s(PyObject *self, CYTHON_UNUSED PyObject *arg) {z%s(self)rH   zPyObject *res = %s;zFif (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); }zreturn res;z
return %s;r+  )
r  r  r  r  r  r  r   method_wrapper_prefixru   r   )ra   r1  r  r  r  	func_callrf   rf   rg   r  C	  s   




z#CCodeWriter.put_pymethoddef_wrapperc                 C   s<   | j jd r| j tdd d S | j tdd d S )Nfast_gilFastGilr&  	NoFastGil)rP  r  r5  r   r   rp   rf   rf   rg   use_fast_gil_utility_codeY	  s   z%CCodeWriter.use_fast_gil_utility_codec                 C   sX   | j tdd |   | d |sd}|r| d | d|  | d dS )	a  
        Acquire the GIL. The generated code is safe even when no PyThreadState
        has been allocated for this thread (for threads not initialized by
        using the Python API). Additionally, the code generated by this method
        may be called recursively.
        ForceInitThreadsr&  #ifdef WITH_THREAD__pyx_gilstate_savezPyGILState_STATE z%s = __Pyx_PyGILState_Ensure();rp  N)rP  r5  r   r   r  ru   r7  )ra   declare_gilstatevariablerf   rf   rg   put_ensure_gil_	  s   


zCCodeWriter.put_ensure_gilc                 C   s6   |    |sd}| d | d|  | d dS )zD
        Releases the GIL, corresponds to `put_ensure_gil`.
        r  r  z__Pyx_PyGILState_Release(%s);rp  Nr  ru   )ra   r  rf   rf   rg   put_release_ensured_gilq	  s   
z#CCodeWriter.put_release_ensured_gilc                 C   sb   |    | d | d |r| d|  |r| d | d |r*| d | d dS )	z
        Acquire the GIL. The thread's thread state must have been initialized
        by a previous `put_release_gil`
        r  z__Pyx_FastGIL_Forget();z_save = %s;zif (_save) {Py_BLOCK_THREADSr+  rp  Nr  ra   r  unknown_gil_staterf   rf   rg   put_acquire_gil|	  s   




zCCodeWriter.put_acquire_gilc                 C   sv   |    | d | d | d |r| d | d |r&| d |r/| d|  | d | d	 d
S )z2Release the GIL, corresponds to `put_acquire_gil`.r  zPyThreadState *_save;z_save = NULL;zif (PyGILState_Check()) {Py_UNBLOCK_THREADSr+  z%s = _save;z__Pyx_FastGIL_Remember();rp  Nr  r  rf   rf   rg   put_release_gil	  s   






zCCodeWriter.put_release_gilc                 C   s"   |  d |  d |  d d S )Nr  z%PyGILState_STATE __pyx_gilstate_save;rp  r.  rp   rf   rf   rg   r  	     

zCCodeWriter.declare_gilstatec                 C   s   |  d|| |f S )Nzif (%s < 0) %s)ru   r{  )ra   rv  r   rf   rf   rg   put_error_if_neg	  s   zCCodeWriter.put_error_if_negc              	   C   s   |j rd}| jtdd nN|jjr#|r#d}| jtdd n;|jjr7|jr7d}| jtdd n'|jjrR|j	rR|j
sR|jjrRd}| jtd	d nd
}| jtdd |sg|j|j}| d|||j| |f  d S )N__Pyx_RaiseClosureNameErrorRaiseClosureNameErrorrk  &__Pyx_RaiseUnboundMemoryviewSliceNogil RaiseUnboundMemoryviewSliceNogil__Pyx_RaiseCppGlobalNameErrorRaiseCppGlobalNameError__Pyx_RaiseCppAttributeErrorRaiseCppAttributeError__Pyx_RaiseUnboundLocalErrorRaiseUnboundLocalErrorz#if (unlikely(!%s)) { %s("%s"); %s })from_closurerP  r5  r   r   rZ   r  r  
is_cglobalis_variable	is_memberrU  is_c_class_scopecheck_for_null_coder  ru   r   r{  )ra   rv  r1  in_nogil_contextunbound_check_coder  rf   rf   rg   put_error_if_unbound	  s@   




z CCodeWriter.put_error_if_unboundc                 C   s.   d| j _|r
d| j _d| |d |d f S )NTz__PYX_MARK_ERR_POS(%s, %s)r   r   )r  rk  rl  r  )ra   rv  r  rf   rf   rg   set_error_info	  s   zCCodeWriter.set_error_infoc                 C   sT   | j j}| j | |d u rd| S d| j _|rd| j _d| |d |d |f S )Nr  Tz__PYX_ERR(%s, %s, %s)r   r   )r  rV  r  rk  rl  r  )ra   rv  r  r  rf   rf   rg   r{  	  s   zCCodeWriter.error_gotoc                 C   s   d|  || |f S )Nz
if (%s) %s)r4  r{  )ra   r3  rv  rf   rf   rg   error_goto_if	  r3  zCCodeWriter.error_goto_ifc                 C      |  d| |S )Nz!%sr  ra   r  rv  rf   rf   rg   r  	  r   zCCodeWriter.error_goto_if_nullc                 C   r  )Nz(%s < 0)r  r  rf   rf   rg   error_goto_if_neg	  s   zCCodeWriter.error_goto_if_negc                 C   s   |  d|S )NzPyErr_Occurred()r  )ra   rv  rf   rf   rg   r9  	  r  zCCodeWriter.error_goto_if_PyErrc                 C   r  ro   )rP  r  )ra   r   rf   rf   rg   r  	  r  zCCodeWriter.lookup_filenamec                 C      |  d d S )N__Pyx_RefNannyDeclarationsr.  rp   rf   rf   rg   r  	  r  z(CCodeWriter.put_declare_refcount_contextc                 C   s>   |  }|r| jtdd | d||rdpdf  d S )Nr  r&  z#__Pyx_RefNannySetupContext(%s, %d);r   r   )r  rP  r5  r   r   ru   )ra   r   acquire_gilrf   rf   rg   r  	  s   
z&CCodeWriter.put_setup_refcount_contextc                 C   s   |  |r	d d S d d S )Nz"__Pyx_RefNannyFinishContextNogil()z__Pyx_RefNannyFinishContext();r.  )ra   nogilrf   rf   rg   r/  	  rw  z'CCodeWriter.put_finish_refcount_contextc                 C   s<   |  }||r
tjndtjtjf}d| j_| d|  dS )z
        Build a Python traceback for propagating exceptions.

        qualified_name should be the qualified name of the function.
        r   Tz#__Pyx_AddTraceback(%s, %s, %s, %s);N)r  r   r(  r&  r'  r  rl  ru   )ra   qualified_nameinclude_clineformat_tuplerf   rf   rg   put_add_traceback	  s   zCCodeWriter.put_add_tracebackc                 C   sL   |t jt jt j| jjd |f}d| j_| d|  | j	t
dd dS )z
        Generate code to print a Python warning for an unraisable exception.

        qualified_name should be the qualified name of the function.
        unraisable_tracebacksTz0__Pyx_WriteUnraisable("%s", %s, %s, %s, %d, %d);WriteUnraisableExceptionzExceptions.cN)r   r(  r&  r'  rP  r  r  rl  ru   r5  r   r   )ra   r  r  r  rf   rf   rg   put_unraisable
  s   

zCCodeWriter.put_unraisablec                 C   r  )N__Pyx_TraceDeclarationsr.  rp   rf   rf   rg   put_trace_declarations!
  r  z"CCodeWriter.put_trace_declarationsc                 C   s   |r|  d|  d S d S )Nz__Pyx_TraceFrameInit(%s)r.  )ra   codeobjrf   rf   rg   put_trace_frame_init$
  s   z CCodeWriter.put_trace_frame_initc                 C   s4   |  d|tj| |d |d || |f  d S )Nz*__Pyx_TraceCall("%s", %s[%s], %s, %d, %s);r   r   )ru   r   filetable_cnamer  r{  )ra   r   rv  r  rf   rf   rg   put_trace_call(
  s   "zCCodeWriter.put_trace_callc                 C   r  )Nz__Pyx_TraceException();r.  rp   rf   rf   rg   put_trace_exception,
  r  zCCodeWriter.put_trace_exceptionc                 C   s   |  d||f  d S )Nz__Pyx_TraceReturn(%s, %d);r.  )ra   retvalue_cnamer  rf   rf   rg   put_trace_return/
  rX  zCCodeWriter.put_trace_returnc                 C   s"   |  d |  | |  d d S )Nz#ifdef _OPENMPz#endif /* _OPENMP */r.  )ra   stringrf   rf   rg   putln_openmp2
  r  zCCodeWriter.putln_openmpc                 C   sD   |  d|  |  d |  d |  d |  d |  d dS )zl
        Redefine the macros likely() and unlikely to no-ops, depending on
        condition 'cond'
        rn      #undef likely    #undef unlikelyz    #define likely(x)   (x)z    #define unlikely(x) (x)rp  Nr.  r2  rf   rf   rg   undef_builtin_expect7
  s   



z CCodeWriter.undef_builtin_expectc                 C   sD   |  d|  |  d |  d |  d |  d |  d d S )Nrn  r  r  z2    #define likely(x)   __builtin_expect(!!(x), 1)z2    #define unlikely(x) __builtin_expect(!!(x), 0)rp  r.  r2  rf   rf   rg   redef_builtin_expectC
  s   



z CCodeWriter.redef_builtin_expect)NNF)NNTro   r  r  )r   F)T)r   NT)TT)FTTr  )r  T)TNNT)FNr  )ry   rz   r{   r|   cythonlocalsrh   r  r  r  r  rx   r  r  r  r  r  r  rW  rZ  rV  rX  r\  r]  r  r^  r  rY  r[  r}  r  r  r  r  r  r  r  r  r  r.  r  r  rF  rK  rM  r  r  r  r  r6  ru   r  r  r  r  r6  r7  r  r  r  r  r  r  r-  r  r$  r+  r-  r0  r4  modifier_output_mapperr9  r=  rA  rD  rF  rH  rJ  rO  rQ  rW  rZ  r_  r  rf  rh  rl  rm  ro  rp  rq  rr  rv  rx  ry  rz  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r{  r  r  r  r9  r  r  r  r/  r  r  r  r  r  r  r  r  r  r  rf   rf   rf   rg   r    s   
	







	+ r  c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
PyrexCodeWriterc                 C   s   t || _d| _d S r  )r   r  r   r  )ra   outfile_namerf   rf   rg   rh   P
  s   
zPyrexCodeWriter.__init__c                 C   s   | j dd| j |f  d S )N%s%s
r5  )r   rx   r  r  rf   rf   rg   ru   T
  r  zPyrexCodeWriter.putlnc                 C   r  r  r  rp   rf   rf   rg   r  W
  r  zPyrexCodeWriter.indentc                 C   r  r  r  rp   rf   rf   rg   dedentZ
  r  zPyrexCodeWriter.dedentN)ry   rz   r{   rh   ru   r  r  rf   rf   rf   rg   r   L
  s
    r   c                   @   s~   e Zd ZdZdddZddd	Zdd
dZedd Zdd Z	dd Z
d ddZdd Zd ddZdd Zdd Zdd ZdS )!PyxCodeWriterz7
    Can be used for writing out some Cython code.
    Nr   rB   c                 C   s(   |pt  | _|| _|| _|| _|| _d S ro   )r   r  r  original_levelr  r   )ra   r  indent_levelr  r   rf   rf   rg   rh   c
  s
   
zPyxCodeWriter.__init__r   c                 C   s   |  j |7  _ dS r  r  ra   levelsrf   rf   rg   r  j
  s   zPyxCodeWriter.indentc                 C   s   |  j |8  _ d S ro   r  r  rf   rf   rg   r  n
  r  zPyxCodeWriter.dedentc                 c   s&    |  | |   dV  |   dS )zf
        with pyx_code.indenter("for i in range(10):"):
            pyx_code.putln("print i")
        N)ru   r  r  ra   r   rf   rf   rg   indenterq
  s
   
zPyxCodeWriter.indenterc                 C   r  ro   )r  emptyrp   rf   rf   rg   r  |
  rN  zPyxCodeWriter.emptyc                 C   s$   | j  }t|tr|| j}|S ro   )r  r  r   r   rY  r   )ra   r  rf   rf   rg   r  
  rW  zPyxCodeWriter.getvaluec                 C   s&   |p| j }|rt||}| | d S ro   )r  rE  _putln)ra   r   r  rf   rf   rg   ru   
  s   

zPyxCodeWriter.putlnc                 C   s   | j d| jd |f  d S )Nr  z    )r  rx   r  r	  rf   rf   rg   r  
  r  zPyxCodeWriter._putlnc                 C   s>   |p| j }|rt||}t|}| D ]}| | qd S ro   )r  rE  r   r  r.  r  )ra   chunkr  r   rf   rf   rg   	put_chunk
  s   


zPyxCodeWriter.put_chunkc                 C   s   t | | j | j| jS ro   )rZ   r  r  r  r  rp   rf   rf   rg   r  
  s   zPyxCodeWriter.insertion_pointc                 C   s   | j   | j| _d S ro   )r  resetr  r  rp   rf   rf   rg   r  
  s   
zPyxCodeWriter.resetc                 C   s   t | ||   d S ro   )r  r  r  rf   rf   rg   named_insertion_point
  r   z#PyxCodeWriter.named_insertion_point)Nr   NrB   )r   ro   )ry   rz   r{   r|   rh   r  r  r   r
  r  r  ru   r  r  r  r  r  rf   rf   rf   rg   r  ^
  s    






	r  c                   @   s$   e Zd Zdd Zdd Zdd ZdS )r  c                 C   s   || _ i | _i | _d| _d S r  )klassrd  re  temps_count)ra   r  rf   rf   rg   rh   
  s   
zClosureTempAllocator.__init__c                 C   s&   | j  D ]\}}t|| j|< qd S ro   )rd  r   r   re  )ra   rZ   r  rf   rf   rg   r  
  s   zClosureTempAllocator.resetc                 C   s   || j vrg | j |< g | j|< n| j| r| j| dS dtj| jf }| jjd |||dd | j | | |  jd7  _|S )Nr   rv  T)rv  r   r  rZ   is_cdefr   )	rd  re  r  r   r  r  r  declare_varr   )ra   rZ   r  rf   rf   rg   r  
  s   


z"ClosureTempAllocator.allocate_tempN)ry   rz   r{   rh   r  r  rf   rf   rf   rg   r  
  s    r  rf   )J
__future__r   r  declareobjectr  r   r   r   r  r   r  r   	functoolsr   
contextlibr   r   collectionsr   r   r   r	   r   r
   r   Scanningr   r   __builtin__r   ImportErrorbuiltinsr   rt  ctypedef_builtins_mapbasicsize_builtins_mapuncachable_builtins	frozensetr  rr   r  rT   r   r   r   r   r   rE  r   rL  rR  r  r  r   rY  Ur   r  r  r  r   r  findallr  r  r  r  r  r  r  r   r  r  rf   rf   rf   rg   <module>   s   "/L

 d =  O     "
      FF