o
    wiS                    @   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 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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d d!d"Zd#d#d$d%d&Zd'd(iZd)Ze g d*Z!g d+Z"e e e d,Z#d-d.ij$Z%e edddd/j$Z&G d0d1 d1Z'd2d3 Z(dZ)	 d4d5 Z*e*Z)G d6d7 d7Z+G d8d9 d9e+Z,G d:d; d;e,Z-dd<dgd=d>d?Z.e.d@dAdBdCdD Z/e. dEe-fdFdGZ0e.dHdIdJdKdLdM Z1e.dNdOdIdPdKdQdR Z2e.dSdTdBdUdV Z3e.dWd<dXdKdYdZ Z4e. d[d\ Z5ddi fd]d^Z6G d_d` d`e-Z7G dadb dbe,Z8G dcdd ddZ9G dedf dfZ:G dgdh dhZ;e jeeeedi e<djej=j>Z?e<dkj>Z@e<dljAZBe<dmjCZDG dndo doZEG dpdq dqZFG drds dsZGdtdu ZHG dvdw dwZIG dxdy dyZJG dzd{ d{ZKG d|d} d}ZLe jMe jNd~eOde jPdeOfddZQe Rde jSdeOde jPfddZTG dd dZUdS )    NosreoperatortextwrapTemplateNamingOptionsStringEncodingUtilsSourceDescriptorStringIOTree
DebugFlagsdefaultdictclosingpartialwrapsr   )r   r   )r   contextmanager)r      )r   )r   )r   )r	      )r
   )r   )r   strrangeinput)unicode
basestringxrange	raw_inputz&PyLong_Typez&PyFloat_Typez&PyWrapperDescr_Type)py_intpy_longpy_floatwrapper_descriptorPyTypeObjectPyHeapTypeObject)      r   alpha   )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_IncompleteInputError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__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)
rE   rY   r+   r;   rx   rz   r8   r   rr   _)		__cinit____dealloc____richcmp____next__	__await__	__aiter__	__anext____getbuffer____releasebuffer__inlineCYTHON_INLINE)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includeverbatimlateinitial r   Q/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/Cython/Compiler/Code.py__init__  s   zIncludeCode.__init__c                 C   s>   ||v r|| }t | j|j|_|j| j dS | ||< dS )z
        Insert `self` in dict `d` with key `key`. If that key already
        exists, update the attributes of the existing value with `self`.
        N)r   r   r   update)r   dkeyotherr   r   r   dict_update.  s
   zIncludeCode.dict_updatec                 C   s   | j S N)r   r   r   r   r   sortkey:  s   zIncludeCode.sortkeyc                 C   s   | j dS )z
        Return the main piece of C code, corresponding to the include
        file. If there was no include file, return None.
        r   )r   getr   r   r   r   	mainpiece=  s   zIncludeCode.mainpiecec                 C   s$   t | jD ]
}|| j|  qd S r   )r   r   putln)r   codekr   r   r   writeD  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 )NUtility)r   pathdirnameabspath__file__join)
Cython_dirr   r   r   get_utility_dirJ  s   r   c                 C   sN   t jt | }ttj|dd}| W  d   S 1 s w   Y  dS )zh
    Read all lines of the file at the provided path from a path relative
    to get_utility_dir().
    UTF-8)encodingN)r   r   r   r   r   r
   open_source_file	readlines)r   filenamefr   r   r   read_utilities_from_utility_dir[  s   $r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )AbstractUtilityCodeNc                 C      d S r   r   )r   outputr   r   r   put_codel     zAbstractUtilityCode.put_codec                 K   r  r   r   r   kwargsr   r   r   get_treeo  r  zAbstractUtilityCode.get_treec                 K   r  r   r   r  r   r   r   get_shared_library_scoper  r  z,AbstractUtilityCode.get_shared_library_scope)r   r   r   requiresr  r  r  r   r   r   r   r   h  s
    r   c                   @   s   e Zd ZdZdZi ZedddZedd Zedd	 Z	ei fd
dZ
edd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.
    FNc                 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   rJ   rp   r]   items
setdefaultr   r   )clsutilitynamer   linesbegin_linenotagsr   new_codeeall_tags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}td	d
|i j}tdj}	t|}
tdd }g }tt}d  } }}d}t|
D ][\}}||}|r|dr| |||||| |d }|d d = |  |d}|	|}|r| \}}nd}|| }qe||d |d |d qe|||| qe|d u rtd| |||||| t|}|| j |< |S )N)z.pyxz.pyz.pxdz.pxi#z^\s*#(?!\s*cython\s*:).* /z^\s*//.*|/\*[^*]*\*/z	\s+(\\?)$z\1zd^%(C)s{5,30}\s*(?P<name>(?:\w|\.)+)\s*%(C)s{5,30}|^%(C)s+@(?P<tag>\w+)\s*:\s*(?P<value>(?:\w|[.:])+)Cz?(.+)[.](proto(?:[.]\S+)?|impl|init|cleanup|module_state_decls)$c                   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  tagvaluezEmpty utility code file)_utility_cacher   r   r   splitextr   r   r   subr   rstripmatchread_utilities_hookr   r   r   groupr  cleargroupsaddappendrp   r   )r  r   	utilitiesr   extcommentstrip_commentsr+  match_special
match_type	all_linesr  r  r  r  r   r  linenolinemmtyper   r   r   load_utilities_from_file  s`   




z(UtilityCodeBase.load_utilities_from_filec           
         sl  d|v r| dd\}sJ  }|| \}}}|rd|v r7d|d v r7t ts7tj|fi |S | | D ]M\}}	||v rHq?|dkrir\ fddt|	D }	n, fddt|	D }	n|dkrw|	d	dh }	|	svq?n|	s|d
}	nt|	dkrt	|	d }	|	||< q?|d
ur||d< |d
ur||d< d|vr||d< d|vrr|d<  di |S )z
        Load utility code from a file specified by from_file (relative to
        Cython/Utility) and name util_code_name.
        z::r   r  tempitar	  c                    s    g | ]} j |fi qS r   )load.0depr  	from_fileorig_kwargsr   r   
<listcomp>  s    z(UtilityCodeBase.load.<locals>.<listcomp>c                    s   g | ]}  |qS r   )load_cachedrA  )r  rE  r   r   rG    s    r  Nr   r  r  r  filer   )
rsplitr>  r   TempitaUtilityCoder@  copyr  r   r   r   )
r  util_code_namerE  r  r3  r  r  r  r  r  r   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.
        )rJ   r@  )r  utility_code_namerE  _UtilityCodeBase__cacher   r   r   r   r   rH  4  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  r2  format_coder  )	util_coderC  implsprependprotosr   r   rT  S  s   

z/UtilityCodeBase.load_as_string.<locals>.prependr!  )r@  rP  r  r  r   )r  rM  rE  include_requiresr  utilr   rR  r   load_as_stringA  s   


	zUtilityCodeBase.load_as_stringz\n\n+c                 C   s   |r|d|  d }|S )z3
        Format a code section for output.
        r  z

strip)r   code_stringreplace_empty_linesr   r   r   rP  _  s   zUtilityCodeBase.format_codec                 C   s   dt | j| jf S )Nz<%s(%s)>)r   r   r  r   r   r   r   __repr__g     zUtilityCodeBase.__repr__c                 K   r  r   r   r  r   r   r   r  j  r  zUtilityCodeBase.get_treec                 K   r  r   r   r  r   r   r   r  m  r  z(UtilityCodeBase.get_shared_library_scopec                 C   s   | S r   r   )r   memodictr   r   r   __deepcopy__p  s   zUtilityCodeBase.__deepcopy__r   F)r   r   r   r   is_cython_utilityr(  r   r  r>  r@  rH  rX  r   r   r*  rP  r]  r  r  r`  r   r   r   r   r
  v  s&    % 
=
5r
  c                   @   sp   e Zd ZdZg dZ			dddZdd Zd	d
 Zdd ZdddZ	ddddde
fddZdd Zdd ZdS )UtilityCodeaF  
    Stores utility code to add during code generation.

    See GlobalState.put_utility_code.

    hashes/equals by instance

    proto           C prototypes
    impl            implementation code
    init            code to call on module initialization
    requires        utility code dependencies
    proto_block     the place in the resulting file where the prototype should
                    end up
    name            name of the utility code (or None)
    file            filename of the utility code file this utility was loaded
                    from (or None)
    )r  r  initcleanupmodule_state_declsNutility_code_protoc
           
         s`   | _ | _| _| _| _| _i  _g  _| _| _	|	 _
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  rd  re  rf  r	  _cachespecialize_listproto_blockr  rI  r   
code_parts_parts_tuple)
r   r  r  rd  re  rf  r	  rl  r  rI  r   r   r   r     s   zUtilityCode.__init__c                 C   s
   t | jS r   )r   rn  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   rn  )r   r   	self_type
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yv   | jd u r8d }n
 fdd| jD }t	| 
| 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   rG        z*UtilityCode.specialize.<locals>.<listcomp>)r  empty_declaration_codespecialization_namer   r   r  rj  rJ   r	  rc  rx  r  r  rd  re  rf  rl  rk  r2  )r   
pyrex_typer}  r  r   r	  rv  r   r|  r   rz    s2   
zUtilityCode.specializewriterCCodeWriterr  GlobalState	code_typec                 C   s   t | |}|s	d S |dv }t| ||\}}|dkr|nd}|d| j |r'dnd | d |rA|sA||| j d|  d S || d S )N)r  r  r  r!  z/* r  z */r   )r   process_utility_ccoder   r  put_or_includeput)r   r  r  r  r[  can_be_reusedresult_is_module_specificcode_type_namer   r   r   _put_code_section  s   
$zUtilityCode._put_code_sectionc                 C   s>   | j sd S |d }| ||d |||j |  d S )Ninit_globalsrd  )rd  r  r   error_goto_if_PyErr
module_pos)r   r  r  r   r   r   _put_init_code_section  s   z"UtilityCode._put_init_code_sectionc                 C   s   | j r| j D ]}|| q| jr| || j |d | jr'| |d |d | jr6tjr6| |d |d | j	rB| |d |d | j
rL| | d S d S )Nr  utility_code_defr  cleanup_globalsre  module_state_contentsrf  )r	  use_utility_coder  r  rl  r  re  r   generate_cleanup_coderf  rd  r  )r   r  
dependencyr   r   r   r    s   
zUtilityCode.put_code)	NNNNNNrg  NNr   )r   r   r   r   rm  r   ro  rs  rx  rz  r   r  r  r  r   r   r   r   rc  u  s    
	

rc  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_coder[  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   r]   r  )r  r  r[  r  macro)funcr  last_processormacro_namesr  r   r   process  s$   z=add_macro_processor.<locals>.build_processor.<locals>.processr   )r   rc  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  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>)r.  replacer   
splitlines)r   matchobjcontentr   r   r   _wrap_c_string%  s   
r  r  c                 C   s
   |  |S r   )rP  )r  r   r  r   r   r   _format_impl_code2  s   
r  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   rY  )rB  argr   r   r   rG  H  s    z*_inject_unbound_method.<locals>.<listcomp>r   N,r#   z'CALL_UNBOUND_METHOD() does not support r   z call arguments->)r0  splitr   cached_unbound_method_call_coder   modulestateglobal_cname)r  r  
type_cnamemethod_name	obj_cnameargsr   r   r   _inject_unbound_method7  s   $"
r  PYIDENT	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->%sIDENT
identifier)r0  r   r  get_py_string_constr	   EncodedStringcname)r  r  str_typer  r   r   r   _inject_string_constantO  s   r  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  empty_)r.  r   r  r   )r  r  ry  r   r   r   !_inject_empty_collection_constant^  s
   
	r  CGLOBALz(NAMED_)?CGLOBAL\(([^)]+)\)c                 C   s*   |  \}}|rtt|}tj d| S Nr  )r0  r   r   r  )r  r  is_namedr  r   r   r   _inject_cglobalm  s   
r  c                 C   s   |S )z;Entry point for code processors, must be defined last.
    r   )r  r   r[  r   r   r   r  y  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  __namer   r   r  )rJ   Tempitar   r  )rv  rw  rI  r  __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 )	rK  Nc                    sb   |d u ri }n|  }t||||}t||||}t||||}t j||f|||d| d S )N)rd  r  rI  )rL  r  r   r   )r   r  r  r  rd  rI  rw  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)rw  )r   r   r  r   rJ   r@  )r  rN  rE  rw  _TempitaUtilityCode__cachecontext_keyr   r   r   r   r   rH    s   
zTempitaUtilityCode.load_cachedc                 C   s   |du rdS t ||| j| jS rt  )r  rI  r  ru  r   r   r   rx    s   zTempitaUtilityCode.none_or_sub)NNNNNN)r   r   r   r   r   rH  rx  __classcell__r   r   r  r   rK    s
    rK  c                   @   s(   e Zd ZdZdZ dZdd Zdd ZdS )LazyUtilityCodez
    Utility code that calls a callback with the root code writer when
    available. Useful when you only have 'env' but not 'code'.
    z<lazy>Nc                 C   s
   || _ d S r   )callback)r   r  r   r   r   r     rp  zLazyUtilityCode.__init__c                 C   s   |  |j}|| d S r   )r  
rootwriterr  )r   globalstater  r   r   r   r       zLazyUtilityCode.put_code)r   r   r   r   r	  r   r  r   r   r   r   r    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ownerscopeerror_labellabel_counterr   labels_used	new_labelreturn_labelnew_error_labelcontinue_labelbreak_labelyield_labelsexc_varscurrent_except	can_trace	gil_ownedtemps_allocated
temps_freetemps_used_typezombie_tempstemp_counterclosure_tempscollect_temps_stackshould_declare_error_indicatoruses_error_indicatorerror_without_exceptionneeds_refnanny)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  ctype	is_pytempr   r   r   rG    s    
z/FunctionState.validate_exit.<locals>.<listcomp>)r  temps_in_user  r  r   r   r]   )r   	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   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  r2  )r   	expr_typer  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   prefix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_labels5  s
   zFunctionState.set_all_labelsc                 C   sR   |   }g }t|g dD ]\}}|r|| | q|| q| | |S )N)r  r  returnr	  )r  r   r2  r  r  )r   r  
new_labels	old_labelr  r   r   r   all_new_labels;  s   
zFunctionState.all_new_labelsc                 C      | j | d S r   )r  r1  r   lblr   r   r   	use_labelF     zFunctionState.use_labelc                 C   s
   || j v S r   )r  r  r   r   r   
label_usedI  rp  zFunctionState.label_usedFTc                 C   s^  |j r
|js
|j}n/|jr|js|j}n%|jr#ddlm} ||}n|j	r9|js9| j
jd r9| j
tdd |js>d}| j||f}|r^|dur^|d r^|d  }|d | n)	 |  jd7  _d
tj| jf }|| jvrtnq_| j||||f |s| j| ||f| j|< tjr| j d|||rdndf  | j!r| j!d ||f |S )a
  
        Allocates a temporary (which may create a new one or get a previously
        allocated and released one of the same type). Type is simply registered
        and handed back, but will usually be a PyrexType.

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

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

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

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

        A C string referring to the variable is returned.
        r   )
PyrexTypes
cpp_localsOptionalLocalsCppSupport.cppFNr   Tr  z/* %s allocated (%s)%s */r!  	 - zombier   )"is_cv_qualifiedis_referencecv_base_typeis_fake_referenceref_base_typeis_cfunctionr!  r"  
c_ptr_typeis_cpp_classr  
directivesr  rc  rH  needs_refcountingr  r   popremover  r   codewriter_temp_prefixr  r  r2  r  r1  r  r   debug_temp_code_commentsr  r   r  )r   r   
manage_refstaticreusabler"  freelistresultr   r   r   allocate_tempN  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   r]   r  r2  r1  r   r4  r  r   )r   r  r   r5  r8  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   r2  r0  )r   usedr  r   r5  r6  r8  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   )r0  )rB  r  r   r5  r   r   r   rG    s    z9FunctionState.temps_holding_reference.<locals>.<listcomp>)r  r   r   r   r   temps_holding_reference  s   z%FunctionState.temps_holding_referencec                 C   s   dd | j D S )zRReturn a list of (cname, type) tuples of refcount-managed Python objects.
        c                 S   s    g | ]\}}}}|r||fqS r   r   )rB  r  r   r5  r6  r   r   r   rG    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   r5  r8  r  r   r   r   rG    s    z8FunctionState.all_free_managed_temps.<locals>.<listcomp>)r   r  r  r   r   r   r   all_free_managed_temps  s   z$FunctionState.all_free_managed_tempsc                 C   s   | j t  dS )zJ
        Useful to find out which temps were used in a code block
        N)r  r2  r   r   r   r   r   start_collecting_temps  s   z$FunctionState.start_collecting_tempsc                 C   
   | j  S r   )r  r1  r   r   r   r   stop_collecting_temps  rp  z#FunctionState.stop_collecting_tempsc                 C   s   t || _d S r   )ClosureTempAllocatorr  r   r  r   r   r   init_closure_temps     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@  rA  rC  rF  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  r'  py_type
value_code)r   r  r'  rI  rJ  r   r   r   r     s   zNumConst.__init__r   r   r   r   r   r   r   r   r   r   rH    s    rH  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     s   
zPyObjectConst.__init__NrK  r   r   r   r   rL    s    rL  )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 S r   )r  textr	   escape_byte_stringescaped_value
py_strings)r   r  rS  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)utf8zutf-8r|   usasciizus-asciir!  r   ubr   )rS  lowerr   rQ  r   r   r~   rO  rN  rV  rJ   r   interned_prefixespy_const_prefixr  r   const_prefixPyStringConst)
r   r   r  rS  encoding_key
is_unicodeinternr   pystring_cname	py_stringr   r   r   r    sH   




zStringConst.get_py_string_constr   )r   r   r   r   r   r  r   r   r   r   rR    s    rR  c                   @   s"   e Zd ZdZdddZdd ZdS )	r`  zDGlobal info about a Python string constant held by GlobalState.
    Fc                 C   s   || _ || _|| _|| _d S r   )r  r   rb  rc  )r   r  r   rc  rb  r   r   r   r   8     
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   ri  r   r   r   r   r`  0  s    
r`  c                   @   sv  e Zd Zi Zg dZg dZdXddZdd Zdd	 Zd
d Z	dd Z
dd Zdd ZdXddZdYddZdd ZdXddZdd Zdd Zdd  ZdXd!d"Zd#d$ Zd%d& Zd'd( ZdXd)d*Zd+d, Zd-d. Zd/d0 ZdZd2d3Zd4efd5d6Zd7d8 Zd9d: Z d;d< Z!d=d> Z"d?d@ Z#d[dBdCZ$dDdE Z%dFdG Z&dHdI Z'dJdK Z(dLdM Z)dNdO Z*dPdQ Z+dRdS Z,dTdU Z-dVdW Z.dS )\r  )%h_codefilename_tableutility_code_proto_before_typesnumeric_typedefscomplex_type_declarationstype_declarationsrg  module_declarationstypeinfobefore_global_var
global_varstring_declsdeclslate_includesmodule_stater  module_state_endconstant_name_definesmodule_state_clearmodule_state_traversemodule_codemodule_exttypesinitfunc_declarationsinit_modulepystring_tablecached_builtinscached_constantsinit_constantsinit_codeobjectsr  r  cleanup_modulemain_methodutility_code_pragmasr  utility_code_pragmas_endend)rl  rn  rq  rg  r  Nc                 C   s   i | _ g | _i | _t | _i | _d| _|| _|| _i | _	|| _
i | _i | _i | _i | _g | _i | _g | _i | _i | _t | _||  || _d S NF)rm  filename_listinput_file_contentsr   utility_codesdeclared_cnamesin_utility_code_generationcode_configcommon_utility_include_dirpartsmodule_nodeconst_cnames_usedstring_const_indexdedup_const_indexpyunicode_ptr_const_indexcodeobject_constantsnum_const_indexarg_default_constantsconst_array_counterscached_cmethodsinitialised_constantsset_global_stater  )r   r  r  r  r  r   r   r   r     s,   

zGlobalState.__init__c                 C   s  | j }t| jD ]\}}|  }| j|< |dkr |d|  qtjs)| jd= n| jd }|d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();r  zint __Pyx_InitCachedConstants(T)refnanny__Pyx_InitCachedConstantsr  zint __Pyx_InitGlobals(void)r  zint __Pyx_InitConstants(r  zvoid __Pyx_CleanupGlobals(rg  r!  z)/* --- Runtime support code (head) --- */r  z
#line 1 "cython_utility"
z"/* --- Runtime support code --- */)r  r   code_layoutinsertion_pointr  r   r   cache_builtinsstart_initcfuncr   modulestatetype_cnamemodulestatevalue_cnameput_setup_refcount_contextr	   r  r  r  emit_linenumsr   )r   r  irh  wr   r   r   r   initialize_main_c_code  st   













z"GlobalState.initialize_main_c_codec                 C   s$   | j }| jD ]	}| | j|< qd S r   )r  h_code_layoutr  r  )r   r  rh  r   r   r   initialize_main_h_code  s   
z"GlobalState.initialize_main_h_codec                 C   s   |    | jd }tdd}|||j |d | jd }tdd}|||j |d | jd }td	d}|||j |d d S )
Nr  TypeConversionszTypeConversion.cr!  r  UtilityCodePragmasModuleSetupCode.cr  UtilityCodePragmasEnd)	close_global_declsr  rK  rH  r  rP  r  r   rc  )r   r   rW  r   r   r   finalize_main_c_code  s   




z GlobalState.finalize_main_c_codec                 C   
   | j | S r   )r  )r   r   r   r   r   __getitem__  rp  zGlobalState.__getitem__c                 C   sL  |    tjr+| jd }|d ||jr"||j |d |d |  | jd }|	  |d ||jrN||j |	  |d |d |  dD ]&}| j| }|d ||jrv||j |d |d |  qYtj
r| jd }|d |  tj
r| jd }|d |  d S d S )	Nr  	return 0;
return -1;}r  )r  r  r  r  )generate_const_declarationsr   r  r  r   r!  r  	put_labelexit_cfunc_scopeput_finish_refcount_contextr  )r   r  rh  r   r   r   r    sF   
















zGlobalState.close_global_declsc                 C   s   | d  d|j  d S )Nru  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 )Nr  )r  r1  r  r   targetr   r   r   get_cached_constants_writer2  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   r  rJ   new_num_const)r   	str_valuelongnessrI  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  rJ  r  r   r   r   get_float_constB  s   zGlobalState.get_float_constc                 C   s@   |d ur| j |}|d ur|S | |}|d ur|| j |< |S r   )r  r   new_array_const_cname)r   r
  	dedup_keyconstr   r   r   get_py_constI  s   

zGlobalState.get_py_constc                 C   s$   |  d}t||}| j| |S Nr!  )new_const_cnamerL  r  r2  )r   r   r  r  r   r   r   get_argument_default_constS  s   

z&GlobalState.get_argument_default_constc                 C   sJ   |j r| }n| }z| j| }W |S  ty$   | ||}Y |S w r   )rb  
utf8encode
byteencoder  rJ   new_string_const)r   rS  rW  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   )rb  r  rJ   r  )r   rS  r  r   r   r   get_pyunicode_ptr_consth  s   
z#GlobalState.get_pyunicode_ptr_constc                 C   s   |  |}||j|}|S r   )r  r  r   )r   rS  r  c_stringre  r   r   r   r  q  s   
zGlobalState.get_py_string_constc                 C   s,   t | j}tj d| d}| j| |S )N[])r   r  r   codeobjtab_cnamer2  )r   nodeidxr  r   r   r   get_py_codeobj_constw  s   
z GlobalState.get_py_codeobj_constc                 C      | j |ddS NTr  r  r   rS  r   r   r   get_interned_identifier}  rG  z#GlobalState.get_interned_identifierc                 C   s$   |  |}t|||}|| j|< |S r   )new_string_const_cnamerR  r  )r   rS  rW  r  r  r   r   r   r    s   

zGlobalState.new_string_constc                 C   s,   |  ||}t||||}|| j||f< |S r   )new_num_const_cnamerH  r  )r   r'  rI  rJ  r  r  r   r   r   r    s   zGlobalState.new_num_constc                 C   s   | dd}| j|dS )NASCIIignore)r'  )decoder  )r   bytes_valuer'  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   )r  r   )r   
format_strr<  r  r'  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   +-neg_*   zlarge{counter}_   _xxx_i%s%s)r   r]  r  r   r  )r   r'  rI  r
  r  r   r   r   r    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  )rP  rZ  r  r   r]  r_  )r   r
  r'  name_suffixr   r   r   r    s   zGlobalState.new_const_cnamer
  c                 C   s2   | j |d}|d | j |< tj | d| dS )Nr   r   r  r  )r  r   r   pyrex_prefix)r   r
  countr   r   r   r    s   z!GlobalState.new_array_const_cnamec              	   C   sL   ||f}z| j | }W |S  ty%   | dd||f  }| j |< Y |S w )Numethodz%s_%s)r  rJ   r  )r   r  r  r   r  r   r   r   get_cached_unbound_method  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  rc  rH  r  r   )	r   modulestate_cnamer  r  r  
arg_cnamesrN  cache_cnamer  r   r   r   r    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_builtin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_decl  s   
z#GlobalState.add_cached_builtin_declc              	   C   sN   | j d }|| |j}| tdd |d|||||f  d S )Nr  GetBuiltinNamer   z*%s = __Pyx_GetBuiltinName(%s); if (!%s) %s)	r   name_in_main_c_code_module_stater  r  r  rc  rH  r   
error_goto)r   r	  r  r  r  cname_in_modulestater   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_declarationsTc                 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 )Ni   r   
Py_ssize_tPy_VISIT__Pyx_VISIT_CONSTr}  zfor (z i=0; i<z	; ++i) { z(traverse_module_state->z[i]); }r|  z&; ++i) { Py_CLEAR(clear_module_state->)r  r   )r   struct_attr_cnamer  may_have_refcyclescounter_type
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   rG    s    z>GlobalState.generate_object_constant_decls.<locals>.<listcomp>ry  z%s;r|  zclear_module_state->TF)clear_before_decrefnannyz	->memviewr}  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])r  sortr  r   r   declaration_coder0  put_xdecref_clearis_memoryviewslicer   r  r  r   r  r  cleanup_level_for_type_prefixr   r  r  r  )
r   constsr   r  r  r
  r  r  cleanup_levelpart_writerr   r   r   r    sD   



z*GlobalState.generate_object_constant_declsc           	      C   s   | j sd S | jd }| jd }g }t| j  D ]8\\}}}|| | t|j}|	d|  |	d|
||f  |	|
| d|
| d qtjrj| jd }|D ]}|	d|
| d	 q[d S d S )
Nry  r  z__Pyx_CachedCFunction %s;z%s.type = (PyObject*)%s;z.method_name = &;r  z	Py_CLEAR(z	.method);)r  r  r   r  r2  r  r	   r  r  r   r  r   r  )	r   declrd  cnamesr  r  r  method_name_cnamere  r   r   r   r  "  s2   




z)GlobalState.generate_cached_methods_declsc              
   C   s  dd | j  D }|  g }d}t }dd }| jd }|D ]E\}}}	t|	j}
|jd| d|
 d	d
d |	j	d uret
|	j|krJt
|	j}|	j	 D ]}||| ||	jt
|j|f qOq t| j D ]0\}	}t|	\}}|r|d |d||f  |r|d |d||f  |d qm|sd S |  | jd }|d |tdt|t
|d  t
|}| jd dtj d| d | jtj|dd t|}|jt
d |rd|vs|d dksJ |dd t|D }|dtjd|f  |d tj  t|D ]/\}\}}}||| }|j}| jd! d"|jtj|f  |d#|||||j|jf  q|d$ |d% | t d&d' | jd( }|d)tj|!tjtj|"| j#f  d S )*Nc                 S   r  r   r  r  r   r   r   rG  <  s    z9GlobalState.generate_string_constants.<locals>.<listcomp>r   c                 S   s&   | j r| j dvrd| j   dS dS )N)r  USASCIIzUS-ASCIIUTF8r   r  0)r   r\  )re  r   r   r   normalise_encoding_nameB  s   zFGlobalState.generate_string_constants.<locals>.normalise_encoding_namerv  zstatic const char z[] = "z";T)safez#ifdef Py_UNICODE_WIDEz static Py_UNICODE %s[] = { %s };#else#endifr  r!  a          typedef struct {
            const char *s;
        #if %(max_length)d <= 65535
            const unsigned short n;
        #elif %(max_length)d / 2 < INT_MAX
            const unsigned int n;
        #elif %(max_length)d / 2 < LONG_MAX
            const unsigned long n;
        #else
            const Py_ssize_t n;
        #endif
        #if %(num_encodings)d <= 31
            const unsigned int encoding : 5;
        #elif %(num_encodings)d <= 255
            const unsigned char encoding;
        #elif %(num_encodings)d <= 65535
            const unsigned short encoding;
        #else
            const Py_ssize_t encoding;
        #endif
            const unsigned int is_unicode : 1;
            const unsigned int intern : 1;
        } __Pyx_StringTabEntry;
        )
max_lengthnum_encodingsry  r!  r  r"  Fr#  )r   r2  c                 S   s   i | ]\}}||qS r   r   )rB  r  r   r   r   r   
<dictcomp>  r~  z9GlobalState.generate_string_constants.<locals>.<dictcomp>z(static const char * const %s[] = { %s };r  z*static const __Pyx_StringTabEntry %s[] = {r{  z#define %s %s[%s]z6{%s, sizeof(%s), %d, %d, %d}, /* PyObject cname: %s */z{0, 0, 0, 0, 0}z};InitStringszStringTools.cr  z*if (__Pyx_InitStrings(%s, %s, %s) < 0) %s;)$r  r  r$  r   r  r	   split_string_literalrU  r   rV  r   r1  r2  r  r   r  r  encode_pyunicode_stringr  r   dedentr   r   stringtab_cnamer  r   stringtab_encodings_cnamer   rb  rc  r  rc  rH  r  r  r  )r   c_constsrV  longest_pystring	encodingsr3  decls_writerr   r  r  cliteralre  utf16_arrayutf32_arrayr  py_string_countencodings_mapr  c_cnameencodings_indexrb  r  r   r   r   r  ;  s   








  




z%GlobalState.generate_string_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
}d
}	| jD ]7}
|
j}|j	sbt
|t|j|j }t
||j}t
||j}t
|t|
j}t
||jd
 }t
|	t|j}	qC|	d }|td|  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 )"Nr  zint __Pyx_CreateCodeObjects(r  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/;
            unsigned int line_table_length : z;;
        } __Pyx_PyCode_New_function_description;
        
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  ry  r!  r  r"  Fr#  )r  r   r  r  r  r  r   r  def_nodeis_generator_expressionr   r   r  num_kwonly_argsnum_posonly_argsvarnamesr	  node_positionsr  r   r=  
bit_lengthr  rc  rH  generate_codeobjr  r  )r   r  init_function	max_flagsmax_func_argsmax_kwonly_argsmax_posonly_argsmax_varsmax_linemax_positionsr  rN  max_linetable_lencode_object_countr   r   r   r    st   
















 z)GlobalState.generate_codeobject_constantsc              
   C   s   dd | j  D }|  | jd }|D ]c\}}}}}}|j}| jd d|  | jd d|  | jd d	|  |d
krEd}	n|dkrLd}	nt|rTd}	nt|	ddkr`d}	nd}	|
|}
|d|
|	| ||
| jf  qd S )Nc                 S   s2   g | ]}|j |jd  dkt|j|j|j|fqS )r   r  )rI  r'  r   rJ  r  r   r   r   rG    s    *z6GlobalState.generate_num_constants.<locals>.<listcomp>r  ry  zPyObject *%s;r|  z!Py_CLEAR(clear_module_state->%s);r}  z-__Pyx_VISIT_CONST(traverse_module_state->%s);r   zPyFloat_FromDouble(%s)r  zPyLong_FromString("%s", 0, 0)r     zPyLong_FromLong(%sL)zPyLong_FromLong(%s)z%s = %s; %s)r  r  r$  r  r  r   r
   long_literalr   lstripr  error_goto_if_nullr  )r   r)  r  rI  r   r'  rJ  r  r  function
init_cnamer   r   r   r    s:   





z"GlobalState.generate_num_constantsc                 C   sN   || j v r | j | }t|jt|jksJ |j|jksJ dS || j |< dS )NFT)r  r   r   rd  )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   )get_filenametable_entryrm  rJ   r   r  r2  )r   source_descr  indexr   r   r   lookup_filename*  s   
zGlobalState.lookup_filenamec              	   C   s   z| j | W S  ty   Y nw |jddd}zdd |D }W t|dr)|  nt|dr4|  w w |s<|d || j |< |S )Nr  r  )r   error_handlingc                 S   s(   g | ]}d |  dddd qS )z * z*/z.*[inserted by cython to avoid comment closer]/z/*z-/[inserted by cython to avoid comment start]*)r+  r  r  r   r   r   rG  <  s    
z7GlobalState.commented_file_contents.<locals>.<listcomp>closer!  )r  rJ   	get_linesr   rk  r2  )r   rg  source_fileFr   r   r   commented_file_contents4  s*   


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

        See UtilityCode.
        N)r  r1  r  )r   r  r   r   r   r  M  s   	zGlobalState.use_utility_codec                 C   s8   |d u rd S |j r| |j  |jr| |j d S d S r   )r  r  utility_code_definitionr  r   r   r   use_entry_utility_codeZ  s   z"GlobalState.use_entry_utility_coder   ra  )r!  r!  T)/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  ri  ro  r  rq  r   r   r   r   r  B  sX    )
4*



	
	
	
		


*zG 
r  c                    s2   | j t  fdd}fdd}t||S )Nc                    s
    | j S r   )	funcstater   )attribute_ofr   r   r   f  rp  z!funccontext_property.<locals>.getc                    s   t | j | d S r   )r   rs  )r   r'  r  r   r   r   h     z!funccontext_property.<locals>.set)r   r   
attrgetterr   )r  r   r   r   )rt  r  r   funccontext_propertyc  s
   

rw  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  ry  rz  r   r   r   r   r  s   
zCCodeConfig.__init__N)TTT)r   r   r   r   r   r   r   r   rx  m  s    rx  c                   @   s  e Zd ZdZejd dd6ddZdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zedd Zedd Zedd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zd7d,d-Zd8d.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'd9dHdIZ(d:dJdKZ)dLdM Z*dNdO Z+d8dPdQZ,dRdS Z-dTdU Z.d8dVdWZ/dXdY Z0dZd[ Z1d\d] Z2d^d_ Z3d8d`daZ4dbdc Z5e6ddde Z7e6dfdg Z8dhdi Z9djdk Z:d;dmdnZ;d<dodpZ<dqdr Z=dsdt Z>dudv Z?dwdx Z@dydz ZAd{d| ZBd}eCfd~dZDdd ZEdd ZFdd ZGdd ZHdd ZIdd ZJdd ZKdd ZL	l	+d=ddZMdd ZNdd ZOdd ZPdd ZQeRfddZSdd ZTdd ZUdd ZVdd ZWdd ZXdd ZYd<ddZZd<ddZ[d>ddZ\d>ddZ]d?ddZ^d?ddZ_dd Z`dd Zadd Zbdd Zcdd Zddd Zedd ZfddÄ Zgddń ZhddǄ ZiddɄ Zjdd˄ Zkdd̈́ Zlddτ Zmddф Znddӄ Zod@ddքZpdd؄ Zqddڄ Zrd<dd܄ZsdAdd߄ZtdBddZudd Zvdd ZwdBddZxd8ddZydd Zzdd Z{dCddZ|dCddZ}dd Z~dd ZdDddZdEddZd<ddZdd Zdd Zd d Zdd Zdd Zdd ZdEdd	ZdEd
dZd<ddZdEddZdd Zdd ZdEddZd8ddZdFddZdEddZdd Zdd ZdGd d!Zd"d# Zd$d% ZdEd&d'Zd(d) Zd9d*d+ZeCd,d-fd.d/Zd0d1 Zd2d3 Zd4d5 ZdS (H  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_pospyclass_stackrs  r  r  level
call_levelbolr  )r   r|  r}  copy_formattingr   r   r   r     s*   zCCodeWriter.__init__c                 C   s   t |||}|S r   r  )r   r|  r}  r  r9  r   r   r   
create_new  s   zCCodeWriter.create_newc                 C   s    | j d u sJ || _ |j| _d S r   )r  r  )r   global_stater   r   r   r    s   zCCodeWriter.set_global_statec                 C   r  r   )r}  copyto)r   r   r   r   r   r    r   zCCodeWriter.copytoc                 C   rB  r   )r}  getvaluer   r   r   r   r    rp  zCCodeWriter.getvaluec                 C   s$   d|v r|  | d S | | d S Nr  )_write_lines_write_to_bufferr   rv  r   r   r   r     s   zCCodeWriter.writec                 C   s@   | j r
| j d d nd}| jj|g|d  | | d S )Nr   Nr   r  )r  r}  markersextendr  r  )r   rv  filename_liner   r   r   r    s   zCCodeWriter._write_linesc                 C   r  r   )r}  r   r  r   r   r   r    r   zCCodeWriter._write_to_bufferc                 C   s   | j | | j dd}|S )NT)r|  r}  r  )r  r}  r  rh  r   r   r   r    s   zCCodeWriter.insertion_pointc                 C   s
   t | dS )z
        Creates a new CCodeWriter connected to the same global state, which
        can later be inserted using insert.
        r{  r  r   r   r   r   
new_writer  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  r}  insert)r   r  r   r   r   r    s   zCCodeWriter.insertc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.label_counterc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.return_labelc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.error_labelc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.labels_usedc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.continue_labelc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.break_labelc                 C   r  r   r   r   r   r   r   return_from_error_cleanup_label  r  z+CCodeWriter.return_from_error_cleanup_labelc                 C   r  r   r   r   r   r   r   r    r  zCCodeWriter.yield_labelsTc                 c   sl    t ||D ]-\}}| |sq|r| | d}|dur$| j||d | | ||fV  | | qdS )a  
        Helper for generating multiple label interceptor code blocks.

        @param new_labels: the new labels that should be intercepted
        @param orig_labels: the original labels that we should dispatch to after the interception
        @param skip_to_label: a label to skip to before starting the code blocks
        @param pos: the node position to mark for each interceptor block
        @param trace: add a trace line for the pos marker or not
        N)trace)r   r!  put_gotomark_posr  )r   r  orig_labelsskip_to_labelr	  r  r  
orig_labelr   r   r   label_interceptor  s   




zCCodeWriter.label_interceptorc                 C      | j |S r   )rs  r  r   r  r   r   r   r  	      zCCodeWriter.new_labelc                 G      | j j| S r   )rs  r  r   r  r   r   r   r  	  r  zCCodeWriter.new_error_labelc                 G   r  r   )rs  r  r  r   r   r   r  	  r  zCCodeWriter.new_yield_labelc                 C   rB  r   )rs  r  r   r   r   r   r  	  r%  zCCodeWriter.get_loop_labelsc                 C   r  r   )rs  r  r  r   r   r   r  	  r  zCCodeWriter.set_loop_labelsc                 G   r  r   )rs  r  r  r   r   r   r  	  r  zCCodeWriter.new_loop_labelsc                 C   rB  r   )rs  r  r   r   r   r   r  	  r%  zCCodeWriter.get_all_labelsc                 C   r  r   )rs  r  r  r   r   r   r  	  r  zCCodeWriter.set_all_labelsc                 C   rB  r   )rs  r  r   r   r   r   r  	  r%  zCCodeWriter.all_new_labelsc                 C   r  r   )rs  r  r  r   r   r   r  	  r  zCCodeWriter.use_labelc                 C   r  r   )rs  r!  r  r   r   r   r!  	  r  zCCodeWriter.label_usedc                 C   s   t | |d| _d S )N)r  )r  rs  rE  r   r   r   enter_cfunc_scope"	  ru  zCCodeWriter.enter_cfunc_scopec                 C   s"   | j d u rd S | j   d | _ d S r   )rs  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!  static  {N)r  r  r   r  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  rw  CYTHON_UNUSED r!  r  r  )mangle_internalr%  r  r   r  r  )	r   class_scopereturn_typec_slot_nameargs_signatureneeds_funcstateneeds_prototypeslotfunc_cnamedeclarationr   r   r   start_slotfunc8	  s   


zCCodeWriter.start_slotfuncc                 C      |  | j||jS r   )name_in_module_stater  r  r  )r   r  r  r   r   r   
get_py_intF	     zCCodeWriter.get_py_intc                 C   r  r   )r  r  r  r  )r   r  rJ  r   r   r   get_py_floatK	  r  zCCodeWriter.get_py_floatc                 C   s   |  | j||S r   )r  r  r  )r   r
  r  r   r   r   r  P	  s   zCCodeWriter.get_py_constc                 C   s   | j |jS r   )r  r  r  r  r   r   r   r  U	  rG  zCCodeWriter.get_string_constc                 C   r  r   )r  r  r  r   r   r   r  X	  rj  z#CCodeWriter.get_pyunicode_ptr_constc                 C   s   | j ||j}| |S r   )r  r  r  r  )r   rS  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  `	  ru  z CCodeWriter.get_py_codeobj_constc                 C   s   |  | j|jS r   )r  r  r  r  r   r   r   r   r   r  c	  r^  z&CCodeWriter.get_argument_default_constc                 C   s
   |  |S r   r  r  r   r   r   rc  f	  rp  zCCodeWriter.internc                 C   r  r  r  r  r   r   r   intern_identifieri	  rG  zCCodeWriter.intern_identifierc                 C   r  r   )r  r  r  r   r   r   r  l	  rj  z'CCodeWriter.get_cached_constants_writerc                 C   s$   | j jd u r| |S | j j|S r   )rs  r  r  r  )r   r  r   r   r   r  o	  s   
z CCodeWriter.name_in_module_statec                 C      t j d|  S r  )r   r  rg  r   r   r   r  y	  s   z,CCodeWriter.name_in_main_c_code_module_statec                 C   r  r  )r   r  rg  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_scopenamespace_cnamer  rE  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  typeptr_cnamer  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   )
r~  r  emit_markerr  r  r  r  get_escaped_descriptionput_safer  )r   r   r4  rg  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   )r  r~  r   r	  r  r   r   r   r  	  s
    zCCodeWriter.mark_posc                 C   sV   | j \}}|| _d | _ | d | jjr |   | | | |r)| | d S d S r  )r~  r  r  r  ry  indent_build_markerwrite_trace_liner  r   r   r   r  	  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)
)	rs  r  r  r/  r  r  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  ro  r   r   r  )r   r	  rg  r;  colcontentsr  r   r   r   r   r  	  s   

zCCodeWriter._build_markerc                 C   s   |  | d| _d S r  )r   r  r   r   r   r   r   r  	  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   rX  r   z.hz.tmpFTr  r"  z
#include "r  )r  r  r   hashlibsha256encode	hexdigestr   r   r   existsgetpidr
   open_new_filer   shutilmover=   rW   unlinkr  r  )r   r   r  include_dirr   include_filer   tmp_pathdoner   c_pathr   r   r   r  	  s:   
zCCodeWriter.put_or_includec                 C   s   d}d|v r| d}nd}d|v r8|| d8 }|dk r%|  j|7  _n|dkr8|d dkr8d}|  jd8  _| jr?|   | | d| _|dkrT|  j|7  _d S |r_|  jd7  _d S d S )NF{r   r  Tr   )r  r  r  r  r   )r   r   
fix_indentdlr   r   r   r  	  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  re  )r  r  r  r  r  re  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
  ru  zCCodeWriter.increase_indentc                 C      |  j d8  _ d S r  r  r   r   r   r   decrease_indent

  ru  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 )Nz  )r  r  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   )r   	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:;)rs  r  r   r  r   r   r   r  
  s   zCCodeWriter.put_labelc                 C   s   | j | | d|  d S )Ngoto %s;)rs  r  r   r  r   r   r   r  
  s   zCCodeWriter.put_gotoc                 C   s   |j dkr|s|jsd S |j dkr|jsd S |js| d |r'| d|  |jr7| |jj|j|d n| |jj	|j|d |j
d urU| d|j|j
  n	|jjr^| d | d | jj| d S )Nprivater  %s )dll_linkagez = %sz = NULLr,  )
visibilitydefined_in_pxdr<  cf_usedr  is_cpp_optionalr   cpp_optional_declaration_coder  r%  rd  r  literal_codeis_pyobjectr   rs  r  rq  )r   r  storage_classr  
definitionr   r   r   put_var_declaration#
  s*   






zCCodeWriter.put_var_declarationc                 C   s   |j D ]F\}}}}|jr|js|jjd r||}n||}|jr+| d|  q|j	r<| d||
|jf  q| d|rCdpDd|f  q|jrv| jjrTd}nd}| d|tjf  | d	|tjf  | d|tjf  d S d S )
Nr#  z
%s = NULL;z%s = %s;z%s%s;r  r!  r  z%sint %s = 0;z%sconst char *%s = NULL;)r  r.  r*  r  r/  r  r%  r  r   r'  r  default_valuer  rs  r  r   lineno_cnamefilename_cnameclineno_cname)r   func_contextr  r   r5  r6  r-  unusedr   r   r   put_temp_declarations=
  s"   
z!CCodeWriter.put_temp_declarationsc                 C   s   |  tj |  d d S r  )r   r
   GENERATED_BY_MARKERr   r   r   r   put_generated_byT
  r  zCCodeWriter.put_generated_byc                 C   s    |  d|  |  d|  d S )Nz
#ifndef %sz
#define %sr   )r   guardr   r   r   put_h_guardX
  s   zCCodeWriter.put_h_guardc                 C   s   t jrd| S |S )Nzunlikely(%s))r   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   c                    s   g | ]} ||qS r   r   )rB  r<  mapperr   r   rG  e
  r~  z8CCodeWriter.build_function_modifiers.<locals>.<listcomp>)r   )r   	modifiersr  r   r  r   build_function_modifiersb
  s   z$CCodeWriter.build_function_modifiersc                 C   s.   |j }|js|j  r|j jrd|j S |jS )Nz(PyObject *))r   is_self_argis_completer  r  )r   r  r   r   r   r   entry_as_pyobjecti
  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_pyobjectq
  s   zCCodeWriter.as_pyobjectc                 C      | | | d S r   )generate_gotrefrM  r   r   r   
put_gotrefu
  r   zCCodeWriter.put_gotrefc                 C   r  r   )generate_giverefrM  r   r   r   put_giverefx
  r   zCCodeWriter.put_giverefc                 C   r  r   )generate_xgiverefrM  r   r   r   put_xgiveref{
  r   zCCodeWriter.put_xgiverefc                 C   r  r   )generate_xgotrefrM  r   r   r   put_xgotref~
  r   zCCodeWriter.put_xgotrefc                 C      |j | ||d d S N)r   )generate_increfr   r  r   r   r   r   r   
put_incref
  s   zCCodeWriter.put_increfc                 C   r  r   )generate_xincrefr"  r   r   r   put_xincref
  r^  zCCodeWriter.put_xincrefc                 C      |j | |||d d S N)r   have_gil)generate_decrefr   r  r   r   r(  r   r   r   
put_decref
     zCCodeWriter.put_decrefc                 C   r&  r'  )generate_xdecrefr*  r   r   r   put_xdecref
  r,  zCCodeWriter.put_xdecrefc                 C      |j | ||||d d S N)r  r   r(  )generate_decref_clearr   r  r   r  r   r(  r   r   r   put_decref_clear
     

zCCodeWriter.put_decref_clearc                 C   r/  r0  )generate_xdecref_clearr2  r   r   r   r&  
  r4  zCCodeWriter.put_xdecref_clearc                 C      | | || d S r   )generate_decref_setr   r  r   	rhs_cnamer   r   r   put_decref_set
  ru  zCCodeWriter.put_decref_setc                 C   r6  r   )generate_xdecref_setr8  r   r   r   put_xdecref_set
  ru  zCCodeWriter.put_xdecref_setc                 C   r  N)r(  )generate_incref_memoryviewslice)r   slice_cnamer   r(  r   r   r   put_incref_memoryviewslice
  s   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
  r^  zCCodeWriter.put_var_gotrefc                 C   rB  r   )r  r  r   r  r   r   r   put_var_giveref
  r^  zCCodeWriter.put_var_giverefc                 C   rB  r   )r  r  r   r  r   r   r   put_var_xgotref
  r^  zCCodeWriter.put_var_xgotrefc                 C   rB  r   )r  r  r   r  r   r   r   put_var_xgiveref
  r^  zCCodeWriter.put_var_xgiverefc                 K      | j |j|jfi | d S r   )r#  r  r   r   r  kwdsr   r   r   put_var_incref
     zCCodeWriter.put_var_increfc                 K   rG  r   )r%  r  r   rH  r   r   r   put_var_xincref
  rK  zCCodeWriter.put_var_xincrefc                 K   rG  r   )r+  r  r   rH  r   r   r   put_var_decref
  rK  zCCodeWriter.put_var_decrefc                 K   rG  r   )r.  r  r   rH  r   r   r   put_var_xdecref
  rK  zCCodeWriter.put_var_xdecrefc                 K   "   | j |j|jfd|ji| d S Nr  )r3  r  r   
in_closurerH  r   r   r   put_var_decref_clear
     "z CCodeWriter.put_var_decref_clearc                 K      | j |j|j|fi | d S r   )r:  r  r   r   r  r9  rI  r   r   r   put_var_decref_set
     zCCodeWriter.put_var_decref_setc                 K   rT  r   )r<  r  r   rU  r   r   r   put_var_xdecref_set
  rW  zCCodeWriter.put_var_xdecref_setc                 K   rO  rP  )r&  r  r   rQ  rH  r   r   r   put_var_xdecref_clear
  rS  z!CCodeWriter.put_var_xdecref_clearr   c                 C   s4   |D ]}|r	|j r|jr| | q| | qd S r   )r<  xdecref_cleanuprN  rM  )r   entries	used_onlyr  r   r   r   put_var_decrefs
  s   

zCCodeWriter.put_var_decrefsc                 C      |D ]}|  | qd S r   )rN  r   r[  r  r   r   r   put_var_xdecrefs
     zCCodeWriter.put_var_xdecrefsc                 C   r^  r   )rY  r_  r   r   r   put_var_xdecrefs_clear
  ra  z"CCodeWriter.put_var_xdecrefs_clearc                 C   sL   ddl m}m} |||d}|r| d||f  d S | d||f  d S )Nr   r  Py_Nonez%s = %s; __Pyx_INCREF(Py_None);z%s = %s; Py_INCREF(Py_None);)r"  r  r  r   )r   r  r   r   r  r  py_noner   r   r   put_init_to_py_none
  s
   zCCodeWriter.put_init_to_py_none%sc                 C   s2   ||j  }| ||j| |jr| d d S d S )Nrc  )r  re  r   rQ  r  )r   r  r  r   r   r   r   r   put_init_var_to_py_none
  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__fast_getattrPyCFunctionz(void(*)(void))(%s)%sz{%s, (PyCFunction)%s, %s, %s}%s|r2  r6  )
is_specialr  r!  ri  special_py_methodsis_binop_number_slotr  r/  r  method_flagsmethod_coexistput_pymethoddef_wrapper
func_cnamemethod_function_typeas_c_string_literalget_slot_tableget_slot_by_method_namepreprocessor_guard_coder   r   doc	doc_cname)r   r  term
allow_skipwrapper_code_writeris_number_slotri  rq  func_ptrcast
entry_nameslotpreproc_guardr   r   r   put_pymethoddef
  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  )
rt  rn  r  rq  ri  r  r   method_wrapper_prefixr   r  )r   r  rt  rq  r  	func_callr   r   r   rs    s   




z#CCodeWriter.put_pymethoddef_wrapperc                 C   s<   | j jd r| j tdd d S | j tdd d S )Nfast_gilFastGilr  	NoFastGil)r  r/  r  rc  rH  r   r   r   r   use_fast_gil_utility_code0  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.
        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/  Errorsr  r  r  rc  rH  r  r  r   )r   declare_gilstatevariabler  r   r   r   put_ensure_gil6  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_gilM  s   z#CCodeWriter.put_release_ensured_gilc                 C   ,   |  d |  dtj d |  d d S )N-#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADINGzPyMutex_Lock(&r  r6  r   r   parallel_freethreading_mutexr   r   r   r   put_acquire_freethreading_lockV     
z*CCodeWriter.put_acquire_freethreading_lockc                 C   r  )Nr  zPyMutex_Unlock(&r  r6  r  r   r   r   r   put_release_freethreading_lock[  r  z*CCodeWriter.put_release_freethreading_lockc                 C   sn   |    | d |r| d|  |r| d | d |r5| d | d |   | d dS 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if (_save) {Py_BLOCK_THREADSr  ##if CYTHON_COMPILING_IN_LIMITED_APIr6  N)r  r   r  r   r  unknown_gil_stater   r   r   put_acquire_gil`  s   




zCCodeWriter.put_acquire_gilc                 C   s   |    | d | d |r-| d |   | d | d | d | d | d |r9| d	 |rB| d
|  | d dS )z2Release the GIL, corresponds to `put_acquire_gil`.zPyThreadState *_save;z_save = NULL;r  r5  zif (PyGILState_Check())r6  r  Py_UNBLOCK_THREADSr  z%s = _save;z__Pyx_FastGIL_Remember();N)r  r   r  r  r   r   r   put_release_gilr  s    








zCCodeWriter.put_release_gilc                 C      |  d d S )Nz%PyGILState_STATE __pyx_gilstate_save;r  r   r   r   r   r    rG  zCCodeWriter.declare_gilstatec                 C   s   |  d|| |f S )Nzif (%s < 0) %s)r   r  )r   r	  r'  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 )
NNogilr!  RaiseClosureNameErrorRaiseCppGlobalNameErrorRaiseCppAttributeErrorRaiseUnboundLocalErrorr   z!if (unlikely(!%s)) { %s(%s); %s }__Pyx_)from_closurer   r.  
is_cglobalis_variable	is_memberr  is_c_class_scoper  r  rc  rH  check_for_null_coder  r   r  rv  r  )r   r	  r  in_nogil_contextunbound_check_code	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   )rs  r  r  ri  )r   r	  r<  r   r   r   set_error_info  s   zCCodeWriter.set_error_infoc                 C   sT   | j j}| j | |d u rd| S d| j _|rd| j _d| |d |d |f S )Nr  Tz__PYX_ERR(%s, %s, %s)r   r   )rs  r  r  r  r  ri  )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_if  r  zCCodeWriter.error_goto_ifc                 C      |  d| |S )Nz!%sr  r   r  r	  r   r   r   rc    r   zCCodeWriter.error_goto_if_nullc                 C   r  )Nz(%s < 0)r  r  r   r   r   error_goto_if_neg  s   zCCodeWriter.error_goto_if_negc                 C   s   |  d|S )NzPyErr_Occurred()r  r  r   r   r   r    rj  zCCodeWriter.error_goto_if_PyErrc                 C   r  r   )r  ri  )r   r   r   r   r   ri    rj  zCCodeWriter.lookup_filenamec                 C   r  )N__Pyx_RefNannyDeclarationsr  r   r   r   r   r    rG  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   )rv  r  r  rc  rH  r   )r   r  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    rK  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)rv  r   r  r  r  rs  r  r   )r   qualified_nameinclude_clineformat_tupler   r   r   put_add_traceback  s   zCCodeWriter.put_add_tracebackc                 C   sL   |t jt jt j| jjd |f}d| j_| d|  | j	t
dd dS )z
        Generate code to print a Python warning for an unraisable exception.

        qualified_name should be the qualified name of the function.
        unraisable_tracebacksTz0__Pyx_WriteUnraisable("%s", %s, %s, %s, %d, %d);WriteUnraisableExceptionzExceptions.cN)r   r  r  r  r  r/  rs  r  r   r  rc  rH  )r   r  r  r  r   r   r   put_unraisable  s   

zCCodeWriter.put_unraisablec                 C   s   | j jd p| j jd S )N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   )rs  r  node_positions_to_offsetparent_scope)r   r	  r  r   r   r   r    s
   zCCodeWriter.pos_to_offsetc                 C   r  )N__Pyx_TraceDeclarationsGen__Pyx_TraceDeclarationsFuncr  )r   is_generatorr   r   r   put_trace_declarations  rK  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 )N__Pyx_TraceStartGen__Pyx_TraceStartFuncr  r  r  r   ], r   r   r2  r  )r   rv  r   filetable_cnameri  r  skip_dispatch_cnamer  )r   r  r	  r  r  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"  rK  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  r  r  )rs  r  scope_classr	  r  rv  ri  r  r   r   r  r  )r   r	  r  
first_liner  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	  reraise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@  rK  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_unwindC  s   (zCCodeWriter.put_trace_unwindc              	   C   s2   |  |}| d| d| | d| d d S )Nz__Pyx_TraceStopIteration(r  r  r  )r   r	  r'  r  r   r   r   put_trace_stopiterationF  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!  __Pyx_TraceReturnValuerc  __Pyx_TraceReturnCValuer  r  r   r  )	r  r  is_void	is_stringto_py_functionr  r   r  r~   )r   r  r	  r  r  	extra_argr  rj  r   r   r   put_trace_returnJ  s    
<zCCodeWriter.put_trace_returnDefaultPlacementNewr%  c                 C   s"   | j | | d| d d S )Nz$__Pyx_default_placement_construct(&(z));)r  r  r   )r   r  _utility_coder   r   r   put_cpp_placement_newb  s   z!CCodeWriter.put_cpp_placement_newc                 C   s"   |  d |  | |  d d S )Nz#ifdef _OPENMPz#endif /* _OPENMP */r  )r   stringr   r   r   putln_openmpg  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)r6  Nr  r  r   r   r   undef_builtin_expectl  s   



z CCodeWriter.undef_builtin_expectc                 C   sD   |  d|  |  d |  d |  d |  d |  d d S )Nr  r  r  z2    #define likely(x)   __builtin_expect(!!(x), 1)z2    #define unlikely(x) __builtin_expect(!!(x), 0)r6  r  r  r   r   r   redef_builtin_expectx  s   



z CCodeWriter.redef_builtin_expect)NNF)NNTr   r  )TF)r!  Frr  )r!  NT)TT)FTTr?  )rf  T)TNNT)FNra  )FFFrk  )r   r   r   r   cythonr   r   r  r  r  r  r   r  r  r  r  r  rw  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  rc  r  r  r  r   r  r  r  r  r   r  r  r  r  r  r  r  rc  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.  r3  r&  r:  r<  r@  rA  rC  rD  rE  rF  rJ  rL  rM  rN  rR  rV  rX  rY  r]  r`  rb  re  rg  r  rs  r  r  r  r  r  r  r  r  r  r  r  r  r  rc  r  r  ri  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  x  sJ   
	











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 r  )r
   r  r   r  )r   outfile_namer   r   r   r     s   
zPyrexCodeWriter.__init__c                 C   s   | j dd| j |f  d S )Nz%s%s
r
  )r   r   r  r  r   r   r   r     rW  zPyrexCodeWriter.putlnc                 C   r  r  r  r   r   r   r   r    ru  zPyrexCodeWriter.indentc                 C   r  r  r  r   r   r   r   r=    ru  zPyrexCodeWriter.dedentN)r   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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   r}  r  original_levelrw  r   _insertion_points)r   r}  indent_levelrw  r   r   r   r   r     s   
zPyxCodeWriter.__init__r   c                 C   s   |  j |7  _ dS r  r  r   levelsr   r   r   r    s   zPyxCodeWriter.indentc                 C   s   |  j |8  _ d S r   r  r  r   r   r   r=    ru  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   rB  r   )r}  emptyr   r   r   r   r
    rp  zPyxCodeWriter.emptyc                 C   s$   | j  }t|tr|| j}|S r   )r}  r  r   r   r  r   )r   r9  r   r   r   r    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  )rw  r  r}  r   r  )r   r;  rw  r   r   r   r     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`  )rw  r  _indent_chunkr  r}  r   )r   chunkrw  r   r   r   	put_chunk  s   

zPyxCodeWriter.put_chunkc                 C   s   t | | j | j| jS r   )r   r}  r  r  rw  r   r   r   r   r    s   zPyxCodeWriter.insertion_pointc                 C   s   | j   | j| _d S r   )r}  resetr  r  r   r   r   r   r    s   
zPyxCodeWriter.resetc                 C   s   |   | j|< d S r   )r  r  r  r   r   r   named_insertion_point  ru  z#PyxCodeWriter.named_insertion_pointc                 C   r  r   )r  r  r   r   r   r    rp  zPyxCodeWriter.__getitem__)Nr   Nr|   )r   r   )r   r   r   r   r   r  r=  r   r	  r
  r  r   r  r  r  r  r  r   r   r   r   r    s    






	
r  r  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.
    	T)keependsr   r
  r  r   r   c                    s    g | ]}|d kr | nd qS )r  r   r  )
add_indentr   r   rG    s    z!_indent_chunk.<locals>.<listcomp>c                    s$   g | ]}|d kr| d nd qS )r  Nr   r  )startr   r   rG    s    r!  )r  r+  r   r   _count_indentationr   )r  r  r  	last_linemin_indentationr  r;  line_indentationr   )r  r  r   r    s>   




r  r   rv  c                 C   s(   d}t | D ]\}}|dkr |S q|S )Nr   r
  )r   )rv  r  chr   r   r   r    s   r  c                   @   s$   e Zd Zdd Zdd Zdd ZdS )rD  c                 C   s   || _ i | _i | _d| _d S r  )klassr  r  temps_count)r   r  r   r   r   r     rf  zClosureTempAllocator.__init__c                 C   s&   | j  D ]\}}t|| j|< qd S r   )r  r  r   r  )r   r   r.  r   r   r   r  !  s   zClosureTempAllocator.resetc                 C   s   || j vrg | j |< g | j|< n| j| r| j| dS dtj| jf }| jjd |||dd | j | | |  jd7  _|S )Nr   r  T)r	  r  r  r   is_cdefr   )	r  r  r1  r   r3  r  r  declare_varr2  )r   r   r  r   r   r   r:  %  s   


z"ClosureTempAllocator.allocate_tempN)r   r   r   r   r  r:  r   r   r   r   rD    s    rD  r   )Vr  declarer   r  r   r   r   r  r   r  r   	functoolsr   r   
contextlibr   r   collectionsr   r!  r   r   r   r	   r
   Scanningr   r   r  ctypedef_builtins_mapbasicsize_builtins_mapKNOWN_PYTHON_BUILTINS_VERSIONr   KNOWN_PYTHON_BUILTINSuncachable_builtinsro  r   r   r(  r   r   r-  r   r   r
  rc  r  r  r  r  r  r  r  r  r  rK  r  r  rH  rL  r   Ur,  rN  rO  r*  rP  findallrQ  rR  r`  r  rw  rx  r  r  r  finalccallr   r   r  	exceptvalcfuncr  rD  r   r   r   r   <module>   s@  " L

   )
	



	

"  ?      '
        K/	