o
    j6                    @   s  d dl Z e jdi 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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mZ d dlmZ ddlmZ ddlmZ ddlmZ ddlmZ d d!lmZ dd"lmZ d d#lmZ d d$lmZ  zd d$l!mZ" W n e#y   dZ"Y nw ee"d%d&Z"zd d'l$mZ%m&Z'm(Z) W n e#y   dZ%Y nw ee%e'j*e)j+e'j,e'j,- d id(Z%['[)dd)ee d%d*fd d+e"fd,d-e%fgZ.d.d.d/d0d1Z/d2d2d3d4d5Z0d6d7iZ1d8Z2e3g d9Z4g d:Z5e e3e3d;Z6d<d=ij7Z8e edd d d>j7Z9G d?d@ d@Z:dAdB Z;dZ<	 dCdD Z=e=Z<G dEdF dFZ>G dGdH dHe>Z?e
G dIdJ dJZ@G dKdL dLe?ZAddMdgdNdOdPZBeBdQdRdSdTdU ZCeB dVeAfdWdXZDeBdYdZd[d\d]d^ ZEeBd_d`dZdad\dbdc ZFeBdddedSdfdg ZGeBdhdMdid\djdk ZHeB dldm ZIddi fdndoZJG dpdq dqeAZKG drds dse?ZLG dtdu duZMG dvdw dwZNG dxdy dyZOe jeeeedz ePd{ejQjRZSePd|jRZTePd}jUZVePd~jWZXG dd dZYG dd dZZG dd dZ[dd Z\G dd dZ]G dd dZ^G dd dZ_G dd dZ`e jae jbdecde jddecfddZee fde jgdecde jdfddZhG dd dZidS )    NosreoperatortextwrapTemplateNamingOptionsStringEncodingUtilsSourceDescriptorStringIOTree
DebugFlagsdefaultdictclosingpartialwrapszlib_compressbz2_compressZlzma_compresszstd_compress)	dataclassr   )r   r   )r   contextmanager)r      )r   )r   )r   )r	      )r
   )r   )r   )compress	   )compresslevel)r   CompressionParameterStrategy)optionszliblevelbz2   zstdstrrangeinput)unicode
basestringxrange	raw_inputz&PyLong_Typez&PyFloat_Typez&PyWrapperDescr_Type)Zpy_intZpy_longZpy_floatZwrapper_descriptorZPyTypeObjectZPyHeapTypeObject)r$      r   betar   )ArithmeticErrorAssertionErrorAttributeErrorBaseExceptionBaseExceptionGroupBlockingIOErrorBrokenPipeErrorBufferErrorBytesWarningChildProcessErrorConnectionAbortedErrorConnectionErrorConnectionRefusedErrorConnectionResetErrorDeprecationWarningEOFErrorEllipsisEncodingWarningEnvironmentError	ExceptionExceptionGroupFalseFileExistsErrorFileNotFoundErrorFloatingPointErrorFutureWarningGeneratorExitIOErrorImportErrorImportWarningIndentationError
IndexErrorInterruptedErrorIsADirectoryErrorKeyErrorKeyboardInterruptLookupErrorMemoryErrorModuleNotFoundError	NameErrorNoneNotADirectoryErrorNotImplementedNotImplementedErrorOSErrorOverflowErrorPendingDeprecationWarningPermissionErrorProcessLookupErrorPythonFinalizationErrorRecursionErrorReferenceErrorResourceWarningRuntimeErrorRuntimeWarningStopAsyncIterationStopIterationSyntaxErrorSyntaxWarningSystemError
SystemExitTabErrorTimeoutErrorTrue	TypeErrorUnboundLocalErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeErrorUnicodeTranslateErrorUnicodeWarningUserWarning
ValueErrorWarningWindowsErrorZeroDivisionError_IncompleteInputError__build_class__	__debug__
__import__absaiterallanextanyasciibinbool
breakpoint	bytearraybytescallablechrclassmethodcompilecomplex	copyrightcreditsdelattrdictdirdivmod	enumerateevalexecexitfilterfloatformat	frozensetgetattrglobalshasattrhashhelphexidr(   int
isinstance
issubclassiterlenlicenselistlocalsmapmax
memoryviewminnextobjectoctopenordpowprintpropertyquitr'   reprreversedroundsetsetattrslicesortedstaticmethodr&   sumsupertupletypevarszip)
r{   r`   r3   rC   r   r   r@   r   ry   _)	Z	__cinit__Z__dealloc__Z__richcmp____next__	__await__	__aiter__	__anext__Z__getbuffer__Z__releasebuffer__inlineZCYTHON_INLINE)Zustringr   r   c                   @   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 {}Fz#include "{}")	counterorderr   piecesr   INITIALlocationLATEEARLY)selfincludeZverbatimZlateinitial r   U/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/Cython/Compiler/Code.py__init__A  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)r   r   r   update)r   dkeyotherr   r   r   dict_updateW  s
   zIncludeCode.dict_updatec                 C   s   | j S N)r   r   r   r   r   sortkeyc  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   getr   r   r   r   	mainpiecef  s   zIncludeCode.mainpiecec                 C   s$   t | jD ]
}|| j|  qd S r   )r   r   putln)r   codekr   r   r   writem  s   zIncludeCode.write)NNTF)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r   r   r   r   '  s    
r   c                  C   s*   t jt jt jt} t j| dS )NZUtility)r   pathdirnameabspath__file__join)Z
Cython_dirr   r   r   get_utility_dirs  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
   Zopen_source_file	readlines)r   filenamefr   r   r   read_utilities_from_utility_dir  s   $r   c                   @   s,   e Zd ZdZddddZdd Zd	d
 ZdS )AbstractUtilityCodeNglobalstateGlobalStatereturnc                 C      d S r   r   )r   r   used_byr   r   r   put_code     zAbstractUtilityCode.put_codec                 K   r   r   r   r   kwargsr   r   r   get_tree  r  zAbstractUtilityCode.get_treec                 K   r   r   r   r  r   r   r   get_shared_library_scope  r  z,AbstractUtilityCode.get_shared_library_scoper   r   r   r   N)r   r   r   requiresr  r  r  r   r   r   r   r     s
    r   c                   @   s   e Zd ZdZdZi ZedjZ	e
dd ZedddZed	d
 Zedd Zei fddZedddZedjfddZ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.
    Fzo(.+)[.](proto(?:[.]\S+)?|impl|init|cleanup|module_state_decls|module_state_traverse|module_state_clear|export)$c                 C   s   t ddt | i t jjS )NzS^%(C)s{5,30}  \s*  (?P<name> (?:\w|\.)+ )  \s*  %(C)s{5,30} |^%(C)s+  @(?P<tag> .+)C)r   r   escapeVERBOSEmatch)Zline_comment_charr   r   r   get_special_comment_matcher  s   z+UtilityCodeBase.get_special_comment_matcherNc                 C   s(  |d u rd S d |}|rWd|v rWd|d v rWzt|tt}W n ttfyA }	 ztd| d| d|dd|	 d }	~	ww ||krUtd	| d| d
|dd|}d| | }|dkrf||d< n|dkro||d< n|d }
||
|< |r|d }
| D ]\}}|
	|t
 | qd S d S )N

substitutenamingz&Error parsing templated utility code '.z
' at line r   z: zFFound useless 'substitute: naming' declaration without replacements. (:)protor   implr   r   )r   r   r  r   r   rQ   rw   rd   items
setdefaultr   r   )clsutilitynamer   linesbegin_linenotagsr   Znew_codeeZall_tagstag_nameZ
tag_valuesr   r   r   _add_utility  s<   


zUtilityCodeBase._add_utilityc              	   C   s:  | j |}|r
|S tj|\}}|dv r%d}ttdjd}t	j
}nd}ttdjd}ttdjd}| |}| j}	t|}
td	d
 }g }tt}d  } }}d}t|
D ]\}}||}|d u rs|||| q]|dr| |||||| |d }|d d = |  |d}|	|}|r| \}}nd}|| }q]|d}d|vrtd| d| d| |d\}}}|
 }| }|dvrtd| d| d| td|std| d| d| || | |d q]|d u rtd| |||||| t|}|| j |< |S )N)z.pyxz.pyz.pxdz.pxi#z^\s*#(?!\s*cython\s*:).* /z^\s*//.*|/\*[^*]*\*/z	\s+(\\?)$z\1c                   S   s
   d d i gS r   r   r   r   r   r   <lambda>     
 z:UtilityCodeBase.load_utilities_from_file.<locals>.<lambda>r   r  r   r  tagr  zFound invalid tag 'z' in utility section r  )r	  r  proto_blockzFound unknown tag name 'z\S+$zFound invalid tag value 'zEmpty utility code file)_utility_cacher   r   r   splitextr   r   r   subr&   rstripr  match_section_titleread_utilities_hookr   r   r   appendgroupr"  cleargroupsrd   	partitionstripr  addrw   r   )r  r   	utilitiesr   extcommentZstrip_commentsr-  Zmatch_specialZ
match_type	all_linesr  r  r  r  r   r  linenolinemmtypeZ	tag_valuer!  r   r   r   load_utilities_from_file  sh   







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  Ztempitar	  c                    s    g | ]} j |fi qS r   )load.0depr  	from_fileZorig_kwargsr   r   
<listcomp>V  s    z(UtilityCodeBase.load.<locals>.<listcomp>c                    s   g | ]}  |qS r   )load_cachedrA  )r  rE  r   r   rF  Z  s    r  Nr   r  r  r  filer   )
rsplitr?  r   TempitaUtilityCoder@  copyr  r   r   r   )
r  util_code_namerE  r  r7  r  r  r  r  valuesr   rD  r   r@  >  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.
        )rQ   r@  )r  utility_code_namerE  Z_UtilityCodeBase__cacher   r   r   r   r   rG  t  s   

zUtilityCodeBase.load_cachedc                    sf   | j ||fi |}|s||j||jfS g g   fdd| dd fS )a  
        Load a utility code as a string. Returns (proto, implementation).

        If 'include_requires=True', concatenates all requirements before the actually
        requested utility code, separately for proto and impl part.

        In a lot of cases it may be better to use regular "load" and "CCodeWriter.put_code_here"
        since that is able to apply the code transformations to the code too.
        c                    sR   | j r| j D ]}| q| jr| | j | jr' | | j d S d S r   )r	  r  r0  format_coder  )Z	util_coderC  Zimplsprependprotosr   r   rQ    s   

z/UtilityCodeBase.load_as_string.<locals>.prependr$  )r@  rO  r  r  r   )r  rL  rE  Zinclude_requiresr  utilr   rP  r   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

r5  )r   code_stringZreplace_empty_linesr   r   r   rO    s   zUtilityCodeBase.format_codec                 C   s   dt | j| jf S )Nz<%s(%s)>)r   r   r  r   r   r   r   __repr__     zUtilityCodeBase.__repr__c                 K   r   r   r   r  r   r   r   r    r  zUtilityCodeBase.get_treec                 K   r   r   r   r  r   r   r   r    r  z(UtilityCodeBase.get_shared_library_scopec                 C   s   | S r   r   )r   Zmemodictr   r   r   __deepcopy__  s   zUtilityCodeBase.__deepcopy__r   F)r   r   r   r   Zis_cython_utilityr*  r   r   r  r.  r   r  r   r"  r?  r@  rG  rT  r,  rO  rW  r  r  rY  r   r   r   r   r
    s4    %
 
G
5r
  c                   @   s*   e Zd ZU dZeed< eed< eed< dS )SharedFunctionDeclz6Contains parsed declaration of shared utility functionr  retparamsN)r   r   r   r   r&   __annotations__r   r   r   r   r[    s
   
 r[  c                   @   s   e Zd ZdZg dZ				d$ddZdedefd	d
Zdd Z	dd Z
dd Zd%ddZdd Zejd%dddddefddZdd Zd&dd Zd%d'd"d#ZdS )(UtilityCodea  
    Stores utility code to add during code generation.

    See GlobalState.put_utility_code.

    hashes/equals by instance

    proto           C prototypes
    export          C prototypes exported from the shared utility code module
    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)
    shared_utility_functions        List of parsed declaration line of the shared utility function
    )r  exportr  initcleanupmodule_state_declsmodule_state_traversemodule_state_clearNutility_code_protoc                    s   | _ | _| _| _| _| _| _| _i  _g  _	|	 _
|
 _| _| _|r1 |ng  _|r:   t fdd jD  _d S )Nc                 3   s    | ]	}t  |d V  qd S r   r   )rB  partr   r   r   	<genexpr>  s    z'UtilityCode.__init__.<locals>.<genexpr>)r  r  ra  rb  rc  rd  re  r	  _cachespecialize_listr)  r  rH  r`  parse_export_functionsshared_utility_functions_validate_suitable_for_sharingr   
code_parts_parts_tuple)r   r  r  ra  rb  rc  rd  re  r	  r)  r  rH  r`  r   r   r   r     s$   zUtilityCode.__init__export_protor   c           	      C   s   d|vrd|vrd|vsJ d|   d| j g }d}|dD ]F}|  dd	}td
d|}t|dkr:q"t||tj}|d usQJ d|d| j |	 \}}}|
t|  |  |  d q"|S )Nz///**/z(Export block must not contain comments:
z

 in file a_  
            ^static\s                                         # `static` keyword
            (?P<ret_type>[^;()]+[\s*])                        # return type + modifier with optional * - e.g.: int *, float, const str *, ...
            (?P<func_name>\w+)\((?P<func_params>[^)]*)\)$     # function with params - e.g. foo(int, float, *PyObject)
        z;
r  r$  z\s+ r   z5Wrong format of function definition in export block 
z
 in )r  r\  r]  )r5  rH  splitreplacer   r,  r   r  r  r3  r0  r[  )	r   rq  Zparsed_protosZproto_regexr  ZmatchedZret_type	func_nameZfunc_paramsr   r   r   rl    s&   
z"UtilityCode.parse_export_functionsc                 C   s
   t | jS r   )r   rp  r   r   r   r   __hash__	     
zUtilityCode.__hash__c                 C   sJ   | |u rdS t | t |}}||urt||st| |sdS | j|jkS )NTF)r   r   rp  )r   r   Z	self_typeZ
other_typer   r   r   __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.
        Nr   r   scontextr   r   r   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y   | jd u r8d }n
 fdd| jD }t	| 
| j | 
| j | 
| j | 
| j | 
| j | 
| j | 
| j || j|
 }| j|< | j| | Y S w )Nr   	type_namez%s[%s]c                    s   g | ]}|  qS r   )
specialize)rB  rdatar   r   rF  +      z*UtilityCode.specialize.<locals>.<listcomp>)r  Zempty_declaration_codeZspecialization_namer   r   r  rj  rQ   r	  r_  r  r  r  ra  rb  rc  rd  re  r)  rk  r0  )r   Z
pyrex_typer  r  r   r	  r}  r   r  r   r    s6   
zUtilityCode.specializec                 C   s,   t | d}|s	d S d|vsJ d|  d S )Nr  zNAMED_CGLOBAL(moddict_cname)z$moddict_cname should not be shared: rg  )r   rV  r   r   r   rn  =  s
   

z*UtilityCode._validate_suitable_for_sharingwriterCCodeWriteroutputr   	code_typec           	      C   s   t | |}|s	d S |dv }t| ||\}}|rd| dnd}|dkr+| j d| n| j}|d| | d |rK|sK||| j d	|  d S || d S )
N)r  r  z
 (used by r  r$  r  r  /*  */r   )r   process_utility_ccoder  r   put_or_includeput_multilines)	r   r  r  r  r  rV  Zcan_be_reusedresult_is_module_specificr  r   r   r   _put_code_sectionC  s   
zUtilityCode._put_code_sectionc                 C   sB   | j sd S |d }| ||d |d||j  |  d S )Ninit_globalsra    )ra  r  r   error_goto_if_PyErr
module_pos)r   r  r  r   r   r   _put_init_code_sectionX  s   z"UtilityCode._put_init_code_sectionr   c              
   C   sP   | d| j d | jD ]}| d|j d|j d|j d q|   d S )Nr  r  static z(*z)(z); /*proto*/)r   r  rm  r\  r]  )r   r   Zsharedr   r   r   !_put_shared_function_declarationsb  s   
&z-UtilityCode._put_shared_function_declarationsr   c                 C   s2  t | jo	|jjjj}| jr|s| jD ]
}|j|| jd q|r(| 	|| j
  |j| j | jr>| j|| j
 |d|d |sJ| || j
 |d | jrZ|sZ| j|d |d|d | jritjri| |d |d | jru| |d |d	 | jr| |d
 |d | jr| |d |d | jr| | d S d S )Nr  r  r`  utility_code_defr  cleanup_globalsrb  module_state_contentsrc  module_state_traverse_contentsrd  module_state_clear_contentsre  )r   rm  module_nodescoper~  Zshared_utility_qualified_namer	  use_utility_coder  r  r)  extendr  r  r  rb  r   generate_cleanup_coderc  rd  re  ra  r  )r   r   r  Zhas_shared_utility_code
dependencyr   r   r   r  i  s4   


zUtilityCode.put_code)NNNNNNNNrf  NNNr   )r   r  r   Nr  )r   r   r   r   ro  r   r&   r   rl  rx  rz  r  r  rn  cythonfinalr  r  r  r  r   r   r   r   r_    s&    
	
 

r_  F)regexis_module_specific_last_macro_processorc                    s     d  fdd}|S )z8Decorator to chain the code macro processors below.
    r   c                    s2   t  dtdtf fdd}|d< |S )Nutility_coderV  c                    s   d}d ur| ||\}}rD ]}||v r nq||fS d u r* | ||}n
t t ||}D ]}||v rHtd| d| j dq6|O }||fS )NFzLeft-over utility code macro 'z()' found in '')r   r,  r   rd   r  )r  r  rV  r  macro)funcr  last_processormacro_namesr  r   r   process  s$   z=add_macro_processor.<locals>.build_processor.<locals>.processr   )r   r_  r&   )r  r  r  r  r  r  r  )r  r   build_processor  s    z,add_macro_processor.<locals>.build_processorr   )r  r  r  r  r  r   r  r   add_macro_processor  s   !r  ZCSTRINGz)CSTRING\(\s*"""([^"]*(?:"[^"]+)*)"""\s*\))r  c                 C   s*   | ddd}ddd | D S )zUReplace CSTRING('''xyz''') by a C compatible string, taking care of line breaks.
    r   "z\042r$  c                 s   sD    | ]}| d r| drd| dn	d|dd  dV  qdS )\z\\r  z\n"
Nr   "
)endswithrB  r<  r   r   r   ri    s
    2
z!_wrap_c_string.<locals>.<genexpr>)r1  rv  r   
splitlines)r   matchobjcontentr   r   r   _wrap_c_string  s   
r  r  c                 C   s
   |  |S r   )rO  )r  r   r  r   r   r   _format_impl_code  s   
r  ZCALL_UNBOUND_METHODTzLCALL_UNBOUND_METHOD\(([a-zA-Z_]+),\s*"([^"]+)",\s*([^),\s]+)((?:,[^),]+)*)\))r  r  c                 C   sx   |  \}}}}d| }|rdd |dd dD ng }t|dk s/J dt|d	d
| tj d||||S )zRReplace 'UNBOUND_METHOD(type, "name")' by a constant Python identifier cname.
    z&%sc                 S   s   g | ]}|  qS r   rU  )rB  argr   r   r   rF        z*_inject_unbound_method.<locals>.<listcomp>r   N,r$   z'CALL_UNBOUND_METHOD() does not support r   z call arguments->)r3  ru  r   cached_unbound_method_call_coder   modulestateglobal_cname)r  r  
type_cnamemethod_name	obj_cnameargsr   r   r   _inject_unbound_method  s   $"
r  ZPYIDENTZ	PYUNICODEzPY(IDENT|UNICODE)\("([^"]+)"\)c                 C   s0   |  \}}dtj| jt||dkdjf S )zDReplace 'PYIDENT("xyz")' by a constant Python identifier cname.
    %s->%sZIDENT
identifier)r3  r   r  get_py_string_constr	   EncodedStringcname)r  r  Zstr_typer  r   r   r   _inject_string_constant  s   r  ZEMPTYzEMPTY\((bytes|unicode|tuple)\)c                 C   s$   | d}dtjttd| f S )zLReplace 'EMPTY(bytes|tuple|...)' by a constant Python identifier cname.
    r   r  Zempty_)r1  r   r  r   )r  r  r  r   r   r   !_inject_empty_collection_constant  s
   
	r  ZCGLOBALz(NAMED_)?CGLOBAL\(([^)]+)\)c                 C   s*   |  \}}|rtt|}tj d| S Nr  )r3  r   r   r  )r  r  Zis_namedr  r   r   r   _inject_cglobal  s   
r  c                 C   s   |S )z;Entry point for code processors, must be defined last.
    r   )r  r   rV  r   r   r   r    s   r  c                 C   sp   | sdS |r| d| }|r||d< z||  }W n t y2   ddlm} || |d }|| < Y nw ||S )z+Run tempita on string s with given context.Nr  Z__namer   r   r  )rQ   ZTempitar   r  )r}  r~  rH  r  Z__cachetemplater   r   r   r   sub_tempita  s   
r  c                       s:   e Zd Zd fdd	Zeddi fddZdd Z  ZS )	rJ  Nc                    sb   |d u ri }n|  }t||||}t||||}t||||}t j||f|||d| d S )N)ra  r  rH  )rK  r  r   r   )r   r  r  r  ra  rH  r~  r  	__class__r   r   r   !  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   r   r  r   rQ   r@  )r  rN  rE  r~  Z_TempitaUtilityCode__cacheZcontext_keyr   r   r   r   r   rG  -  s   
zTempitaUtilityCode.load_cachedc                 C   s   |du rdS t ||| j| jS r{  )r  rH  r  r|  r   r   r   r  9  s   zTempitaUtilityCode.none_or_sub)NNNNNN)r   r   r   r   r   rG  r  __classcell__r   r   r  r   rJ     s
    rJ  c                   @   s,   e Zd ZdZdZ dZdd Zdd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 r   )callback)r   r  r   r   r   r   J  ry  zLazyUtilityCode.__init__r   r   r   c                 C   s   |  |j}|j||d d S )Nr  )r  
rootwriterr  )r   r   r  r  r   r   r   r  M     zLazyUtilityCode.put_coder   r  )r   r   r   r   r	  r   r  r   r   r   r   r  B  s    r  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| _g | _i | _i | _t | _d| _d | _g | _d| _d| _d| _d| _d S )Nr   FT)names_takenownerr  error_labellabel_counterr   labels_used	new_labelreturn_labelnew_error_labelcontinue_labelbreak_labelyield_labelsZexc_varsZ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_indicatorZerror_without_exceptionZneeds_refnanny)r   r  r  r  r   r   r   r   _  s4   

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]r   )rB  r  ctypeZ	is_pytempr   r   r   rF    s    
z/FunctionState.validate_exit.<locals>.<listcomp>)r  temps_in_user  r  r   r   rd   )r   Z	leftoversmsgr   r   r   validate_exit  s   zFunctionState.validate_exitc                 C   s6   | j }|d | _ dtj|f }|d ur|d| 7 }|S )Nr   %s%dr   )r  r   Zlabel_prefix)r   r  nlabelr   r   r   r    s   
zFunctionState.new_labelyieldc                 C   s0   |  d| }t| jd |f}| j| |S )Nzresume_from_%sr   )r  r   r  r0  )r   Z	expr_typer  Znum_and_labelr   r   r   new_yield_label  s   zFunctionState.new_yield_labelr$  c                 C   s   | j }| |d | _ |S )Nerror)r  r  )r   prefixZold_err_lblr   r   r   r    s   zFunctionState.new_error_labelc                 C   s   | j | jfS r   r  r  r   r   r   r   get_loop_labels  s   zFunctionState.get_loop_labelsc                 C   s   |\| _ | _d S r   r  r   labelsr   r   r   set_loop_labels  s   zFunctionState.set_loop_labelsc                 C   s.   |   }| | |d | |d f |S )Ncontinuebreak)r   r  r  )r   r  
old_labelsr   r   r   new_loop_labels  s   zFunctionState.new_loop_labelsc                 C   s   | j | j| j| jfS r   r  r  r  r  r   r   r   r   get_all_labels  s
   zFunctionState.get_all_labelsc                 C   s   |\| _ | _| _| _d S r   r  r  r   r   r   set_all_labels  s
   zFunctionState.set_all_labelsc                 C   sR   |   }g }t|g dD ]\}}|r|| | q|| q| | |S )N)r  r  r   r  )r	  r   r0  r  r
  )r   r  
new_labelsZ	old_labelr  r   r   r   all_new_labels  s   
zFunctionState.all_new_labelsc                 C      | j | d S r   )r  r6  r   lblr   r   r   	use_label     zFunctionState.use_labelc                 C   s
   || j v S r   )r  r  r   r   r   
label_used  ry  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_localsZOptionalLocalsCppSupport.cppFNr   Tr  z/* %s allocated (%s)%s */r$  	 - zombier   )"Zis_cv_qualifiedZis_referenceZcv_base_typeis_fake_referenceZref_base_typeZis_cfunctionr$  r  Z
c_ptr_typeis_cpp_classr  
directivesr  r_  rG  needs_refcountingr  r   popremover  r   codewriter_temp_prefixr  r  r0  r  r6  r  r   debug_temp_code_commentsr  r   r  )r   r   
manage_refstaticZreusabler  freelistresultr   r   r   allocate_temp  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$  )r  r  r   r   rd   r  r0  r6  r   r  r  r   )r   r  r   r   r"  r   r   r   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   )r  r  r   r0  r  )r   usedr  r   r   r!  r"  r   r   r   r  (  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 r   )r  )rB  r  r   r   r   r   r   rF  8  s    z9FunctionState.temps_holding_reference.<locals>.<listcomp>)r  r   r   r   r   temps_holding_reference3  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 r   r   )rB  r  r   r   r!  r   r   r   rF  ?  s    
z3FunctionState.all_managed_temps.<locals>.<listcomp>)r  r   r   r   r   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   r   )rB  r   r   r"  r  r   r   r   rF  I  s    z8FunctionState.all_free_managed_temps.<locals>.<listcomp>)r   r  r  r   r   r   r   all_free_managed_tempsC  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)r  r0  r   r   r   r   r   start_collecting_tempsO  s   z$FunctionState.start_collecting_tempsc                 C   
   | j  S r   )r  r  r   r   r   r   stop_collecting_tempsU  ry  z#FunctionState.stop_collecting_tempsc                 C   s   t || _d S r   )ClosureTempAllocatorr  r   r  r   r   r   init_closure_tempsX     z FunctionState.init_closure_tempsr   )r  )r$  )FT)r   r   r   r   r   r  r  r  r  r   r  r  r	  r
  r  r  r  r$  r%  r  r'  r(  r*  r+  r-  r0  r   r   r   r   r  R  s.    +




:	r  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 r   )r  valuepy_type
value_code)r   r  r3  r4  r5  r   r   r   r   e  s   zNumConst.__init__r   r   r   r   r   r   r   r   r   r   r2  \  s    r2  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 r   )r  r   r   r  r   r   r   r   r   r  s   
zPyObjectConst.__init__Nr6  r   r   r   r   r7  l  s    r7  )possible_unicode_identifierpossible_bytes_identifierreplace_identifierfind_alphanumsz(?![0-9])\w+$s   (?![0-9])\w+$z[^a-zA-Z0-9_]+z([a-zA-Z0-9]+)c                   @   s"   e Zd Z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 | _d| _d S NF)r  textr	   escape_byte_stringescaped_value
py_stringsc_used)r   r  r?  byte_stringr   r   r   r     s
   
zStringConst.__init__Nc           
      C   s*  | j }|s	|d u rd  }}d}nd}| }|dv rd }d }ndt|}|r+d}n|d u rBt|tr;tt|}n	tt|}nd}|||f}| j	d u rRi | _	nz| j	| W S  t
ya   Y nw |ritjd ntj |rpdnd |rxd| nd d| jttjd   }t||||}	|	| j	|< |	S )	NTF)utf8utf-8r   Zusasciizus-asciir$  r&   ubr   )r?  lowerr   r<  r   r   r   r:  r9  rB  rQ   r   interned_prefixesZpy_const_prefixr  r   const_prefixPyStringConst)
r   r   r  r?  Zencoding_key
is_unicodeinternr   Zpystring_cname	py_stringr   r   r   r    sH   




zStringConst.get_py_string_constr   )r   r   r   r   r   r  r   r   r   r   r=  ~  s    r=  c                   @   s"   e Zd ZdZdddZdd ZdS )	rL  zDGlobal info about a Python string constant held by GlobalState.
    Fc                 C   s   || _ || _|| _|| _d S r   )r  r   rM  rN  )r   r  r   rN  rM  r   r   r   r        
zPyStringConst.__init__c                 C   s   | j |j k S r   r  r   r   r   r   r   __lt__     zPyStringConst.__lt__NFF)r   r   r   r   r   rS  r   r   r   r   rL    s    
rL  c                   @   s  e Zd Zi Zg dZg dZd^ddZdd Zdd	 Zd
d Z	dd Z
dd Zdd Zd^ddZd_ddZdd Zd^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^d*d+Zd,d- Zd.d/ Zd0d1 Zdad3d4Zd5efd6d7Zd8d9 Zd:d; Z d<d= Z!d>d? Z"d@dA Z#d`dBdCZ$dDdE Z%dFdG Z&dHdI Z'dJe(dKe(fdLdMZ)dNdO Z*dPdQ Z+e,dRdS Z-dTdU Z.dVdW Z/dXdY Z0d^dZd[Z1d\d] Z2dS )br   ))h_codefilename_tableutility_code_proto_before_typesZnumeric_typedefsZcomplex_type_declarationstype_declarationsrf  Zmodule_declarationsZtypeinfoZbefore_global_var
global_varstring_declsdeclsZlate_includesmodule_stater  Zmodule_state_endconstant_name_definesre  r  Zmodule_state_clear_endrd  r  Zmodule_state_traverse_endZmodule_codeZmodule_exttypesinitfunc_declarationsZinit_moduleZpystring_tablecached_builtinscached_constantsinit_constantsinit_codeobjectsr  r  cleanup_moduleZmain_methodutility_code_pragmasr  utility_code_pragmas_endend)rV  rX  rY  rf  rg  Nc                 C   s   i | _ g | _i | _t | _i | _d| _|| _|| _i | _	|| _
i | _i | _i | _i | _g | _i | _g | _i | _i | _t | _g | _||  || _d S r>  )rW  filename_listinput_file_contentsr   utility_codesdeclared_cnamesZin_utility_code_generationcode_configcommon_utility_include_dirpartsr  const_cnames_usedstring_const_indexdedup_const_indexpyunicode_ptr_const_indexcodeobject_constantsnum_const_indexarg_default_constantsconst_array_counterscached_cmethodsinitialised_constantsrm  set_global_stater  )r   r  r  rl  rm  r   r   r   r   &  s.   

zGlobalState.__init__c                 C   s  | j }t| jD ]\}}|  }| j|< |dkr |d|  q| jd }|dtj dtj	 d |dtj	 d | jd	 }|jd
tj dtj	 ddd |dtj	 d |
td | jd }|d | jd }|dtj dtj	 d |dtj	 d tjs| jd= n| jd }|dtj dtj	 d |dtj	 d | jd }|d |d | jd }| jjr|d |d |d d S )Nr   z/* #### Code section: %s ### */r`  zint __Pyx_InitCachedBuiltins( *r  CYTHON_UNUSED_VAR();ra  zint __Pyx_InitCachedConstants(T)refnannyZ__Pyx_InitCachedConstantsr  zint __Pyx_InitGlobals(void)rb  zint __Pyx_InitConstants(r  zvoid __Pyx_CleanupGlobals(rf  r$  z)/* --- Runtime support code (head) --- */r  z
#line 1 "cython_utility"
z"/* --- Runtime support code --- */)r  r   code_layoutinsertion_pointrn  r   start_initcfuncr   modulestatetype_cnamemodulestatevalue_cnameput_setup_refcount_contextr	   r  r   r  rl  emit_linenumsr   )r   r  irh  wr   r   r   r   initialize_main_c_codeB  sp   












z"GlobalState.initialize_main_c_codec                 C   s$   | j }| jD ]	}| | j|< qd S r   )r  h_code_layoutr  rn  )r   r  rh  r   r   r   initialize_main_h_codes  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 )
Nr  ZTypeConversionszTypeConversion.cr$  re  ZUtilityCodePragmasModuleSetupCode.crf  ZUtilityCodePragmasEnd)	close_global_declsrn  rJ  rG  putrO  r  r   r_  )r   r   rS  r   r   r   finalize_main_c_codex  s   




z GlobalState.finalize_main_c_codec                 C   
   | j | S r   )rn  )r   r   r   r   r   __getitem__  ry  zGlobalState.__getitem__c                 C   sz  |    | jd }|d ||jr||j |d |d |  | jd }dD ]}|| jv rF| |	t
j| | j| | q/|  |d ||jre||j |  |d |d |  dD ]&}| j| }|d ||jr||j |d |d |  qptjr| jd }|d |  tjr| jd	 }|d |  d S d S )
Nr`  	return 0;
return -1;}ra  )r   r   )r  rb  r  rd  )generate_const_declarationsrn  r   r  r  	put_labelexit_cfunc_scoperv  immortalize_constantsname_in_module_stater   pyrex_prefixput_finish_refcount_contextr   r  )r   r  Z
const_typerh  r   r   r   r    sT   

















zGlobalState.close_global_declsc                 C   s   | d  d|j  d S )NrZ  zstatic PyObject *%s;)r   r  r   entryr   r   r   put_pyobject_decl     zGlobalState.put_pyobject_declc                 C   s,   |d ur|| j v rd S | j | | jd S )Nra  )rx  r6  rn  r   targetr   r   r   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longr   rt  rQ   new_num_const)r   	str_valuelongnessr4  cr   r   r   get_int_const  s   zGlobalState.get_int_constc                 C   s8   z
| j |df }W |S  ty   | |d|}Y |S w )Nr   r  )r   r  r5  r  r   r   r   get_float_const  s   zGlobalState.get_float_constc                 C   s@   |d ur| j |}|d ur|S | |}|d ur|| j |< |S r   )rq  r   new_array_const_cname)r   r  	dedup_keyconstr   r   r   get_py_const  s   

zGlobalState.get_py_constc                 C   s$   |  d}t||}| j| |S Nr$  )new_const_cnamer7  ru  r0  )r   r   r  r  r   r   r   get_argument_default_const  s   

z&GlobalState.get_argument_default_constTc                 C   sT   |j r| }n| }z| j| }W n ty"   | ||}Y nw |r(d|_|S NT)rM  
utf8encode
byteencoderp  rQ   new_string_constrC  )r   r?  rC  rD  r  r   r   r   get_string_const  s   
zGlobalState.get_string_constc                 C   sB   |j sJ z| j| }W |S  ty    |   }| j|< Y |S w r   )rM  rr  rQ   r  )r   r?  r  r   r   r   get_pyunicode_ptr_const  s   
z#GlobalState.get_pyunicode_ptr_constc                 C   s    | j |dd}||j|}|S )NF)rC  )r  r  r   )r   r?  r  c_stringrO  r   r   r   r    s   zGlobalState.get_py_string_constc                 C   s,   t | j}tj d| d}| j| |S )N[])r   rs  r   codeobjtab_cnamer0  )r   nodeidxr  r   r   r   get_py_codeobj_const  s   
z GlobalState.get_py_codeobj_constc                 C      | j |ddS NTr  r  r   r?  r   r   r   get_interned_identifier  r1  z#GlobalState.get_interned_identifierc                 C   s$   |  |}t|||}|| j|< |S r   )new_string_const_cnamer=  rp  )r   r?  rD  r  r  r   r   r   r    s   

zGlobalState.new_string_constc                 C   s,   |  ||}t||||}|| j||f< |S r   )new_num_const_cnamer2  rt  )r   r3  r4  r5  r  r  r   r   r   r     s   zGlobalState.new_num_constc                 C   s   | dd}| j|dS )NASCIIignore)r3  )decoder  )r   Zbytes_valuer3  r   r   r   r  &  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$  )sepr   r   r   )ro  r   )r   
format_strr&  r  r3  r   r   r   r   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 )Nr  Lr   r  r   +-Zneg_*   zlarge{counter}_   Z_xxx_i%s%s)r   rJ  rv  r   r  )r   r3  r4  r  r  r   r   r   r  4  s   
"zGlobalState.new_num_const_cnamer$  c                 C   sH   t d|d d d}| |d }|rtj| }ntj}d||f S )Nr       z{sep}{counter}r  )r;  r5  r  r   rJ  rK  )r   r  r3  Zname_suffixr   r   r   r  C  s   zGlobalState.new_const_cnamer  c                 C   s2   | j |d}|d | j |< tj | d| dS )Nr   r   r  r  )rv  r   r   r  )r   r  countr   r   r   r  L  s   z!GlobalState.new_array_const_cnamec              	   C   sL   ||f}z| j | }W |S  ty%   | dd||f  }| j |< Y |S w )NZumethodz%s_%s)rw  rQ   r  )r   r  r  r   r  r   r   r   get_cached_unbound_methodQ  s   z%GlobalState.get_cached_unbound_methodc           	      C   sJ   dt | }| t|d | ||}|g| }d|||d|f S )NzCallUnboundCMethod%dObjectHandling.cz__Pyx_%s(&%s%s, %s)r  )r   r  r_  rG  r  r   )	r   Zmodulestate_cnamer  r  r  Z
arg_cnamesrN  Zcache_cnamer  r   r   r   r  Z  s   
z+GlobalState.cached_unbound_method_call_codec                 C   sb   |j r+|jr-| |j|r/| | |j}|tv rt| }| |jt	
||j d S d S d S d S r   )
is_builtinZis_constshould_declarer  r  r  renamed_py2_builtins_mapput_cached_builtin_initposr	   r  )r   r  r  r   r   r   add_cached_builtin_declg  s   
z#GlobalState.add_cached_builtin_declc              	   C   sN   | j d }|| |j}| tdd |d|||||f  d S )Nr`  ZGetBuiltinNamer  z*%s = __Pyx_GetBuiltinName(%s); if (!%s) %s)	rn   name_in_main_c_code_module_stater  r  r  r_  rG  r   
error_goto)r   r  r  r  r  Zcname_in_modulestater   r   r   r  r  s   


z#GlobalState.put_cached_builtin_initc                 C   s,   |    |   |   |   |   d S r   )generate_cached_methods_declsgenerate_object_constant_declsgenerate_codeobject_constantsgenerate_string_constantsgenerate_num_constantsr   r   r   r   r  ~  s
   z'GlobalState.generate_const_declarationsc                 C   sv   |dk rdnd}|rdnd}| j d }|d| d| d	| d
| d	 | j d }|d| d| d| d d S )N   r   
Py_ssize_tZPy_VISITZ__Pyx_VISIT_CONSTrd  for (z i=0; i<z	; ++i) { z(traverse_module_state->z[i]); }re  z&; ++i) { Py_CLEAR(clear_module_state->)rn  r   )r   struct_attr_cnamer  may_have_refcyclescounter_typeZ
visit_callr  r   r   r   )_generate_module_array_traverse_and_clear  s   
$
"z5GlobalState._generate_module_array_traverse_and_clearc           
      C   s>  dd | j D }|  |D ]<\}}}| jd d|j|  |jjs&q| jd jd| |jddd	 |jjr>|d
7 }| jd d| d qt	| j
 D ]J\}}tj | }| jd d| d| d | j||dd t|}|d ur|tjkr| jd }	|	d| d |	d|	| d  qRd S )Nc                 S      g | ]}t |j|j|fqS r   r   r  rB  r  r   r   r   rF    s    z>GlobalState.generate_object_constant_decls.<locals>.<listcomp>r]  z%s;re  zclear_module_state->TF)clear_before_decrefnannyz	->memviewrd  z Py_VISIT(traverse_module_state->r|  
PyObject *r  ];r  r  zfor (size_t i=0; i<z; ++i) z{ Py_CLEAR(%s); }z[i])ru  sortrn  r   r   declaration_coder  put_xdecref_clearis_memoryviewslicer   rv  r  r   r  r  cleanup_level_for_type_prefixr   r  r  r  )
r   constsr   r  r  r  r  r  Zcleanup_levelZpart_writerr   r   r   r    sD   



z*GlobalState.generate_object_constant_declsc           	      C   s   | j sd S | jd }| jd }|d |d g }t| j  D ]8\\}}}|| | t|j	}|d|  |d|
||f  ||
| d|
| d q"tjrt| jd	 }|D ]}|d
|
| d qed S d S )Nr]  r`  r$  z/* Cached unbound methods */z__Pyx_CachedCFunction %s;z%s.type = (PyObject*)%s;z.method_name = &;r  z	Py_CLEAR(z	.method);)rw  rn  r   r   r  r0  r  r	   r  r  r  r   r  )	r   declra  cnamesr  r  r  Zmethod_name_cnamerb  r   r   r   r    s6   






z)GlobalState.generate_cached_methods_declsc                 C   s  g }g }g }t dd | j D D ]H\}}}|jr'|t|j|j|jf |jrZ|j D ]*}|j	}|j
rGt|tsGt||jpDd}|j
rL|n||joS|j
|j|f q/q|  |  |  | jd }|D ]\}}	}
t|
}|jd|	 d| ddd	 qnt | j D ]0\}}	t|\}}|r|d
 |d|	|f  |r|d |d|	|f  |d qt|t| }| jd dtj d| d | jtj|dd | || d S )Nc                 S   r  r   r  r  r   r   r   rF    s    z9GlobalState.generate_string_constants.<locals>.<listcomp>r   r[  zstatic const char z[] = "";Tsafez#ifdef Py_UNICODE_WIDEz static Py_UNICODE %s[] = { %s };#else#endifr]  r  r  r  Fr  )r   rp  rM  rC  r0  r   r  rA  rB  r?  rM  r   r&   r	   r  r  r   rN  r  rn  split_string_literalr   rr  r  Zencode_pyunicode_stringr   stringtab_cnamer  generate_pystring_constants)r   Zc_constsZpy_bytes_constsZpy_unicode_constsr   r  rO  r?  Zdecls_writerr  rA  ZcliteralZutf16_arrayZutf32_arrayZpy_string_countr   r   r   r    sR   "





 z%GlobalState.generate_string_constantstext_stringsbyte_stringsc                 C   s  | j d }g }d}d}t|D ]+\}\}}	}
||
d |dkr&|r&|}|d|	 dtj d| d |d	7 }qt|}|D ]'\}}	}
||
jrO|
	 n|

  |d|	 dtj d| d |d	7 }qAttt|}d
|}| j d }|d |dt|  dddd |D  d | tdd d}ttD ]\}}}|d u rq||}t|t|d krq|dkr|d	ksJ dd}n|dkrd| d}nd| }|d|sdnd d| d | d!t| d"	 d#}tt|}|jd$| d%d#d& |d't| d(| d) ||d*| j |d+ |d, |d-|| j d. |d/ q|rN|d0t| d" tt|}|jd1| d%d#d& |d2 |d3 |rs|d/ |d4|tj d5 |d6 |dkr|d7|d8k rd9nd: d;| d< |d= |d> |dkr|d?| d@ |dA |dB ||| j |dC |dD |dE |dC |t|k r.|d7t|d8k rd9nd: dF| dGt| d< |d= |dH |dD |dE |dA |dB ||| j |dC |dC |dB |dIt| d< |dJ ||| j |dC |dC |t|k rk| dK| t|| | |dC d S )LNr^  r   r   rF  #define rt  r  r  r       rb  {z*const struct { const unsigned int length: z; } index[] = {r  c                 S   s   g | ]}d | qS )z{%d}r   )rB  lengthr   r   r   rF  1  r  z;GlobalState.generate_pystring_constants.<locals>.<listcomp>};ZDecompressStringzStringTools.cF
   r    zBCompression algorithm no. 1 must be 'zlib' to be used as fallback.z(CYTHON_COMPRESS_STRINGS) != 0r%   z(CYTHON_COMPRESS_STRINGS) == z+ && __PYX_LIMITED_VERSION_HEX >= 0x030e0000r#  ifelifz /* compression: z (z
 bytes) */Tzconst char* const cstring = "r  r  z1PyObject *data = __Pyx_DecompressString(cstring, r  r|  r  z7const char* const bytes = __Pyx_PyBytes_AsString(data);z#if !CYTHON_ASSUME_SAFE_MACROSz,if (likely(bytes)); else { Py_DECREF(data); z }r  z#else /* compression: none (zconst char* const bytes = "zPyObject *data = NULL;z*CYTHON_UNUSED_VAR(__Pyx_DecompressString);zPyObject **stringtab = r  zPy_ssize_t pos = 0;r  r  r   r   i = 0; i < ; i++) {z*Py_ssize_t bytes_length = index[i].length;zIPyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL);zif (likely(string) && i >= z#) PyUnicode_InternInPlace(&string);zif (unlikely(!string)) {zPy_XDECREF(data);r  zstringtab[i] = string;zpos += bytes_length;z i = z; i < zHPyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length);zfor (Py_ssize_t i = 0; i < z2if (unlikely(PyObject_Hash(stringtab[i]) == -1)) {zstringtab + )rn  r   r0  encoder   r   r  r   r   r  r  r   r   r   r   
bit_lengthr  r_  rG  r   compression_algorithmsr	   r  r@  error_goto_if_nullr  r  r  r  )r   r  r  definesZbytes_valuesZfirst_internedZstringtab_posr  Zis_internedr  r?  Zstringtab_bytes_startr   indexZconcat_bytesr  Zhas_ifZalgo_numberZ	algo_namer   Zcompressed_bytesguardZescaped_bytesr   r   r   r     s   
 
 





0






&








4











z'GlobalState.generate_pystring_constantsc                 C   s  | j d }dtj dtj d}| js2|| |dtj d |d |  |d d S d	}d
}d
}d
}d
}d
}| jD ]/}	|	j}
|
j	s`t
|t|
j|
j }t
||
j}t
||
j}t
|t|	j}t
||
jd
 }qA|td|  d|  d|  d|  d|  d|  d | tdd || |d |d | jD ]}	|	|d q|d |d |d |d |d |  |d t| j}| j d dtj d| d | jtj|dd d S ) Nrc  zint __Pyx_CreateCodeObjects(rz  r  r{  r|  r  r  i  r   z=        typedef struct {
            unsigned int argcount : z.;
            unsigned int num_posonly_args : z-;
            unsigned int num_kwonly_args : z%;
            unsigned int nlocals : z#;
            unsigned int flags : z(;
            unsigned int first_line : z;;
        } __Pyx_PyCode_New_function_description;
        Z
NewCodeObjr  z)PyObject* tuple_dedup_map = PyDict_New();z*if (unlikely(!tuple_dedup_map)) return -1;badzPy_DECREF(tuple_dedup_map);zbad:r  r]  r  r  r  Fr  )rn  r   r  r  rs  r  r   r  def_nodeZis_generator_expressionr   r   r  Znum_kwonly_argsZnum_posonly_argsvarnamesr  r  r   dedentr  r  r_  rG  Zgenerate_codeobjr  r  )r   r  Zinit_functionZ	max_flagsZmax_func_argsZmax_kwonly_argsZmax_posonly_argsZmax_varsZmax_liner  r  Zcode_object_countr   r   r   r    sj   
















 z)GlobalState.generate_codeobject_constantsc                     s6  dd | j  D }|  |sd S t|}| jd dtj d| d | jtj|dd g }g g}g }d	}d
}|D ]h\}}	}	}
}}|j	}|dkrS|
||f q<t|
}| }|dkr|d d dt|d > kr|
g  dd t|d  }|d d dt|d > ksn|d7 }|d 
|| | f q<|
||f q<| jd }| jd }dtdtdtfdd}dtjfdd}dtfdd}dAdtdtjfd d!}d	}|r|d" |d#|tj d$ ||d%d&| |||| ||t| ||| jd' |d( |d( |t|7 }|d	kr|d" |d#|tj d)| d$ g d*}d+}d	}t|dD ]F\}}|sFq=d,d|d >  }||||| | |||||  | d-| d.}|t|7 }||t|krx|nd/| d0| d1; }q=||| t|d2krd3nd4}||| j| d5| d6 |d( |d( ||7 }|rd7d8  |d" |d#|tj d)| d$ d9 fd:d|D d;}|d<t| d= |||| ||t| |d> ||| jd? |d@ |d( |d( | |tj|| d S )BNc                 S   s6   g | ]}|j t|jd |jd |j|j|fqS )r  )r4  r   r3  lstripr5  r  r   r   r   rF    s    .z6GlobalState.generate_num_constants.<locals>.<listcomp>r]  r  r  r  Fr  r   r$  r   ?      r   ZLLr   r   rb  r^  r  r  	constantsc                 S   s4   d dd |D }| | d| d| d d S )Nr  c                 S   s   g | ]}|d  qS r   r   r  r   r   r   rF  	  r  zKGlobalState.generate_num_constants.<locals>.store_array.<locals>.<listcomp>z const z[] = {r  )r   r   )r  r  r  r  rM  r   r   r   store_array	  s    z7GlobalState.generate_num_constants.<locals>.store_arrayrg  c                 S   s,   |dk rdnd}|  d| d| d d S )Nr  r   r  r  r  r  r   )r  rg  r  r   r   r   generate_forloop_start	  s   zBGlobalState.generate_num_constants.<locals>.generate_forloop_startrhs_codec                 S   s(   |  d| d |  | d| d S )Nznumbertab[i] = r  znumbertab[i])r   r  )r  Z	error_posr   r   r   r   assign_constant	  s   z;GlobalState.generate_num_constants.<locals>.assign_constantstart_offsetc              
   S   sF   t j}t|D ]\}}|d }| d| d| d||  d qd S )Nr   r  rt  r  r  )r   numbertab_cnamer   r   )r  r  r"  r#  r  r  r  r   r   r   define_constants	  s
   $z<GlobalState.generate_num_constants.<locals>.define_constantsr  zPyObject **numbertab = r  Zc_constantsdoublez"PyFloat_FromDouble(c_constants[i])r  z + )r$  Zint8_tZint16_tZint32_tZint64_t%sZcint_constants_z[i - r  z(i < z ? z : %s)r$   ZPyLong_FromLongZPyLong_FromLongLong(r  c                 S   sh   | dk }|r	|  } t  }| r!| d@ }d| }|| | dL } | s|s%dS |r.|td |  |S )Nr      s    0123456789abcdefghijklmnopqrstuv      0   -)r   r0  r   reverse)numberZis_negdigitsdigitZ
digit_charr   r   r   	to_base32L	  s    
z5GlobalState.generate_num_constants.<locals>.to_base32s   \000c                    s   g | ]} |d  qS r  r   r  r0  r   r   rF  a	  s    r   zconst char* c_constant = "r  zchar *end_pos;z+PyLong_FromString(c_constant, &end_pos, 32)zc_constant = end_pos + 1;r)  )rt  rM  r  r   rn  r   r   r#  r  r  r0  r
   Zstr_to_numberr  r&   r   r  r  r  r  r   r   r  r	   r  r  ) r   r  constant_countZfloat_constantsZint_constants_by_bytesizeZlarge_constantsZint_constant_countZ
int_suffixr4  r   r3  r5  r  r  Znumber_valuer  r  r  r  r  r!  r$  Zconstant_offsetZ	int_typesZarray_accessZint_constants_seenZ	byte_sizer  Z
array_nameZ	read_itemZ	capi_funcr  r   r1  r   r    s    








 



 




z"GlobalState.generate_num_constantsc                 C   s   | d | d | d|  d | d| d | d | d | d	 | d
 | d | d | d | d | d | d
 | d | d | d | d | d d S )Nz#if CYTHON_IMMORTAL_CONSTANTSr  zPyObject **table = r  zfor (Py_ssize_t i=0; i<z; ++i) {-#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADINGz#if PY_VERSION_HEX < 0x030E0000zEif (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1)r  z5if (PyUnstable_Object_IsUniquelyReferenced(table[i]))r  z3Py_SET_REFCNT(table[i], _Py_IMMORTAL_REFCNT_LOCAL);r  z5Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT);r  )Zarray_cnamer2  r  r   r   r   r  r	  s&   















z!GlobalState.immortalize_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)rk  r&   r   ra  )r   r  r  r   r   r   r   r  	  s   


zGlobalState.should_declarec                 C   sN   |  }z| j| }W |S  ty&   t| j}| j| || j|< Y |S w r   )Zget_filenametable_entryrW  rQ   r   rh  r0  )r   source_descr  r  r   r   r   lookup_filename	  s   
zGlobalState.lookup_filenamec                 C   sX   z| j | W S  ty   Y nw |jddd}dd |D }|s%|d || j |< |S )Nr  r  )r   error_handlingc                 S   s0   g | ]}d d|v r| dd ddn| qS )z * r%  rs  z.*[inserted by cython to avoid comment closer]/rr  z-/[inserted by cython to avoid comment start]*)rv  r  r   r   r   rF  	  s    z7GlobalState.commented_file_contents.<locals>.<listcomp>r$  )ri  rQ   	get_linesr0  )r   r4  source_fileFr   r   r   commented_file_contents	  s   
z#GlobalState.commented_file_contentsc                 C   s4   |r|| j vr| j | |j| |d 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.
        r  N)rj  r6  r  )r   r  r  r   r   r   r  	  s   	zGlobalState.use_utility_codec                 C   sr   |d u rd S |j r| |j  |jr| |j ddlm} ||jD ]}t|dr6|j|ur6| 	|j q$d S )Nr   r  r  )
r  r  Zutility_code_definitionr$  r  Zget_all_subtypesr   r   r  use_entry_utility_code)r   r  r  tpr   r   r   r;  	  s   z"GlobalState.use_entry_utility_coder   rZ  T)r$  r$  )3r   r   r   r  r~  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r&   r  r  r  r  r  r  r  r  r  r  r   r   r  r  r   r  r  r5  r:  r  r;  r   r   r   r   r     sb    -
10




	
	
	
		


*5 A 


r   c                    s2   | j t  fdd}fdd}t||S )Nc                    s
    | j S r   )	funcstater   )attribute_ofr   r   r   	  ry  z!funccontext_property.<locals>.getc                    s   t | j | d S r   )r   r>  )r   r3  r  r   r   r   	     z!funccontext_property.<locals>.set)r   r   
attrgetterr   )r  r   r   r   )r?  r  r   funccontext_property	  s
   

rB  c                   @   s   e Zd ZdddZdS )CCodeConfigTc                 C   s   || _ || _|| _d S r   )emit_code_commentsr  c_line_in_traceback)r   r  rD  rE  r   r   r   r   	  s   
zCCodeConfig.__init__N)TTT)r   r   r   r   r   r   r   r   rC  	  s    rC  c                   @   sp  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ej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&dDdE Z'dFdG Z(d>dHdIZ)d?dJdKZ*dLdM Z+dNdO Z,d=dPdQZ-dRdS Z.dTdU Z/d=dVdWZ0dXdY Z1dZd[ Z2d\d] Z3d^d_ Z4d=d`daZ5dbdc Z6e7ddde Z8e7dfdg Z9dhdi Z:djdk Z;d@dmdnZ<dAdodpZ=ejdqdr Z>ejdsdt Z?ejdudv Z@dwdx ZAejdydz ZBejd{d| ZCd}d~ ZDdeEfddZFejdd ZGejdd ZHejdd ZIejdd ZJejdd ZKdd ZLdd ZMdd ZN	l	+dBddZOdePfddZQdd ZRdd ZSdd ZTeUfddZVdd ZWdd ZXdd ZYdd ZZdd Z[dd Z\dAddZ]dAddZ^dCddZ_dCddZ`dDddZadDddZbdd Zcdd Zddd Zedd Zfdd Zgdd ZhddĄ ZiddƄ ZjddȄ Zkddʄ Zldd̄ Zmdd΄ ZnddЄ Zodd҄ ZpddԄ Zqddք ZrdEddلZsddۄ Ztdd݄ Zudd߄ ZvdAddZwdFddZxdGddZydd Zzdd Z{dGddZ|d=ddZ}dd Z~dd ZdHddZdHddZdd Zdd ZdIddZdJddZdAdd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdJddZdJddZdAddZdJddZdd Zdd ZdJddZd=ddZdKddZdJdd Zd!d" Zd#d$ ZdLd%d&Zd'd( Zd)d* ZdJd+d,Zd-d. Zd>d/d0ZeEd1d2fd3d4Zd5d6 Zd7d8 Zd9d: ZdS (M  r  a  
    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_posZpyclass_stackr>  r   rl  r"   Z
call_levelbolry  )r   rG  rH  copy_formattingr   r   r   r   
  s*   zCCodeWriter.__init__c                 C   s   t |||}|S r   r  )r   rG  rH  rL  r#  r   r   r   
create_new'
  s   zCCodeWriter.create_newc                 C   s    | j d u sJ || _ |j| _d S r   )r   rl  )r   Zglobal_stater   r   r   ry  -
  s   zCCodeWriter.set_global_statec                 C   r  r   )rH  copyto)r   r   r   r   r   rO  2
  r  zCCodeWriter.copytoc                 C   r,  r   )rH  getvaluer   r   r   r   rP  5
  ry  zCCodeWriter.getvaluec                 C   s$   d|v r|  | d S | | d S Nr  )_write_lines_write_to_bufferr   r}  r   r   r   r   8
  s   zCCodeWriter.writec                 C   s@   | j r
| j d d nd}| jj|g|d  | | d S )Nr   Nr   r  )rJ  rH  markersr  r  rS  )r   r}  Zfilename_liner   r   r   rR  >
  s   zCCodeWriter._write_linesc                 C   r  r   )rH  r   rT  r   r   r   rS  H
  r  zCCodeWriter._write_to_bufferc                 C   s   | j | | j dd}|S )NT)rG  rH  rL  )rN  rH  r  rR  r   r   r   r  K
  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.
        rF  rM  r   r   r   r   
new_writerO
  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)r   rH  insert)r   r  r   r   r   rX  V
  s   zCCodeWriter.insertc                 C   r   r   r   r   r   r   r   r  a
  r  zCCodeWriter.label_counterc                 C   r   r   r   r   r   r   r   r  c
  r  zCCodeWriter.return_labelc                 C   r   r   r   r   r   r   r   r  e
  r  zCCodeWriter.error_labelc                 C   r   r   r   r   r   r   r   r  g
  r  zCCodeWriter.labels_usedc                 C   r   r   r   r   r   r   r   r  i
  r  zCCodeWriter.continue_labelc                 C   r   r   r   r   r   r   r   r  k
  r  zCCodeWriter.break_labelc                 C   r   r   r   r   r   r   r   return_from_error_cleanup_labelm
  r  z+CCodeWriter.return_from_error_cleanup_labelc                 C   r   r   r   r   r   r   r   r  o
  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  )r   r  Zorig_labelsZskip_to_labelr  rZ  r  Z
orig_labelr   r   r   label_interceptorr
  s   




zCCodeWriter.label_interceptorc                 C      | j |S r   )r>  r  r   r  r   r   r   r  
      zCCodeWriter.new_labelc                 G      | j j| S r   )r>  r  r   r  r   r   r   r  
  r`  zCCodeWriter.new_error_labelc                 G   ra  r   )r>  r  rb  r   r   r   r  
  r`  zCCodeWriter.new_yield_labelc                 C   r,  r   )r>  r   r   r   r   r   r   
  r'  zCCodeWriter.get_loop_labelsc                 C   r^  r   )r>  r  r  r   r   r   r  
  r`  zCCodeWriter.set_loop_labelsc                 G   ra  r   )r>  r  rb  r   r   r   r  
  r`  zCCodeWriter.new_loop_labelsc                 C   r,  r   )r>  r	  r   r   r   r   r	  
  r'  zCCodeWriter.get_all_labelsc                 C   r^  r   )r>  r
  r  r   r   r   r
  
  r`  zCCodeWriter.set_all_labelsc                 C   r,  r   )r>  r  r   r   r   r   r  
  r'  zCCodeWriter.all_new_labelsc                 C   r^  r   )r>  r  r  r   r   r   r  
  r`  zCCodeWriter.use_labelc                 C   r^  r   )r>  r  r  r   r   r   r  
  r`  zCCodeWriter.label_usedc                 C   s   t | |d| _d S )N)r  )r  r>  r/  r   r   r   enter_cfunc_scope
  r@  zCCodeWriter.enter_cfunc_scopec                 C   s"   | j d u rd S | j   d | _ d S r   )r>  r  r   r   r   r   r  
  s   


zCCodeWriter.exit_cfunc_scopec                 C   sX   | j jd }|d| d | | | d | d| d |r*|   dS dS )z
        Init code helper function to start a cfunc scope and generate
        the prototype and function header ("static SIG {") of the function.
        r_  zstatic CYTHON_SMALL_CODE ; /*proto*/r$  r   {N)r   rn  r   rc  put_declare_refcount_context)r   	signaturer  r}  r  r   r   r   r  
  s   

zCCodeWriter.start_initcfuncc           	      C   sl   | |}d|| d| d}|r!| jd |ddd  |r(| | | d | |d  d S )	Nr  r'  r  r\  CYTHON_UNUSED r$  rd  re  )Zmangle_internalr  r   r   rv  rc  )	r   Zclass_scopereturn_typeZc_slot_nameZargs_signatureZneeds_funcstateZneeds_prototypeZslotfunc_cnameZdeclarationr   r   r   start_slotfunc
  s   


zCCodeWriter.start_slotfuncc                 C      |  | j||jS r   )r  r   r  r  )r   r  r  r   r   r   
get_py_int
     zCCodeWriter.get_py_intc                 C   rk  r   )r  r   r  r  )r   r  r5  r   r   r   get_py_float
  rm  zCCodeWriter.get_py_floatc                 C   s   |  | j||S r   )r  r   r  )r   r  r  r   r   r   r  
  s   zCCodeWriter.get_py_constc                 C   s   | j |jS r   )r   r  r  r  r   r   r   r  
  r1  zCCodeWriter.get_string_constc                 C   r^  r   )r   r  r  r   r   r   r  
  rT  z#CCodeWriter.get_pyunicode_ptr_constc                 C   s   | j ||j}| |S r   )r   r  r  r  )r   r?  r  r  r   r   r   r  
  s   
zCCodeWriter.get_py_string_constc                 C   s   |  | j|S r   )r  r   r  )r   r  r   r   r   r  
  r@  z CCodeWriter.get_py_codeobj_constc                 C   s   |  | j|jS r   )r  r   r  r  r   r   r   r   r   r  
  rX  z&CCodeWriter.get_argument_default_constc                 C   s
   |  |S r   r  r  r   r   r   rN  
  ry  zCCodeWriter.internc                 C   r  r  r  r  r   r   r   intern_identifier
  r1  zCCodeWriter.intern_identifierc                 C   r^  r   )r   r  r  r   r   r   r  
  rT  z'CCodeWriter.get_cached_constants_writerc                 C   s$   | j jd u r| |S | j j|S r   )r>  r  r  r  r   r  r   r   r   r  
  s   
z CCodeWriter.name_in_module_statec                 C      t j d|  S r  )r   r  rQ  r   r   r   r  
  s   z,CCodeWriter.name_in_main_c_code_module_statec                 C   rr  r  )r   r  rQ  r   r   r   name_in_slot_module_state
  s   z%CCodeWriter.name_in_slot_module_statec                 C   s   |j r|jS | |jS r   )is_py_class_scopeZnamespace_cnamer  r/  r   r   r   namespace_cname_in_module_state
  s   z+CCodeWriter.namespace_cname_in_module_statec                 C   s   |j r	| |jS |jS r   )is_extension_typer  Ztypeptr_cnamero  r   r   r   typeptr_cname_in_module_state  s   z)CCodeWriter.typeptr_cname_in_module_stater$  c                 C   s|   | j r
| jr
|   | jjr%| jr%| j\}}}| d| d|  d |r4|r/| | n| 	| | d d| _d S )Nz
#line z "r  r  r   )
rI  rK  emit_markerrl  r  rJ  rR  get_escaped_descriptionput_safer  )r   r   r  r4  r<  r   r   r   r   r   
  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   )rJ  rI  r   r  rZ  r   r   r   r\    s
    zCCodeWriter.mark_posc                 C   sV   | j \}}|| _d | _ | d | jjr |   | | | |r)| | d S d S rQ  )rI  rJ  rR  rl  rD  indent_build_markerwrite_trace_liner{  r   r   r   rx    s   

zCCodeWriter.emit_markerc                 C   sr   | j r3| j jr5| jjd r7|   | d|d dd| |dd| j j dd| | d	 d S d S d S d S )N	linetracez__Pyx_TraceLine(r   r   r  z)
)	r>  r  r   r  r|  rR  pos_to_offsetr  r  r   r  r   r   r   r~  +  s   8zCCodeWriter.write_trace_linec                 C   s   |\}}}t |tsJ | j|}|td|d | }|d  d7  < ||||d  7 }d|}d|  d|d	d| d
S )Nr   r$   r   z             # <<<<<<<<<<<<<<r   r  z/* "z":r   z
*/
)r   r   r   r:  r   r   ry  )r   r  r4  r<  colcontentsr  r   r   r   r   r}  2  s   

zCCodeWriter._build_markerc                 C   s   |  | d| _d S rU  )r   rK  r   r   r   r   r   rz  =  s   

zCCodeWriter.put_safec              	   C   s@  | j j}|rt|dkrt|d }| d| d}tj	||}tj
|s| dt  }d}zFz$t|}	|	| W d    n1 sMw   Y  t|| d}W n ttfym   tj
|sk Y nw W |s|tj
|r|t| n|stj
|rt| w w w |dd	}
d
|
 d}| | d S )Ni   rE  r   z.hz.tmpFTr  r%  z
#include "r  )r   rm  r   hashlibsha256r  	hexdigestr   r   r   existsgetpidr
   open_new_filer   shutilmoverE   r^   unlinkrv  r  )r   r   r  Zinclude_dirr   Zinclude_filer   Ztmp_pathdoner   Zc_pathr   r   r   r  B  s:   
zCCodeWriter.put_or_includec                 C   s4   | j rd|v rd| j  |jdd}| | d S )Nr  r  Tkeepends)r"   r   r  r  r  r   r   r   r  _  s   zCCodeWriter.put_multilinesc                 C   s   d}d|v r| dnd}d|v r7|| d8 }|dk r$|  j|7  _n|dkr7|d dkr7d}|  jd8  _| jr>|   | | d| _|dkrS|  j|7  _d S |r^|  jd7  _d S d S )NFr  r   r  Tr   )r  r"   rK  r|  r   )r   r   Z
fix_indentdlr   r   r   r  g  s$   
zCCodeWriter.putr  c                 C   sZ   |j rJ |j|| | jd || j |jr)tjr+|| jd | jd d S d S d S )Nr  r  rb  )r  r  r  r   r  rb  r   r  )r   r  r   r   r   put_code_here{  s   zCCodeWriter.put_code_herec                 C      |  j d7  _ d S Nr   r!   r   r   r   r   increase_indent     zCCodeWriter.increase_indentc                 C      |  j d8  _ d S r  r!   r   r   r   r   decrease_indent  r  zCCodeWriter.decrease_indentc                 C   s   |  d |   d S )Nr  )r   r  r   r   r   r   begin_block  s   
zCCodeWriter.begin_blockc                 C   s   |    | d d S )Nr  )r  r   r   r   r   r   	end_block  s   zCCodeWriter.end_blockc                 C   s   |  d| j  d S )Nr  )rS  r"   r   r   r   r   r|       zCCodeWriter.indentc                 C   s   dt |d d d  S )Nz0x%02X%02X%02X%02X)r   r   r   r      )r   )r   Z	pyversionr   r   r   get_py_version_hex  r  zCCodeWriter.get_py_version_hexc                 C   s"   || j jv r| d|  d S d S )Nz%s:;)r>  r  r   r  r   r   r   r    s   zCCodeWriter.put_labelc                 C   s   | j | | d|  d S )Ngoto %s;)r>  r  r   r  r   r   r   r[    r  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| d S )Nprivaterh  %s )dll_linkagez = %sz = NULLr  )Z
visibilityZdefined_in_pxdr&  Zcf_usedr  Zis_cpp_optionalr   cpp_optional_declaration_coder  r  ra  rz  literal_codeis_pyobjectr   r   r;  )r   r  Zstorage_classr  Z
definitionr   r   r   put_var_declaration  s*   






zCCodeWriter.put_var_declarationfunc_contextc                 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;r  r$  rh  z%sint %s = 0;z%sconst char *%s = NULL;)r  r  r  r  r  r  r  r  r   r  r  default_valuer  r>  r  r   lineno_cnamefilename_cnameclineno_cname)r   r  r  r   r   r!  r  Zunusedr   r   r   put_temp_declarations  s"   
z!CCodeWriter.put_temp_declarationsc                 C   s   |  tj |  d d S r  )r   r
   ZGENERATED_BY_MARKERr   r   r   r   put_generated_by  s   zCCodeWriter.put_generated_byc                 C   s    |  d|  |  d|  d S )Nz
#ifndef %sz
#define %sr  )r   r  r   r   r   put_h_guard  s   zCCodeWriter.put_h_guardc                 C   s   t jrd| S |S )Nzunlikely(%s))r   Zgcc_branch_hintsr   condr   r   r   unlikely  s   zCCodeWriter.unlikelyc                    s$   |sdS dd  fdd|D  S )Nr$  r  rt  c                    s   g | ]} ||qS r   r   )rB  r=  mapperr   r   rF    r  z8CCodeWriter.build_function_modifiers.<locals>.<listcomp>)r   )r   	modifiersr  r   r  r   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 *))r   Zis_self_argZis_completerv  r  )r   r  r   r   r   r   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  )r   r  r   r  r  r   r   r   as_pyobject  s   zCCodeWriter.as_pyobjectc                 C      | | | d S r   )Zgenerate_gotrefr8  r   r   r   
put_gotref  r  zCCodeWriter.put_gotrefc                 C   r  r   )Zgenerate_giverefr8  r   r   r   put_giveref  r  zCCodeWriter.put_giverefc                 C   r  r   )Zgenerate_xgiverefr8  r   r   r   put_xgiveref  r  zCCodeWriter.put_xgiverefc                 C   r  r   )Zgenerate_xgotrefr8  r   r   r   put_xgotref  r  zCCodeWriter.put_xgotrefc                 C      |j | ||d d S N)r  )Zgenerate_increfr   r  r   r  r   r   r   
put_incref  s   zCCodeWriter.put_increfc                 C   r  r  )Zgenerate_xincrefr  r   r   r   put_xincref  rX  zCCodeWriter.put_xincrefc                 C      |j | |||d d S N)r  have_gil)Zgenerate_decrefr   r  r   r  r  r   r   r   
put_decref     zCCodeWriter.put_decrefc                 C   r  r  )Zgenerate_xdecrefr  r   r   r   put_xdecref  r  zCCodeWriter.put_xdecrefc                 C      |j | ||||d d S N)r  r  r  )Zgenerate_decref_clearr   r  r   r  r  r  r   r   r   put_decref_clear     

zCCodeWriter.put_decref_clearc                 C   r  r  )Zgenerate_xdecref_clearr  r   r   r   r    r  zCCodeWriter.put_xdecref_clearc                 C      | | || d S r   )Zgenerate_decref_setr   r  r   	rhs_cnamer   r   r   put_decref_set  r@  zCCodeWriter.put_decref_setc                 C   r  r   )Zgenerate_xdecref_setr  r   r   r   put_xdecref_set  r@  zCCodeWriter.put_xdecref_setc                 C   r  N)r  )Zgenerate_incref_memoryviewslice)r   Zslice_cnamer   r  r   r   r   put_incref_memoryviewslice"  r  z&CCodeWriter.put_incref_memoryviewslicec                 C   s   | j |j|j|d d S r  )r  r  r   )r   r  r  r   r   r   put_var_incref_memoryviewslice&  r  z*CCodeWriter.put_var_incref_memoryviewslicec                 C      |  |j|j d S r   )r  r  r   r  r   r   r   put_var_gotref)  rX  zCCodeWriter.put_var_gotrefc                 C   r  r   )r  r  r   r  r   r   r   put_var_giveref,  rX  zCCodeWriter.put_var_giverefc                 C   r  r   )r  r  r   r  r   r   r   put_var_xgotref/  rX  zCCodeWriter.put_var_xgotrefc                 C   r  r   )r  r  r   r  r   r   r   put_var_xgiveref2  rX  zCCodeWriter.put_var_xgiverefc                 K      | j |j|jfi | d S r   )r  r  r   r   r  kwdsr   r   r   put_var_incref5     zCCodeWriter.put_var_increfc                 K   r  r   )r  r  r   r  r   r   r   put_var_xincref8  r  zCCodeWriter.put_var_xincrefc                 K   r  r   )r  r  r   r  r   r   r   put_var_decref;  r  zCCodeWriter.put_var_decrefc                 K   r  r   )r  r  r   r  r   r   r   put_var_xdecref>  r  zCCodeWriter.put_var_xdecrefc                 K   "   | j |j|jfd|ji| d S Nr  )r  r  r   
in_closurer  r   r   r   put_var_decref_clearA     "z CCodeWriter.put_var_decref_clearc                 K      | j |j|j|fi | d S r   )r  r  r   r   r  r  r  r   r   r   put_var_decref_setD     zCCodeWriter.put_var_decref_setc                 K   r  r   )r  r  r   r  r   r   r   put_var_xdecref_setG  r  zCCodeWriter.put_var_xdecref_setc                 K   r  r  )r  r  r   r  r  r   r   r   put_var_xdecref_clearJ  r  z!CCodeWriter.put_var_xdecref_clearr   c                 C   s4   |D ]}|r	|j r|jr| | q| | qd S r   )r&  Zxdecref_cleanupr  r  )r   entriesZ	used_onlyr  r   r   r   put_var_decrefsM  s   

zCCodeWriter.put_var_decrefsc                 C      |D ]}|  | qd S r   )r  r   r  r  r   r   r   put_var_xdecrefsU     zCCodeWriter.put_var_xdecrefsc                 C   r  r   )r  r  r   r   r   put_var_xdecrefs_clearY  r  z"CCodeWriter.put_var_xdecrefs_clearc                 C   sL   | j jjs| j jjs| j jjr$| d | d| d | d d S d S )Nz?#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000z)PyUnstable_Object_EnableDeferredRefcount(r|  r  )r>  r  Zis_module_scopeis_c_class_scopert  r   rq  r   r   r   put_make_object_deferred]  s   

z$CCodeWriter.put_make_object_deferredc                 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  r   )r   r  r   r  r  r  Zpy_noner   r   r   put_init_to_py_noneh  s
   zCCodeWriter.put_init_to_py_noner&  c                 C   s2   ||j  }| ||j| |jr| d d S d S )Nr  )r  r  r   r  r  )r   r  r  r  r   r   r   r   put_init_var_to_py_nonep  s
   
z#CCodeWriter.put_init_var_to_py_nonec                 C   s4  d}|j s
|jdkr.ddlm} |jtvr.||jrd}n|jdkr*| jjd s*n|r.d S |j	 }|s7d S |j r@||j
g7 }|rG||n|j}|j }	|	dkrYd	|	|f }|j }
|rv|| jj|j}| }|rv| | | d
|
|d||jr|jnd|f  |r|r| d d S d S d S )NF__getattribute__r   )	TypeSlotsT__getattr__Zfast_getattrZPyCFunctionz(void(*)(void))(%s)%sz{%s, (PyCFunction)%s, %s, %s}%s|0r  )
is_specialr  r$  r  special_py_methodsZis_binop_number_slotr   r  rg  method_flagsZmethod_coexistput_pymethoddef_wrapper
func_cnameZmethod_function_typeas_c_string_literalZget_slot_tableZget_slot_by_method_nameZpreprocessor_guard_coder   r   docZ	doc_cname)r   r  termZ
allow_skipZwrapper_code_writerZis_number_slotr  r  Zfunc_ptrcastZ
entry_nameZslotZpreproc_guardr   r   r   put_pymethoddefx  sJ   




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)r   zPyObject *res = %s;zFif (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); }zreturn res;z
return %s;r  )
r  r  rg  r  r  r  r   Zmethod_wrapper_prefixr   r  )r   r  r  r  r  Z	func_callr   r   r   r    s   




z#CCodeWriter.put_pymethoddef_wrapperc                 C   s<   | j jd r| j tdd d S | j tdd d S )NZfast_gilZFastGilr  Z	NoFastGil)r   r  r  r_  rG  r   r   r   r   use_fast_gil_utility_code  s   z%CCodeWriter.use_fast_gil_utility_codec                 C   sn   | j jd dkrddlm} || jdd | j tdd |   |s.d	}|r.| 	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.
        Zsubinterpreters_compatiblenor   )warningzTAcquiring the GIL is currently very unlikely to work correctly with subinterpreters.r   ForceInitThreadsr  __pyx_gilstate_savezPyGILState_STATE z%s = __Pyx_PyGILState_Ensure();N)r   r  ZErrorsr  rJ  r  r_  rG  r  r  r   )r   declare_gilstatevariabler  r   r   r   put_ensure_gil  s    

zCCodeWriter.put_ensure_gilc                 C   s"   |    |sd}| d|  dS )zD
        Releases the GIL, corresponds to `put_ensure_gil`.
        r  z__Pyx_PyGILState_Release(%s);N)r  r   )r   r  r   r   r   put_release_ensured_gil  s   z#CCodeWriter.put_release_ensured_gilc                 C   ,   |  d |  dtj d |  d d S )Nr3  zPyMutex_Lock(&r|  r  r   r   Zparallel_freethreading_mutexr   r   r   r   put_acquire_freethreading_lock     
z*CCodeWriter.put_acquire_freethreading_lockc                 C   r  )Nr3  zPyMutex_Unlock(&r|  r  r  r   r   r   r   put_release_freethreading_lock  r  z*CCodeWriter.put_release_freethreading_lockc                 C   sZ   |    | d |r| d|  |r!d}| jtdd nd}| | d dS )	z
        Acquire the GIL. The thread's thread state must have been initialized
        by a previous `put_release_gil`
        z__Pyx_FastGIL_Forget();z_save = %s;Z__Pyx_RestoreUnknownThreadReleaseUnknownGilr  ZPyEval_RestoreThreadz(_save);N)r  r   r   r  r_  rG  )r   r  unknown_gil_staterw  r   r   r   put_acquire_gil  s   

zCCodeWriter.put_acquire_gilc                 C   st   |    |r| jtdd d}d}nd}d}| | d | d| d	 |r3| d
|  | d dS )z2Release the GIL, corresponds to `put_acquire_gil`.r  r  Z__Pyx_SaveUnknownThreadZ__Pyx_UnknownThreadStateZPyEval_SaveThreadzPyThreadState *z _save;z_save = z();z%s = _save;z__Pyx_FastGIL_Remember();N)r  r   r  r_  rG  r   )r   r  r  rw  Zresult_typer   r   r   put_release_gil   s   
zCCodeWriter.put_release_gilc                 C      |  d d S )Nz%PyGILState_STATE __pyx_gilstate_save;r  r   r   r   r   r    r1  zCCodeWriter.declare_gilstatec                 C   s   |  d|| |f S )Nzif (%s < (0)) %s)r   r  )r   r  r3  r   r   r   put_error_if_neg  s   zCCodeWriter.put_error_if_negc              	   C   s   |rdnd}|j rd}n|jjr|jrd}n|jjr'|jr'|js'|jjr'd}nd}| j	t
| | d |s@|j|j}| d|d	| | |j | |f  d S )
NZNogilr$  ZRaiseClosureNameErrorZRaiseCppGlobalNameErrorZRaiseCppAttributeErrorZRaiseUnboundLocalErrorr  z!if (unlikely(!%s)) { %s(%s); %s }Z__Pyx_)Zfrom_closurer   r  Z
is_cglobalZis_variableZ	is_memberr  r  r   r  r_  rG  Zcheck_for_null_coder  r   r  r  r  )r   r  r  Zin_nogil_contextZunbound_check_codeZ	nogil_tagr  r   r   r   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>  r  r  r5  )r   r  r&  r   r   r   set_error_info3  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>  r  r  r  r  r5  )r   r  r&  r  r   r   r   r  ;  s   zCCodeWriter.error_gotoc                 C   s   d|  || |f S )Nz
if (%s) %s)r  r  )r   r  r  r   r   r   error_goto_ifH  r  zCCodeWriter.error_goto_ifc                 C      |  d| |S )Nz!%sr"  r   r  r  r   r   r   r  K  r  zCCodeWriter.error_goto_if_nullc                 C   r#  )Nz(%s < 0)r$  r%  r   r   r   error_goto_if_negN  s   zCCodeWriter.error_goto_if_negc                 C   s   |  d|S )NzPyErr_Occurred()r$  r  r   r   r   r  R  rT  zCCodeWriter.error_goto_if_PyErrc                 C   r^  r   )r   r5  )r   r   r   r   r   r5  U  rT  zCCodeWriter.lookup_filenamec                 C   r  )NZ__Pyx_RefNannyDeclarationsr  r   r   r   r   rf  X  r1  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  r   r  r_  rG  r   )r   r  Zacquire_gilr   r   r   r  [  s   
z&CCodeWriter.put_setup_refcount_contextc                 C      |  |r	d d S d d S )Nz"__Pyx_RefNannyFinishContextNogil()z__Pyx_RefNannyFinishContext();r  r   nogilr   r   r   r  b  r  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>  r  r   )r   qualified_nameZinclude_clineZformat_tupler   r   r   put_add_tracebacke  s   zCCodeWriter.put_add_tracebackc              	   C   sH   d| j _| d|tjtjtj| jjd |f  | 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.
        Tz0__Pyx_WriteUnraisable("%s", %s, %s, %s, %d, %d);Zunraisable_tracebacksZWriteUnraisableExceptionzExceptions.cN)r>  r  r   r   r  r  r  r   r  r  r_  rG  )r   r*  r)  r   r   r   put_unraisablev  s   

zCCodeWriter.put_unraisablec                 C   s   | j jd p| j jd S )NZprofiler  )r   r  r   r   r   r   
is_tracing  r  zCCodeWriter.is_tracingc                 C   s<   | j j}|r||jvr|j}|r||jvs|r|j| S dS )zk
        Calculate a fake 'instruction offset' from a node position as 31 bit int (32 bit signed).
        r   )r>  r  Znode_positions_to_offsetZparent_scope)r   r  r  r   r   r   r    s
   zCCodeWriter.pos_to_offsetc                 C   r'  )NZ__Pyx_TraceDeclarationsGenZ__Pyx_TraceDeclarationsFuncr  )r   is_generatorr   r   r   put_trace_declarations  r  z"CCodeWriter.put_trace_declarationsc                 C   s   |r|  d|  d S d S )Nz__Pyx_TraceFrameInit(%s)r  )r   codeobjr   r   r   put_trace_frame_init  s   z CCodeWriter.put_trace_frame_initc                 C   s~   |rdnd}|  | d|  dtj d| |d  d|d  d| |d	d|d	d|r1tjnd
 d| | d d S )NZ__Pyx_TraceStartGenZ__Pyx_TraceStartFuncr'  r  r  r   ], r   r   r   r|  )r   r  r   filetable_cnamer5  r  Zskip_dispatch_cnamer  )r   r  r  r)  r.  Zis_cpdef_func
trace_funcr   r   r   put_trace_start  s(   
zCCodeWriter.put_trace_startc                 C   s   |  dt|dd d S )Nz__Pyx_PyMonitoring_ExitScope(r   r|  )r   r   r(  r   r   r   put_trace_exit  r  zCCodeWriter.put_trace_exitc              	   C   s2   |  |}| d| d| | d| d d S )Nz__Pyx_TraceYield(r  r|  r  r   r  )r   retvalue_cnamer  r  r   r   r   put_trace_yield     
(zCCodeWriter.put_trace_yieldc                 C   s   | j j}|jr|jjd n|d }|j }| |d }| |}| d| dt	j
 d| d| d| | d| d d S )Nr   r   z__Pyx_TraceResumeGen(r  r  r2  r|  )r>  r  Zscope_classr  r  r  r5  r  r   r   r3  r  )r   r  r  
first_liner  Zfilename_indexr  r   r   r   put_trace_resume  s(   

zCCodeWriter.put_trace_resumec              	   C   s4   |  d| | dt|ddt|dd d S )N__Pyx_TraceException(r  r   r|  r   r  r   )r   r  reraiseZfreshr   r   r   put_trace_exception  s   4zCCodeWriter.put_trace_exceptionc                 C   s   |  dtj d d S )Nr=  z, 0, 0);)r   r   r  r   r   r   r   put_trace_exception_propagating  r  z+CCodeWriter.put_trace_exception_propagatingc                 C   s   |  d| | d d S )Nz__Pyx_TraceExceptionHandled(r|  )r   r  r  r   r   r   put_trace_exception_handled  r  z'CCodeWriter.put_trace_exception_handledc                 C   s(   |  d| | dt|dd d S )Nz__Pyx_TraceExceptionUnwind(r  r   r|  r>  )r   r  r)  r   r   r   put_trace_unwind  s   (zCCodeWriter.put_trace_unwindc              	   C   s2   |  |}| d| d| | d| d d S )Nz__Pyx_TraceStopIteration(r  r|  r7  )r   r  r3  r  r   r   r   put_trace_stopiteration  r:  z#CCodeWriter.put_trace_stopiterationc                 C   s   d}d}|d u r	n#|j r||}n|jrd}n|jrd}n|jr*d}d|j }nd}| |}| | d| | d| | dt|dd| d d S )	Nr$  Z__Pyx_TraceReturnValuer  Z__Pyx_TraceReturnCValuer  r'  r   r|  )	r  r  Zis_voidZ	is_stringZto_py_functionr  r   r  r   )r   r8  r  ri  r)  Z	extra_argr4  r6  r   r   r   put_trace_return  s    
<zCCodeWriter.put_trace_returnZDefaultPlacementNewr  c                 C   s"   | j | | d| d d S )Nz$__Pyx_default_placement_construct(&(z));)r   r  r   )r   r  Z_utility_coder   r   r   put_cpp_placement_new  s   z!CCodeWriter.put_cpp_placement_newc                 C   s"   |  d |  | |  d d S )Nz#ifdef _OPENMPz#endif /* _OPENMP */r  )r   stringr   r   r   putln_openmp  s   

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'
        #if %s    #undef likely    #undef unlikelyz    #define likely(x)   (x)z    #define unlikely(x) (x)r  Nr  r  r   r   r   undef_builtin_expect  s   



z CCodeWriter.undef_builtin_expectc                 C   sD   |  d|  |  d |  d |  d |  d |  d d S )NrI  rJ  rK  z2    #define likely(x)   __builtin_expect(!!(x), 1)z2    #define unlikely(x) __builtin_expect(!!(x), 0)r  r  r  r   r   r   redef_builtin_expect  s   



z CCodeWriter.redef_builtin_expect)NNF)NNTr   r>  )TF)r$  Fr=  )r$  NT)TT)FTTr)  )r&  T)TNr  )FNrZ  )FFFrU  )r   r   r   r   r  r   r   rN  ry  rO  rP  r   r  rR  rS  r  rW  rX  rB  r  r  r  r  r  r  rY  r  r]  r  r  r  r   r  r  r	  r
  r  r  r  rc  r  r  rj  rl  rn  r  r  r  r  r  r  rN  rp  r  r  r   r  rs  ru  rw  r   r\  rx  r~  r}  rz  r  r  r  r_  r  r  r  r  r  r|  r  r  r[  r  r  r  r  r  r  modifier_output_mapperr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r  r  r  r  r  r  r   r!  r  r"  r  r&  r  r5  rf  r  r  r+  r,  r-  r  r/  r1  r5  r6  r9  r<  r@  rA  rB  rC  rD  rE  r@  rF  rH  rL  rM  r   r   r   r   r  	  sd   

	





















1		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 rU  )r
   r  r   r"   )r   Zoutfile_namer   r   r   r     s   
zPyrexCodeWriter.__init__c                 C   s   | j dd| j |f  d S )Nz%s%s
rt  )r   r   r"   r  r   r   r   r     r  zPyrexCodeWriter.putlnc                 C   r  r  r!   r   r   r   r   r|    r@  zPyrexCodeWriter.indentc                 C   r  r  r!   r   r   r   r   r    r@  zPyrexCodeWriter.dedentN)r   r   r   r   r   r|  r  r   r   r   r   rO    s
    rO  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dZ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   r   c                 C   s.   |pt  | _|| _|| _|| _|| _i | _d S r   )r   rH  r"   original_levelr~  r   _insertion_points)r   rH  indent_levelr~  r   r   r   r   r     s   
zPyxCodeWriter.__init__r   c                 C   s   |  j |7  _ dS r  r!   r   Zlevelsr   r   r   r|  '  s   zPyxCodeWriter.indentc                 C   s   |  j |8  _ d S r   r!   rT  r   r   r   r  +  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)r   r|  r  )r   r<  r   r   r   indenter.  s
   
zPyxCodeWriter.indenterc                 C   r,  r   )rH  emptyr   r   r   r   rV  9  ry  zPyxCodeWriter.emptyc                 C   s$   | j  }t|tr|| j}|S r   )rH  rP  r   r   r  r   )r   r#  r   r   r   rP  <  s   

zPyxCodeWriter.getvaluec                 C   sX   |d u r| j d ur| j }|d urt||}| j|r'| jd  | d d S d d S )Nz    r  )r~  r  rH  r   r"   )r   r<  r~  r   r   r   r   B  s   

.zPyxCodeWriter.putlnc                 C   sJ   |d u r| j d ur| j }|d urt||}t|| jd }| j| d S )Nr  )r~  r  _indent_chunkr"   rH  r   )r   chunkr~  r   r   r   	put_chunkK  s   

zPyxCodeWriter.put_chunkc                 C   s   t | | j | j| jS r   )r   rH  r  r"   r~  r   r   r   r   r  U  s   zPyxCodeWriter.insertion_pointc                 C   s   | j   | j| _d S r   )rH  resetrQ  r"   r   r   r   r   rZ  X  s   
zPyxCodeWriter.resetc                 C   s   |   | j|< d S r   )r  rR  r_  r   r   r   named_insertion_point^  r@  z#PyxCodeWriter.named_insertion_pointc                 C   r  r   )rR  r_  r   r   r   r  a  ry  zPyxCodeWriter.__getitem__)Nr   Nr   r  r   )r   r   r   r   r   r|  r  r   rU  rV  rP  r   rY  r  rZ  r[  r  r   r   r   r   rP    s    






	
rP  rX  indentation_lengthr   c                    s   d| vsJ | j dd}|s| S |d d}|r||d< n|d= |s%dS t| d }t|D ]\}}t|}|d t|krDd||< q/||k rJ|}q/|t| krSd}||k rgd||    fd	d
|D }n||krx|| fdd
|D }d|S )zONormalise leading space to the intended indentation and strip empty lines.
    	Tr  r   rt  r  r   r   c                    s    g | ]}|d kr | nd qS )r  r   r  )
add_indentr   r   rF    s    z!_indent_chunk.<locals>.<listcomp>c                    s$   g | ]}|d kr| d nd qS )r  Nr   r  )startr   r   rF    s    r$  )r  r-  r   r   _count_indentationr   )rX  r\  r  	last_lineZmin_indentationr  r<  Zline_indentationr   )r^  r_  r   rW  e  s>   




rW  r   r}  c                 C   s(   d}t | D ]\}}|dkr |S q|S )Nr   rt  )r   )r}  r  chr   r   r   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 rU  )klassr  r  temps_count)r   rc  r   r   r   r     rP  zClosureTempAllocator.__init__c                 C   s&   | j  D ]\}}t|| j|< qd S r   )r  r  r   r  )r   r   r  r   r   r   rZ    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   r  T)r  r  r  r   Zis_cdefr   )	r  r  r  r   r  rd  rc  Zdeclare_varr0  )r   r   r  r   r   r   r$    s   


z"ClosureTempAllocator.allocate_tempN)r   r   r   r   rZ  r$  r   r   r   r   r.    s    r.  r   )jr  Zdeclarer   r  r   r   r   r  r   dataclassesr   rG  r   	functoolsr   r   
contextlibr   r   collectionsr   r$  r   r   r   r	   r
   ZScanningr   r   r    r   r   r#   r   rK   Zcompression.zstdr   r   Zzstd_CompressionParameterr   Zzstd_StrategyZstrategyZbtultra2Zcompression_levelZboundsr  r  Zctypedef_builtins_mapZbasicsize_builtins_mapZKNOWN_PYTHON_BUILTINS_VERSIONr   ZKNOWN_PYTHON_BUILTINSZuncachable_builtinsr  r   rN  r  r   r   r/  r   r   r
  r[  r_  r  r  r  r  r  r  r  r  r  rJ  r  r  r2  r7  r   Ur  r9  r:  r,  r;  findallr<  r=  rL  r   rB  rC  r  rO  rP  r  Zccallr&   r   rW  Z	exceptvalZcfuncr`  r.  r   r   r   r   <module>   s  " L

   O)
	



	

"  B        
        #K/	