o
    1&i                    @   sj  d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
Z
d dlmZ d dlmZmZmZmZmZmZmZ d dlmZ ejZejZejZedv rTejZG d	d
 d
eZ e  Z!e  Z"e  Z#e!j$Z%e"j$Z&e#j$Z'G dd deddZ(G dd deddZ)G dd deddZ*G dd deZ+G dd deZ,eddZ-G dd deZ.G dd dZ/dS )    )
namedtupleN)ir)Constant)
_helperlib)typesutilsconfigloweringcgutilsimputils	serialize)	PYVERSION))   
   )r      c                   @   s&   e Zd Zdd Zdd ZdddZdS )		_Registryc                 C   s
   i | _ d S N)	functionsself r   ?C:\wamp64\www\opt\env\Lib\site-packages\numba/core/pythonapi.py__init__      
z_Registry.__init__c                    s"   t tjsJ  fdd}|S )Nc                    s&    j v rtdf |  j < | S )Nzduplicate registration for %s)r   KeyError)funcr   	typeclassr   r   	decorator   s   

z%_Registry.register.<locals>.decorator)
issubclassr   Type)r   r   r   r   r   r   register   s   z_Registry.registerNc                 C   s<   t |tjsJ |jD ]}| j|}|d ur|  S q|S r   )r   r   r    __mro__r   get)r   r   defaultclsr   r   r   r   lookup&   s   
z_Registry.lookupr   )__name__
__module____qualname__r   r!   r&   r   r   r   r   r      s    	r   c                   @      e Zd ZdZdZdd ZdS )_BoxContextz<
    The facilities required by boxing implementations.
    r   c                 C      | j ||| jS r   pyapifrom_native_valueenv_managerr   typvalr   r   r   box>      z_BoxContext.boxN)r'   r(   r)   __doc__	__slots__r4   r   r   r   r   r+   7       r+   )contextbuilderr.   r0   c                   @   r*   )_UnboxContextz>
    The facilities required by unboxing implementations.
    r   c                 C   s   | j ||S r   )r.   to_native_value)r   r2   objr   r   r   unboxI      z_UnboxContext.unboxN)r'   r(   r)   r6   r7   r>   r   r   r   r   r;   B   r8   r;   )r9   r:   r.   c                   @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
_ReflectContextz@
    The facilities required by reflection implementations.
    r   c                 C   s   | j | jtj d S r   )r:   storeis_errorr
   Ztrue_bitr   r   r   r   	set_errorV   s   z_ReflectContext.set_errorc                 C   r,   r   r-   r1   r   r   r   r4   Y   r5   z_ReflectContext.boxc                 C   r,   r   )r.   reflect_native_valuer0   r1   r   r   r   reflect\   r5   z_ReflectContext.reflectN)r'   r(   r)   r6   r7   rC   r4   rE   r   r   r   r   r@   M   s    r@   )r9   r:   r.   r0   rB   c                   @   s   e Zd ZdZdddZdS )NativeValuez
    Encapsulate the result of converting a Python object to a native value,
    recording whether the conversion was successful and how to cleanup.
    Nc                 C   s$   || _ |d ur	|ntj| _|| _d S r   )valuer
   	false_bitrB   cleanup)r   rG   rB   rI   r   r   r   r   f   s   
zNativeValue.__init__NN)r'   r(   r)   r6   r   r   r   r   r   rF   `   s    rF   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )EnvironmentManagerc                 C   s,   t |tjsJ || _|| _|| _|| _d S r   )
isinstancer	   Environmentr.   envenv_bodyenv_ptr)r   r.   rN   rO   rP   r   r   r   r   n   s
   
zEnvironmentManager.__init__c                 C   sV   t |tr
t|}t| jjD ]\}}||u r |S qt| jj}| jj| |S )zF
        Add a constant to the environment, return its index.
        )	rL   strsysintern	enumeraterN   constslenappend)r   constindexr3   r   r   r   	add_constu   s   

zEnvironmentManager.add_constc              	   C   s   |t | jjk s
J | jj}| jj}tj|| jjdd}|	t
||B\}}| | j||}||| W d   n1 sBw   Y  | | jdd W d   n1 s[w   Y  W d   n1 sjw   Y  ||S )z
        Look up constant number *index* inside the environment body.
        A borrowed reference is returned.

        The returned LLVM value may have NULL value at runtime which indicates
        an error at runtime.
        TzfillNPyExc_RuntimeErrorz$`env.consts` is NULL in `read_const`)rV   rN   rU   r.   r:   rO   r
   alloca_oncepyobjif_elseis_not_nulllist_getitemrA   err_set_stringload)r   rY   r:   rU   retZbr_not_nullZbr_nullgetitemr   r   r   
read_const   s&   
zEnvironmentManager.read_constN)r'   r(   r)   r   rZ   rg   r   r   r   r   rK   l   s    rK   _IteratorLoop)rG   do_breakc                   @   s  e Zd ZdZdd Zdd Z		d]dd	Zd
d Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zd^dd Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zejd_d+d,Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd`d:d;Z d<d= Z!d>d? Z"d@dA Z#dBdC Z$dDdE Z%dFdG Z&dHdI Z'dJdK Z(dLdM Z)dNdO Z*dPdQ Z+dRdS Z,dTdU Z-dVdW Z.dXdY Z/dZd[ Z0d\d] Z1d^d_ Z2d_d`daZ3d_dbdcZ4d_dddeZ5d_dfdgZ6d_dhdiZ7d_djdkZ8d_dldmZ9d_dndoZ:d_dpdqZ;d_drdsZ<d_dtduZ=d_dvdwZ>d_dxdyZ?d_dzd{Z@d|d} ZAd~d ZBdd ZCdd ZDdd ZEdd ZFdd ZGdd ZHdd ZIdd ZJdd ZKdd ZLdd ZMdd ZNdd ZOdd ZPdd ZQdd ZRdd ZSdd ZTdd ZUdd ZVdd ZWdd ZXdd ZYd^ddZZdd Z[dd Z\dd Z]dd Z^dd Z_ejdd Z`dd Zadd Zbdd ZcddÄ Zdddń ZeddǄ ZfddɄ Zgdd˄ Zhdd̈́ ZidaddЄZjdbdd҄ZkddԄ Zlddք Zmdd؄ Znddڄ Zodd܄ Zpddބ Zqdd Zrdd Zsdd Ztdd Zudd Zvdd Zwdd Zxdd Zydd Zzdd Z{dd Z|dd Z}dd Z~dd Zdd Zdd Zd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dd Zdd Zdd Zdd Zdd Zdd  Zejd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd^d;d<Zd^d=d>Zd?d@ Zd^dAdBZdCdD ZdEdF ZdGdH ZdIdJ ZdKdL ZdMdN ZdOdP ZdQdR ZdSdT ZdUdV ZdWdX ZdYdZ Zd[d\ ZdS (c  	PythonAPIz^
    Code generation facilities to call into the CPython C API (and related
    helpers).
    c                 C   s>  || _ || _|jjj| _z| jj W n ty   i | j_Y nw | j tj	| _
| j
 | _ttd| _tttjd | _| j| _tttjd | _| j| _t | _tjrh| j tj| _n| j tj | _ttd| _!tt"j#d | _$t%tdt"j&| _'| j| _(t"j)| _)t"j*| _*t"j+| _+dS )zL
        Note: Maybe called multiple times when lowering a function
           N),r9   r:   Zbasic_blockfunctionmodule_PythonAPI__serializedAttributeErrorZget_argument_typer   pyobjectr_   
as_pointerpyobjptrr   PointerTypeIntTypevoidptrctypessizeofc_longlongulongc_ulonglonglonglong	ulonglong
DoubleTypedoubler   ZUSE_LEGACY_TYPE_SYSTEMget_value_typeintp
py_ssize_tZc_intpcstringr   Zpy_gil_state_size	gil_state	ArrayTypeZpy_buffer_sizepy_buffer_t	py_hash_tpy_unicode_1byte_kindpy_unicode_2byte_kindpy_unicode_4byte_kind)r   r9   r:   r   r   r   r      s4   
zPythonAPI.__init__c                 C   s   t | |||S r   )rK   )r   rN   rO   rP   r   r   r   get_env_manager   r?   zPythonAPI.get_env_managerF c                 C   s   t | j|}t | j|A |r1| jjjj}|j| jksJ | 	dd|  | j
|   n| jj| jtd| f W d   dS W d   dS 1 sRw   Y  dS )z;Emits LLVM code to ensure the `envptr` is not NULL
        r]   zmissing Environment: N)r
   is_nullr:   Zif_unlikelyrl   typepointeereturn_typer_   rc   re   get_null_objectr9   	call_convZreturn_user_excRuntimeError)r   ZenvptrZreturn_pyobjectZ	debug_msgr   fntyr   r   r   emit_environment_sentry   s    

"z!PythonAPI.emit_environment_sentryc                 C   6   t t  | jg}| j|dd}| j||g d S )NZ	Py_IncRefnamer   FunctionTypeVoidTyper_   _get_functionr:   callr   r=   r   fnr   r   r   incref      zPythonAPI.increfc                 C   r   )NZ	Py_DecRefr   r   r   r   r   r   decref   r   zPythonAPI.decrefc                 C   0   t | j| jg}| j|dd}| j||gS )NZnumba_py_typer   r   r   r_   r   r:   r   r   r   r   r   get_type      zPythonAPI.get_typec                 G   sl   t t d}t |}| j| j||g}t jt d|dd}	| j|	dd}
| j|
||||gt| S )Nrk       TZvar_argZPyArg_ParseTupleAndKeywordsr   	r   rs   rt   r_   r   r   r:   r   list)r   argskwsfmtkeywordsobjscharptrZ
charptraryargtypesr   r   r   r   r   parse_tuple_and_keywords   s   
z"PythonAPI.parse_tuple_and_keywordsc                 G   sX   t t d}| j|g}t jt d|dd}| j|dd}| j|||gt| S )Nrk   r   Tr   ZPyArg_ParseTupler   r   )r   r   r   r   r   r   r   r   r   r   r   parse_tuple  s
   
zPythonAPI.parse_tuplec           
      G   s   t t d}| j|| j| jg}t jt d|dd}| j|dd}	t| jt|}t| jt|}t	|t
rA| j| jj|}| j|	||||gt| S )Nrk   r   Tr   ZPyArg_UnpackTupler   )r   rs   rt   r_   r   r   r   r   intrL   rQ   r9   insert_const_stringr:   rm   r   r   )
r   r   r   Zn_minZn_maxr   r   r   r   r   r   r   r   unpack_tuple
  s   
zPythonAPI.unpack_tuplec                 C   s*   t | jd}| j|dd}| j|dS )Nr   ZPyErr_Occurredr   r   r   r   r   r   r   r   err_occurred  s   zPythonAPI.err_occurredc                 C   s,   t t  d}| j|dd}| j|dS )Nr   ZPyErr_Clearr   )r   r   r   r   r:   r   r   r   r   r   	err_clear  s   zPythonAPI.err_clearc                 C   sf   t t  | j| jg}| j|dd}t|tr| |}t|tr*| j	
| j|}| j|||fS )NZPyErr_SetStringr   )r   r   r   r_   r   r   rL   rQ   get_c_objectr9   r   rm   r:   r   )r   exctypemsgr   r   r   r   r   rc   #  s   


zPythonAPI.err_set_stringc                 G   sr   t jt  | j| jgdd}| j|dd}t|tr| |}t|tr,| j	
| j|}| j|||ft| S )NTr   ZPyErr_Formatr   )r   r   r   r_   r   r   rL   rQ   r   r9   r   rm   r:   r   tuple)r   r   r   Zformat_argsr   r   r   r   r   
err_format,  s   


zPythonAPI.err_formatNc                 C   sB   t t  | jg}| j|dd}|du r|  }| j||fS )z
        Raise an arbitrary exception (type or value or (type, args)
        or None - if reraising).  A reference to the argument is consumed.
        Znumba_do_raiser   N)r   r   r   r_   r   	make_noner:   r   )r   excr   r   r   r   r   raise_object5  s
   zPythonAPI.raise_objectc                 C   sL   t t  | j| jg}| j|dd}t|tr| |}| j	|||fS )NZPyErr_SetObjectr   
r   r   r   r_   r   rL   rQ   r   r:   r   )r   r   Zexcvalr   r   r   r   r   err_set_object@  s
   

zPythonAPI.err_set_objectc                 C   sF   t t  | jg}| j|dd}t|tr| |}| j	||fS )NZPyErr_SetNoner   r   )r   r   r   r   r   r   r   err_set_noneG  s
   

zPythonAPI.err_set_nonec                 C   2   t t  | jg}| j|dd}| j||fS )NZPyErr_WriteUnraisabler   r   r   r   r   r   err_write_unraisableN     zPythonAPI.err_write_unraisablec                 C   :   t t  | jgd }| j|dd}| j||||fS )Nr   ZPyErr_Fetchr   )r   r   r   rr   r   r:   r   )r   ptypvalptbr   r   r   r   r   	err_fetchS     zPythonAPI.err_fetchc                 C   r   )Nr   ZPyErr_Restorer   r   )r   tyr3   tbr   r   r   r   r   err_restoreX  r   zPythonAPI.err_restorec              	   #   s<    fddt dD \}}} ||| dV   j|} j|} j|}|rt j  } jj|ddM\}	}
|	  |  |  | W d   n1 s]w   Y  |
  	||| W d   n1 svw   Y  W d   dS W d   dS 1 sw   Y  dS  	||| dS )a  
        Temporarily push the current error indicator while the code
        block is executed.  If *keep_new* is True and the code block
        raises a new error, the new error is kept, otherwise the old
        error indicator is restored at the end of the block.
        c                    s   g | ]
}t  j jqS r   )r
   r^   r:   r_   ).0ir   r   r   
<listcomp>e  s    z&PythonAPI.err_push.<locals>.<listcomp>r   NFZlikely)
ranger   r:   rd   r
   ra   r   r`   r   r   )r   Zkeep_newr   r   r   r   r3   r   Z	new_errorZif_errorZif_okr   r   r   err_push]  s0   


"
zPythonAPI.err_pushc                 C   s   | j j| j| jj|ddS )z
        Get a Python object through its C-accessible *name*
        (e.g. "PyExc_ValueError").  The underlying variable must be
        a `PyObject *`, and the value of that pointer is returned.
        T)Z	dllimport)r9   Zget_c_valuer:   r_   r   )r   r   r   r   r   r   z  s   zPythonAPI.get_c_objectc                 C   (   d| }| j | j|}| d| d S )Nzglobal name '%s' is not definedPyExc_NameErrorr9   r   rm   rc   r   r   r   cstrr   r   r   raise_missing_global_error     z$PythonAPI.raise_missing_global_errorc                 C   r   )Nzname '%s' is not definedr   r   r   r   r   r   raise_missing_name_error  r   z"PythonAPI.raise_missing_name_errorc                 C   sR   t t  | jg}| j|dd}|jd | j| j	|}| j
||f d S )NZPy_FatalErrorr   Znoreturn)r   r   r   r   r   
attributesaddr9   r   rm   r:   r   )r   r   r   r   r   r   r   r   fatal_error  s
   zPythonAPI.fatal_errorc                 C   sF   t | j| j| jg}| j|dd}| j| j|}| j	|||gS )FLookup name inside dict

        Returns a borrowed reference
        ZPyDict_GetItemStringr   )
r   r   r_   r   r   r9   r   rm   r:   r   )r   dicr   r   r   r   r   r   r   dict_getitem_string  s   zPythonAPI.dict_getitem_stringc                 C   6   t | j| j| jg}| j|dd}| j|||gS )r   ZPyDict_GetItemr   r   )r   r   r   r   r   r   r   r   dict_getitem  s   zPythonAPI.dict_getitemr   c                 C   sn   |dkrt | jd}| j|dd}| j|dS t | j| jg}| j|dd}| j|t| jt|gS )Nr   r   Z
PyDict_Newr   Z_PyDict_NewPresized)	r   r   r_   r   r:   r   r   r   r   )r   Zpresizer   r   r   r   r   dict_new  s   zPythonAPI.dict_newc                 C   s@   t t d| j| j| jf}| j|dd}| j||||fS )Nr   ZPyDict_SetItemr   r   r   rt   r_   r   r:   r   )r   dictobjZnameobjvalobjr   r   r   r   r   dict_setitem  s
   zPythonAPI.dict_setitemc                 C   sP   t t d| j| j| jf}| j|dd}| j| j|}| j	
||||fS )Nr   ZPyDict_SetItemStringr   )r   r   rt   r_   r   r   r9   r   rm   r:   r   )r   r   r   r   r   r   r   r   r   r   dict_setitem_string  s   zPythonAPI.dict_setitem_stringc                 C   sT   |   }| | |D ]\}}| ||| qW d   |S 1 s#w   Y  |S )zb
        Args
        -----
        keyvalues: iterable of (str, llvm.Value of PyObject*)
        N)r   if_object_okr   )r   Z	keyvaluesr   kvr   r   r   	dict_pack  s   
zPythonAPI.dict_packc                 C   0   t | j| jg}| j|dd}| j||gS )NZPyFloat_FromDoubler   )r   r   r_   r   r   r:   r   )r   Zfvalr   r   r   r   r   float_from_double  r   zPythonAPI.float_from_doublec                 C   s@   t | j| j| jg}| j|dd}| d}| j|||gS )NZPyNumber_AsSsize_tr   ZPyExc_OverflowError)r   r   r   r_   r   r   r:   r   )r   numobjr   r   	exc_classr   r   r   number_as_ssize_t  s   
zPythonAPI.number_as_ssize_tc                 C   r   )NZPyNumber_Longr   r   r   r   r   r   r   r   r   number_long  r   zPythonAPI.number_longc                 C   r   )NZPyLong_AsUnsignedLongLongr   r   r   r}   r_   r   r:   r   r   r   r   r   long_as_ulonglong  r   zPythonAPI.long_as_ulonglongc                 C   r   )NZPyLong_AsLongLongr   r   r   r   r   r   long_as_longlong  r   zPythonAPI.long_as_longlongc                 C   r   )z
        Convert the given Python integer to a void*.  This is recommended
        over number_as_ssize_t as it isn't affected by signedness.
        ZPyLong_AsVoidPtrr   r   r   ru   r_   r   r:   r   r   r   r   r   long_as_voidptr  s   zPythonAPI.long_as_voidptrc                 C   sb   t | j|g}| j||d}t| j| j}| j||d}| j| j||g| | j	|S )Nr   )
r   r   r_   r   r
   r^   r:   rA   r   rd   )r   ival	func_nameZnative_int_typesignedr   r   Zresptrr   r   r   _long_from_native_int  s   zPythonAPI._long_from_native_intc                 C   s4   d}t | j| jg}| j||d}| j||gS )NZPyLong_FromLongr   r   r   r_   ry   r   r:   r   )r   r   r   r   r   r   r   r   long_from_long  s   zPythonAPI.long_from_longc                 C      | j |d| jddS )NZPyLong_FromUnsignedLongFr   )r   ry   r   r   r   r   r   long_from_ulong	     zPythonAPI.long_from_ulongc                 C   r  )NZPyLong_FromSsize_tTr  )r   r   r  r   r   r   long_from_ssize_t  r  zPythonAPI.long_from_ssize_tc                 C   r  )NZPyLong_FromLongLongTr  )r   r|   r  r   r   r   long_from_longlong  r  zPythonAPI.long_from_longlongc                 C   r  )NZPyLong_FromUnsignedLongLongFr  )r   r}   r  r   r   r   long_from_ulonglong  r  zPythonAPI.long_from_ulonglongc                 C   X   |j j}|| jjkr| | j|| jS || jjkr&| | j|| jS td| )zH
        Return a Python integer from any native integer value.
        integer too big (%d bits))	r   widthry   r  r:   Zsextr|   r	  OverflowErrorr   r   bitsr   r   r   long_from_signed_int     zPythonAPI.long_from_signed_intc                 C   r  )zH
        Same as long_from_signed_int, but for unsigned values.
        r  )	r   r  rz   r  r:   zextr}   r
  r  r  r   r   r   long_from_unsigned_int%  r  z PythonAPI.long_from_unsigned_intc                 C   s,   t | j| j| jg}| j|d| d}|S )NzPyNumber_%sr   )r   r   r_   r   )r   r   r   r   r   r   r   _get_number_operator1  s   zPythonAPI._get_number_operatorc                 C   s(   |rd| }|  |}| j|||gS )NZInPlace)r  r:   r   )r   r   lhsrhsinplacer   r   r   r   _call_number_operator6  s   
zPythonAPI._call_number_operatorc                 C      | j d|||dS )NAddr  r  r   r  r  r  r   r   r   
number_add<  r5   zPythonAPI.number_addc                 C   r  )NZSubtractr  r  r  r   r   r   number_subtract?  r5   zPythonAPI.number_subtractc                 C   r  )NZMultiplyr  r  r  r   r   r   number_multiplyB  r5   zPythonAPI.number_multiplyc                 C   r  )NZ
TrueDivider  r  r  r   r   r   number_truedivideE  r5   zPythonAPI.number_truedividec                 C   r  )NZFloorDivider  r  r  r   r   r   number_floordivideH  r5   zPythonAPI.number_floordividec                 C   r  )NZ	Remainderr  r  r  r   r   r   number_remainderK  r5   zPythonAPI.number_remainderc                 C   r  )NZMatrixMultiplyr  r  r  r   r   r   number_matrix_multiplyN  r5   z PythonAPI.number_matrix_multiplyc                 C   r  )NZLshiftr  r  r  r   r   r   number_lshiftQ  r5   zPythonAPI.number_lshiftc                 C   r  )NZRshiftr  r  r  r   r   r   number_rshiftT  r5   zPythonAPI.number_rshiftc                 C   r  )NAndr  r  r  r   r   r   
number_andW  r5   zPythonAPI.number_andc                 C   r  )NOrr  r  r  r   r   r   	number_orZ  r5   zPythonAPI.number_orc                 C   r  )NZXorr  r  r  r   r   r   
number_xor]  r5   zPythonAPI.number_xorc                 C   sF   t | j| jgd }|rdnd}| ||}| j||||  gS )Nr   ZPyNumber_InPlacePowerZPyNumber_Power)r   r   r_   r   r:   r   borrow_none)r   r  r  r  r   fnamer   r   r   r   number_power`  s   zPythonAPI.number_powerc                 C   0   t | j| jg}| j|dd}| j||fS )NZPyNumber_Negativer   r   r   r   r   r   number_negativef  r   zPythonAPI.number_negativec                 C   r0  )NZPyNumber_Positiver   r   r   r   r   r   number_positivek  r   zPythonAPI.number_positivec                 C   r   )NZPyNumber_Floatr   r   )r   r3   r   r   r   r   r   number_floatp  r   zPythonAPI.number_floatc                 C   r0  )NZPyNumber_Invertr   r   r   r   r   r   number_invertu  r   zPythonAPI.number_invertc                 C   r   )NZPyFloat_AsDoubler   )r   r   r   r_   r   r:   r   )r   Zfobjr   r   r   r   r   float_as_doublez  r   zPythonAPI.float_as_doublec                 C   s   | j || j}| |S )z8
        Get a Python bool from a LLVM boolean.
        )r:   r  ry   bool_from_long)r   ZbvalZlongvalr   r   r   bool_from_bool  s   
zPythonAPI.bool_from_boolc                 C   r   )NZPyBool_FromLongr   r  )r   r   r   r   r   r   r   r6    r   zPythonAPI.bool_from_longc                 C   s:   t | jt  t  g}| j|dd}| j|||gS )NZPyComplex_FromDoublesr   )r   r   r_   r~   r   r:   r   )r   ZrealvalZimagvalr   r   r   r   r   complex_from_doubles     zPythonAPI.complex_from_doublesc                 C   2   t t  | jg}| j|dd}| j||gS )NZPyComplex_RealAsDoubler   r   r   r~   r_   r   r:   r   r   cobjr   r   r   r   r   complex_real_as_double  r   z PythonAPI.complex_real_as_doublec                 C   r:  )NZPyComplex_ImagAsDoubler   r;  r<  r   r   r   complex_imag_as_double  r   z PythonAPI.complex_imag_as_doublec                 C   s   t | j| j}t | j| j}t | j| j}ttd| jg| j gd  }| j	|dd}| j
|||||f}| j|}| j|}	| j|}
t | j|||	|
fS )z
        Read the members of a slice of integers.

        Returns a (ok, start, stop, step) tuple where ok is a boolean and
        the following members are pointer-sized ints.
        r   r   Znumba_unpack_slicer   )r
   r^   r:   r   r   r   rt   r_   rq   r   r   rd   r   )r   r=   ZpstartZpstopZpstepr   r   resstartstopstepr   r   r   slice_as_ints  s   zPythonAPI.slice_as_intsc                 C   s<   t | j| j| j| jg}| j|dd}| j||||fS )NZPySequence_GetSlicer   r   r   r_   r   r   r:   r   )r   r=   rA  rB  r   r   r   r   r   sequence_getslice  s
   zPythonAPI.sequence_getslicec                 C   r   )NZPySequence_Tupler   r   r   r   r   r   sequence_tuple  r   zPythonAPI.sequence_tuplec                 C   r   )NZPySequence_Concatr   r   )r   Zobj1obj2r   r   r   r   r   sequence_concat     zPythonAPI.sequence_concatc                 C   r   )NZ
PyList_Newr   rE  )r   Zszvalr   r   r   r   r   list_new  r   zPythonAPI.list_newc                 C   r   )NZPyList_Sizer   r   r   r   r_   r   r:   r   )r   lstr   r   r   r   r   	list_size  r   zPythonAPI.list_sizec                 C   :   t t d| j| jg}| j|dd}| j|||gS )Nr   ZPyList_Appendr   r   )r   rM  r3   r   r   r   r   r   list_append  r9  zPythonAPI.list_appendc                 C   s@   t t d| j| j| jg}| j|dd}| j||||gS )z6
        Warning: Steals reference to ``val``
        r   ZPyList_SetItemr   r   r   rt   r_   r   r   r:   r   )r   rM  idxr3   r   r   r   r   r   list_setitem  s
   zPythonAPI.list_setitemc                 C   sP   t | j| j| jg}| j|dd}t|tr| jt	j
|}| j|||gS )z/
        Returns a borrowed reference.
        ZPyList_GetItemr   )r   r   r_   r   r   rL   r   r9   get_constantr   r   r:   r   )r   rM  rR  r   r   r   r   r   rb     s
   
zPythonAPI.list_getitemc                 C   sV   |d u r|   }ttd| j| j| j| jg}| j|dd}| j|||||fS )Nr   ZPyList_SetSlicer   )	r   r   r   rt   r_   r   r   r:   r   )r   rM  rA  rB  r=   r   r   r   r   r   list_setslice  s   zPythonAPI.list_setslicec                 C   sF   t | j| j| jg}| j|dd}| jtj|}| j	
|||gS )z"
        Borrow reference
        ZPyTuple_GetItemr   )r   r   r_   r   r   r9   rT  r   r   r:   r   )r   tuprR  r   r   r   r   r   tuple_getitem  s   zPythonAPI.tuple_getitemc                 C   sV   t j| j| jgdd}| j|dd}| jtjt	|}|g}|
| | j||S )NTr   ZPyTuple_Packr   )r   r   r_   r   r   r9   rT  r   r   rV   extendr:   r   )r   itemsr   r   nr   r   r   r   
tuple_pack  s   
zPythonAPI.tuple_packc                 C   r   )NZPyTuple_Sizer   rL  )r   rV  r   r   r   r   r   
tuple_size  r   zPythonAPI.tuple_sizec                 C   s6   t | j| jg}| j|dd}| j|| |gS )NZPyTuple_Newr   rE  )r   countr   r   r   r   r   	tuple_new	  s   zPythonAPI.tuple_newc                 C   sN   t t d| j| j| jg}| j|dd}| |}| j||||g dS )z/
        Steals a reference to `item`.
        r   ZPyTuple_SetItemr   NrQ  )r   Z	tuple_valrY   itemr   Z
setitem_fnr   r   r   tuple_setitem  s   
zPythonAPI.tuple_setitemc                 C   s@   |d u r|   }t| j| jg}| j|dd}| j||gS )NZ	PySet_Newr   )r   r   r   r_   r   r:   r   )r   iterabler   r   r   r   r   set_new  s
   zPythonAPI.set_newc                 C   rO  )Nr   Z	PySet_Addr   r   )r   setrG   r   r   r   r   r   set_add#  r9  zPythonAPI.set_addc                 C   4   t t d| jg}| j|dd}| j||gS )Nr   ZPySet_Clearr   r   r   rc  r   r   r   r   r   	set_clear(     zPythonAPI.set_clearc                 C   r   )NZ
PySet_Sizer   rL  rf  r   r   r   set_size-  r   zPythonAPI.set_sizec                 C   rO  )Nr   Z_PySet_Updater   r   )r   rc  ra  r   r   r   r   r   
set_update2  r9  zPythonAPI.set_updatec                 C   sR   t t d| j| j | j | j g}| j|dd}| j	|||||fS )Nr   Z_PySet_NextEntryr   )
r   r   rt   r_   r   rq   r   r   r:   r   )r   rc  posptrkeyptrhashptrr   r   r   r   r   set_next_entry7  s   zPythonAPI.set_next_entryc           	   	   #   s   | j tj| jdd}tj| jdd}tjt| jddd}d}d 	|  fdd	}
|@ | ||||}t|}j|d
d 	  W d    n1 scw   Y  t||V  	| W d    n1 sw   Y    d S )Nrm  r   rl  r   rk  bb_bodybb_endc                      s      d S r   )branchr   rp  r:   r   r   ri   L  r?   z'PythonAPI.set_iterate.<locals>.do_breakFr   )r:   r
   r^   r   r_   alloca_once_valuer   r   append_basic_blockrq  Z
goto_blockrn  r   if_thenrh   rd   position_at_end)	r   rc  rm  rl  rk  ro  ri   rfinishedr   rr  r   set_iterate>  s,   



zPythonAPI.set_iteratec                 C   sN   t | j}t t  |g}| |d}t| j| j}| j	||g |S )zk
        Ensure the GIL is acquired.
        The returned value must be consumed by gil_release().
        Znumba_gil_ensure)
r   rs   r   r   r   r   r
   r^   r:   r   )r   gilptrtyr   r   Zgilptrr   r   r   
gil_ensure]  s   zPythonAPI.gil_ensurec                 C   s:   t | j}t t  |g}| |d}| j||gS )zg
        Release the acquired GIL by gil_ensure().
        Must be paired with a gil_ensure().
        Znumba_gil_release)r   rs   r   r   r   r   r:   r   )r   Zgilrz  r   r   r   r   r   gil_releasei  s   zPythonAPI.gil_releasec                 C   s*   t | jg }| j|dd}| j|g S )zj
        Release the GIL and return the former thread state
        (an opaque non-NULL pointer).
        ZPyEval_SaveThreadr   )r   r   ru   r   r:   r   r   r   r   r   save_threads  s   zPythonAPI.save_threadc                 C   s6   t t  | jg}| j|dd}| j||g dS )zH
        Restore the given thread state by reacquiring the GIL.
        ZPyEval_RestoreThreadr   N)r   r   r   ru   r   r:   r   )r   Zthread_stater   r   r   r   r   restore_thread|  s   zPythonAPI.restore_threadc                 C   s0   t | j| jg}| j|dd}| j||fS )NZnumba_get_pyobject_private_datar   r   r   r   r   r   object_get_private_data  r   z!PythonAPI.object_get_private_datac                 C   s8   t t  | j| jg}| j|dd}| j|||fS )NZnumba_set_pyobject_private_datar   )r   r   r   r_   ru   r   r:   r   )r   r=   ptrr   r   r   r   r   object_set_private_data  s   z!PythonAPI.object_set_private_datac                 C   r   )NZ!numba_reset_pyobject_private_datar   r   r   r   r   r   object_reset_private_data  r   z#PythonAPI.object_reset_private_datac                 C   r   )NZPyImport_ImportModuler   r   r   r_   r   r   r:   r   )r   modnamer   r   r   r   r   import_module  r   zPythonAPI.import_modulec                 C   sT   t j| j| jgdd}| j|dd}|gt| }|| jtj	 | j
||S )NTr   ZPyObject_CallFunctionObjArgsr   )r   r   r_   r   r   rW   r9   get_constant_nullr   rp   r:   r   )r   calleeobjargsr   r   r   r   r   r   call_function_objargs  s
   zPythonAPI.call_function_objargsr   c           
      C   s   | j | j|}tj| j| j| j| jgdd}| j|dd}dt| }| j | j|}|||g}	|r8|		| |	
| j tj | j||	S )NTr   ZPyObject_CallMethodr   O)r9   r   rm   r   r   r_   r   r   rV   rX  rW   r  r   rp   r:   r   )
r   r  methodr  cnamer   r   r   Zcfmtr   r   r   r   call_method  s   

zPythonAPI.call_methodc                 C   sp   |d u  }r|  d}|d u r|  }t| j| jgd }| j|dd}| j||||f}|r6| | |S )Nr   r   ZPyObject_Callr   )	r^  r   r   r   r_   r   r:   r   r   )r   r  r   r   Zargs_was_noner   r   resultr   r   r   r     s   

zPythonAPI.callc                 C   r0  )zJEmit a call to ``PyObject_Type(obj)`` to get the type of ``obj``.
        ZPyObject_Typer   r   r   r   r   r   object_type  s   zPythonAPI.object_typec                 C   re  )Nr   ZPyObject_IsTruer   r   r   r   r   r   object_istrue  rh  zPythonAPI.object_istruec                 C   re  )Nr   ZPyObject_Notr   r   r   r   r   r   
object_not  rh  zPythonAPI.object_notc                 C   s  g d}||v r5| |}t| j| j| jtdg}| j|dd}| jtj	|}| j
||||fS |dkrF| j
d||}	| |	S |dkrW| j
d||}	| |	S |d	v rttd| j| jg}| j|d
d}| j
|||f}
| jtj	d}| j
d|
|}t| j
t| jd}t| j
|& |dkr| j
|
}
| j
|
td}| j
| || W d   n1 sw   Y  | j
|S tdj|d)zd
        Refer to Python source Include/object.h for macros definition
        of the opid.
        )<z<===!=>z>=r   ZPyObject_RichComparer   isr  zis notr  )innot inZPySequence_ContainsNr     zUnknown operator {op!r})op)rY   r   r   r_   rt   r   r9   rT  r   int32r:   r   icmp_unsignedr7  r
   rs  r   	if_likelynot_truncrA   rd   NotImplementedErrorformat)r   r  r  ZopstropsZopidr   r   ZlopidZbitflagstatusZnegoneZis_goodZoutptr	truncatedr   r   r   object_richcompare  sD   



zPythonAPI.object_richcomparec                 C   r   )NZPyIter_Nextr   r   )r   Ziterobjr   r   r   r   r   	iter_next  r   zPythonAPI.iter_nextc                 C   r   )NZPyObject_GetIterr   r   r   r   r   r   object_getiter  r   zPythonAPI.object_getiterc                 C   sF   | j | j|}t| j| j| jg}| j|dd}| j	|||gS )NZPyObject_GetAttrStringr   )
r9   r   rm   r   r   r_   r   r   r:   r   )r   r=   attrr   r   r   r   r   r   object_getattr_string  s   zPythonAPI.object_getattr_stringc                 C   r   )NZPyObject_GetAttrr   r   )r   r=   r  r   r   r   r   r   object_getattr  rJ  zPythonAPI.object_getattrc                 C   sP   | j | j|}ttd| j| j| jg}| j|dd}| j	
||||gS )Nr   ZPyObject_SetAttrStringr   )r9   r   rm   r   r   rt   r_   r   r   r:   r   )r   r=   r  r3   r   r   r   r   r   r   object_setattr_string  s   zPythonAPI.object_setattr_stringc                 C   s@   t t d| j| j| jg}| j|dd}| j||||gS )Nr   ZPyObject_SetAttrr   r   )r   r=   r  r3   r   r   r   r   r   object_setattr  s   zPythonAPI.object_setattrc                 C      |  |||  S r   )r  r   r   r=   r  r   r   r   object_delattr_string     zPythonAPI.object_delattr_stringc                 C   r  r   )r  r   r  r   r   r   object_delattr!  r  zPythonAPI.object_delattrc                 C   s6   t | j| j| jg}| j|dd}| j|||fS )z!
        Return obj[key]
        ZPyObject_GetItemr   r   r   r=   keyr   r   r   r   r   object_getitem&  s   zPythonAPI.object_getitemc                 C   s@   t t d| j| j| jg}| j|dd}| j||||fS )z 
        obj[key] = val
        r   ZPyObject_SetItemr   r   )r   r=   r  r3   r   r   r   r   r   object_setitem.  s   zPythonAPI.object_setitemc                 C   s:   t t d| j| jg}| j|dd}| j|||fS )z
        del obj[key]
        r   ZPyObject_DelItemr   r   r  r   r   r   object_delitem6  s   zPythonAPI.object_delitemc                 C   4   t | j| jg}d}| j||d}| j||gS )NZPyUnicode_AsUTF8r   r   r   r   r_   r   r:   r   )r   strobjr   r.  r   r   r   r   string_as_string>     zPythonAPI.string_as_stringc                 C   sx   t | j| j}t| j| j| j g}d}| j	||d}| j
|||g}| jdt|jd|}||| j|fS )z
        Returns a tuple of ``(ok, buffer, length)``.
        The ``ok`` is i1 value that is set if ok.
        The ``buffer`` is a i8* of the output buffer.
        The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
        ZPyUnicode_AsUTF8AndSizer   r  N)r
   r^   r:   r   r   r   r   r_   rq   r   r   r  r   r   rd   )r   r  p_lengthr   r.  r   bufferokr   r   r   string_as_string_and_sizeD  s   
z#PythonAPI.string_as_string_and_sizec              	   C   s   t | j| j}t | jtd}t | jtd}t | j| j}t| j| j	| j
 td
 td
 | j
 g}d}| j||d}| j||||||g}	| jdt|	jd|	}
|
|	| j|| j|| j|| j|fS )a  
        Returns a tuple of ``(ok, buffer, length, kind)``.
        The ``ok`` is i1 value that is set if ok.
        The ``buffer`` is a i8* of the output buffer.
        The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
        The ``kind`` is a i32 (int32) of the Unicode kind constant
        The ``hash`` is a long/uint64_t (py_hash_t) of the Unicode constant hash
        r   Znumba_extract_unicoder   r  N)r
   r^   r:   r   r   rt   r   r   r   r_   rq   r   r   r  r   r   rd   )r   r  r  Zp_kindZp_asciiZp_hashr   r.  r   r  r  r   r   r   string_as_string_size_and_kindX  s.   	

z(PythonAPI.string_as_string_size_and_kindc                 C   :   t | j| j| jg}d}| j||d}| j|||gS )NZPyString_FromStringAndSizer   r   r   r_   r   r   r   r:   r   r   stringsizer   r.  r   r   r   r   string_from_string_and_sizev     z%PythonAPI.string_from_string_and_sizec                 C   r  )NZPyUnicode_FromStringr   r  )r   r  r   r.  r   r   r   r   string_from_string|  r  zPythonAPI.string_from_stringc                 C   sD   t | jt d| j| jg}d}| j||d}| j||||gS )Nr   ZPyUnicode_FromKindAndDatar   )	r   r   r_   rt   r   r   r   r:   r   )r   kindr  r  r   r.  r   r   r   r   string_from_kind_and_data  s   z#PythonAPI.string_from_kind_and_datac                 C   r  )NZPyBytes_AsStringr   r  r   r=   r   r.  r   r   r   r   bytes_as_string  r  zPythonAPI.bytes_as_stringc           	      C   sh   t t d| j| j | j g}d}| j||d}| j	||||g}| j
dt|jd|}|S )Nr   ZPyBytes_AsStringAndSizer   r  r  )r   r   rt   r_   r   rq   r   r   r:   r   Zicmp_signedr   r   )	r   r=   Zp_bufferr  r   r.  r   r  r  r   r   r   bytes_as_string_and_size  s   z"PythonAPI.bytes_as_string_and_sizec                 C   r  )NZPyBytes_FromStringAndSizer   r  r  r   r   r   bytes_from_string_and_size  r  z$PythonAPI.bytes_from_string_and_sizec                 C   r  )NZPyObject_Hashr   )r   r   r   r_   r   r:   r   r  r   r   r   object_hash  r  zPythonAPI.object_hashc                 C   r   )NZPyObject_Strr   r   r   r   r   r   
object_str  r   zPythonAPI.object_strc                 C   s   |   }| | |S r   )r-  r   r   r=   r   r   r   r     s   
zPythonAPI.make_nonec                 C   s
   |  dS )NZ_Py_NoneStruct)r   r   r   r   r   r-    r   zPythonAPI.borrow_nonec                 G   s:   t jt  | jgdd}| j|dd}| j||f| S )NTr   ZPySys_FormatStdoutr   )r   r   r   r   r   r:   r   )r   r   r   r   r   r   r   r   sys_write_stdout  r   zPythonAPI.sys_write_stdoutc                 C   r   )zL
        Dump a Python object on C stderr.  For debugging purposes.
        Z_PyObject_Dumpr   r   r   r   r   r   object_dump  s   zPythonAPI.object_dumpc                 C   s   | j jsJ dtd}| | |j}t| j| j	| j||| jg}| j
|dd}|jd d | j tj|j}| j tjt|j}	t| j|}
| j|| j|
| j	|||	|gS )NzNRT requiredr   Z"NRT_adapt_ndarray_to_python_acqrefr   r   	nocapture)r9   
enable_nrtr   rt   unserializeserialize_objectZbox_typer   r_   ru   r   r   add_attributerT  r   r  ndimr   Zmutabler
   rs  r:   r   bitcast)r   ZarytyaryZdtypeptrZinttyZserial_aryty_pytyper   r   r  writableZaryptrr   r   r   nrt_adapt_ndarray_to_python  s"   
z%PythonAPI.nrt_adapt_ndarray_to_pythonc                 C   sj   | j j}ttjtjtjg}t||d}|jd d |jd d |j	d | j 
|||gS )za
        Allocate a new MemInfo with data payload borrowed from a python
        object.
        ZNRT_meminfo_new_from_pyobjectr   r  r  noalias)r:   rm   r   r   r
   	voidptr_tget_or_insert_functionr   r  return_valuer   )r   datar_   modr   r   r   r   r   nrt_meminfo_new_from_pyobject  s   
z'PythonAPI.nrt_meminfo_new_from_pyobjectc                 C   sD   | j j}t| jtjg}t||d}|j	d | j 
||gS )NZNRT_meminfo_as_pyobjectr  )r:   rm   r   r   r_   r
   r  r  r  r  r   )r   Zmiptrr  r   r   r   r   r   nrt_meminfo_as_pyobject     z!PythonAPI.nrt_meminfo_as_pyobjectc                 C   sD   | j j}ttj| jg}t||d}|j	d | j 
||gS )NZNRT_meminfo_from_pyobjectr  )r:   rm   r   r   r
   r  r_   r  r  r  r   )r   Zmiobjr  r   r   r   r   r   nrt_meminfo_from_pyobject  r  z#PythonAPI.nrt_meminfo_from_pyobjectc                 C   sf   | j jsJ ttd| j| jg}| j|dd}|jd 	d |jd 	d | j
|||fS )Nr   ZNRT_adapt_ndarray_from_pythonr   r   r  r  r9   r  r   r   rt   r_   ru   r   r   r  r:   r   r   r  r  r   r   r   r   r   nrt_adapt_ndarray_from_python     z'PythonAPI.nrt_adapt_ndarray_from_pythonc                 C   sj   | j jsJ tt t| j| jg}| j|dd}|j	d 
d |j	d 
d | j|||fS )NZNRT_adapt_buffer_from_pythonr   r   r  r  )r9   r  r   r   r   rs   r   ru   r   r   r  r:   r   r   bufr  r   r   r   r   r   nrt_adapt_buffer_from_python  s   z&PythonAPI.nrt_adapt_buffer_from_pythonc                 C   s   t | j||S r   )r
   r  rm   )r   r   r   r   r   r   r     s   zPythonAPI._get_functionc                 C   s   | j | jS r   )r:   Zallocar_   r   r   r   r   
alloca_obj  r?   zPythonAPI.alloca_objc                 C   s   t | jt| jd}|S )zT
        Return a pointer to a stack-allocated, zero-initialized Py_buffer.
        N)r
   rs  r:   r   r   )r   r  r   r   r   alloca_buffer!  s   
zPythonAPI.alloca_bufferc                 c   sF    t | jt | j| d V  W d    d S 1 sw   Y  d S r   )r
   r  r:   ra   r  r   r   r   r   *  s   "zPythonAPI.if_object_okc                 C   s>   |  |}| |}| j| jd}| || | | d S )Nz%s)r  r  r9   r   rm   r  r   )r   r=   r  r   r   r   r   r   print_object0  s
   

zPythonAPI.print_objectc                 C   s   | j | j|}| | d S r   )r9   r   rm   r  )r   textr   r   r   r   print_string7  s   zPythonAPI.print_stringc                 C   s   t | jd S r   )r   r_   r   r   r   r   r   ;  s   zPythonAPI.get_null_objectc                 C   s   |   }| j| d S r   )r   r:   re   )r   noner   r   r   return_none>  s   zPythonAPI.return_nonec                 C   s   t |}| | jtj|}| |( t|D ]}| jtj|}| ||  | 	||||  qW d    |S 1 s?w   Y  |S r   )
rV   rK  r9   rT  r   r   r   r   r   rS  )r   rY  rZ  seqr   rR  r   r   r   	list_packB  s   
zPythonAPI.list_packc                 C   s   t | j| jt d| jf}| j|dd}| j| j|d}| j| j|d}| j| j|d}| j	||||fS )z
        Unserialize some data.  *structptr* should be a pointer to
        a {i8* data, i32 length, i8* hashbuf, i8* func_ptr, i32 alloc_flag}
        structure.
        r   Znumba_unpickler   r   r     )
r   r   r_   ru   rt   r   r:   Zextract_valuerd   r   )r   Z	structptrr   r   r  rZ  hashedr   r   r   r  L  s   zPythonAPI.unserializec                 C   s6   t | j| j| jf}| j|dd}| j|||fS )z
        Serialize some data at runtime. Returns a pointer to a python tuple
        (bytes_data, hash) where the first element is the serialized data as
        bytes and the second its hash.
        Z"numba_runtime_build_excinfo_structr   r   )r   Z	struct_gvZexc_argsr   r   r   r   r   build_dynamic_excinfo_structZ  s   z&PythonAPI.build_dynamic_excinfo_structc           	   
   C   s   t |}t|dk sJ dtjdkrt|nd }t|}tt	|
 }| j| j||}| j| j| d|}t|| jttd|jjj|| jt| jttddg}|S )z
        Same as serialize_object(), but don't create a global variable,
        simply return a literal for structure:
        {i8* data, i32 length, i8* hashbuf, i8* func_ptr, i32 alloc_flag}
        l        z.const.pickledata.%sr   DIFF_IRz.sha1r   )r   dumpsrV   r   r  idr
   Zmake_bytearrayhashlibsha1digestr9   insert_unique_constrm   r   Zliteral_structr  ru   r   rt   r   r   r]  Zget_null_value)	r   r=   r  r   Zbdatar  ZarrZhasharrstructr   r   r   serialize_uncachedd  s"   




zPythonAPI.serialize_uncachedc                 C   sj   z	| j j| }W |S  ty4   | |}dtjdkrt|nd }| j| j ||}|| j j|< Y |S w )z
        Serialize the given object in the bitcode, and return it
        as a pointer to a
        {i8* data, i32 length, i8* hashbuf, i8* fn_ptr, i32 alloc_flag},
        structure constant (suitable for passing to unserialize()).
        z.const.picklebuf.%sr   r  )	rm   rn   r   r  r   r  r  r9   r  )r   r=   gvr  r   r   r   r   r    s   
zPythonAPI.serialize_objectc                 C   s   t | j|  S r   )r
   ra   r:   r   r   r   r   r   c_api_error  r5   zPythonAPI.c_api_errorc                 C   s6   ddl m} t|j|}t| j| j| }||||S )zn
        Unbox the Python object as the given Numba type.
        A NativeValue instance is returned.
        r   )unbox_unsupported)numba.core.boxingr  	_unboxersr&   	__class__r;   r9   r:   )r   r2   r=   r  implcr   r   r   r<     s   zPythonAPI.to_native_valuec                 C   s&   t |tjr
J d| |||}|S )Nz;callconv should have prevented the return of optional value)rL   r   Optionalr/   )r   r2   r3   r0   outr   r   r   from_native_return  s   zPythonAPI.from_native_returnc                 C   s8   ddl m} t|j|}t| j| j| |}||||S )z
        Box the native value of the given Numba type.  A Python object
        pointer is returned (NULL if an error occurred).
        This method steals any native (NRT) reference embedded in *val*.
        r   )box_unsupported)r  r  _boxersr&   r
  r+   r9   r:   )r   r2   r3   r0   r  r  r  r   r   r   r/     s   zPythonAPI.from_native_valuec                 C   sX   t |j}|du rtjS t| jtj}t| j| j| ||}|||| | j	|j
S )z
        Reflect the native value onto its Python original, if any.
        An error bit (as an LLVM value) is returned.
        N)_reflectorsr&   r
  r
   rH   rs  r:   r@   r9   rd   rB   )r   r2   r3   r0   r  rB   r  r   r   r   rD     s   zPythonAPI.reflect_native_valuec                 C   s,   t | j|}| j| j||}t|S )zy
        Extract the generator structure pointer from a generator *obj*
        (a _dynfunc.Generator instance).
        )r   rs   r9   get_data_typeZget_generator_stater:   rF   )r   r=   r2   Z
gen_ptr_tyrG   r   r   r   to_native_generator  s   zPythonAPI.to_native_generatorc              	   C   s   | j |}|jrJ | j |}| j |}t| j| j| j| jg}| j||j	d}tt
 | jg}	|jrB| j|	|jd}
ntt|	d}
t| j| j| jt|t|	| jg}| j|dd}t| j|}| j|| j}|du r||  }| j|| j}| j|||||
|fS )z
        Make a Numba generator (a _dynfunc.Generator instance) from a
        generator structure pointer *val*.
        *env* is an optional _dynfunc.Environment instance to be wrapped
        in the generator.
        r   NZnumba_make_generator)r9   r  Z
is_pointerZget_abi_sizeofZget_generator_descr   r   r_   r   Zllvm_cpython_wrapper_namer   ru   Zhas_finalizerZllvm_finalizer_namer   rs   r   r:   r  r   r   )r   r3   r2   rN   ZlltyZgen_struct_sizeZgendescZgenfntyZgenfnZfinalizerty	finalizerr   r   Z
state_sizeZinitial_stater   r   r   from_native_generator  s2   
zPythonAPI.from_native_generatorc                 C   sf   | j jrJ ttd| j| jg}| j|dd}|jd 	d |jd 	d | j
|||fS )Nr   Znumba_adapt_ndarrayr   r   r  r  r  r  r   r   r   numba_array_adaptor  r  zPythonAPI.numba_array_adaptorc                 C   s^   t t  t | j| jg}| j|dd}|jd d |jd d | j	
|||fS )NZnumba_adapt_bufferr   r   r  r  )r   r   r   rs   r   ru   r   r   r  r:   r   r  r   r   r   numba_buffer_adaptor  s   
zPythonAPI.numba_buffer_adaptorc                 C   s:   t t d| j|jg}| j|dd}| j|||gS )Nr   Znumba_complex_adaptorr   )r   r   rt   r_   r   r   r:   r   )r   r=  Zcmplxr   r   r   r   r   complex_adaptor  r9  zPythonAPI.complex_adaptorc                 C   s<   t | j| jt | jg}| j|dd}| j|||gS )NZnumba_extract_record_datar   )	r   r   ru   r_   rs   r   r   r:   r   r   r=   pbufr   r   r   r   r   extract_record_data  s
   zPythonAPI.extract_record_datac                 C   s@   t t d| jt | jg}| j|dd}| j|||gS )Nr   Znumba_get_bufferr   )	r   r   rt   r_   rs   r   r   r:   r   r  r   r   r   
get_buffer  s
   zPythonAPI.get_bufferc                 C   s8   t t  t | jg}| j|dd}| j||gS )NZnumba_release_bufferr   )r   r   r   rs   r   r   r:   r   )r   r  r   r   r   r   r   release_buffer  s   zPythonAPI.release_bufferc                 C   re  )N@   Znumba_extract_np_datetimer   r   r   r   r   r   extract_np_datetime  rh  zPythonAPI.extract_np_datetimec                 C   re  )Nr  Znumba_extract_np_timedeltar   r   r   r   r   r   extract_np_timedelta!  rh  zPythonAPI.extract_np_timedeltac                 C   R   t tdt|}t| jtdtdg}| j|dd}| j|||gS )Nr   r  Znumba_create_np_datetimer   	r   r   rt   r   r   r_   r   r:   r   r   r3   Z	unit_coder   r   r   r   r   create_np_datetime&     zPythonAPI.create_np_datetimec                 C   r"  )Nr   r  Znumba_create_np_timedeltar   r#  r$  r   r   r   create_np_timedelta,  r&  zPythonAPI.create_np_timedeltac                 C   sZ   t | jt t dt d| jg}| j|dd}|||}| j	||||gS )Nrk   r   Znumba_recreate_recordr   )
r   r   r_   rs   rt   r   rg   rZ   r:   r   )r   Zpdatar  Zdtyper0   r   r   Z	dtypeaddrr   r   r   recreate_record2  s   zPythonAPI.recreate_recordc                 C   s0   | j | j|}| j tjt|}| ||S r   )r9   r   rm   rT  r   r   rV   r  )r   r  r   szr   r   r   string_from_constant_string9  s   z%PythonAPI.string_from_constant_stringc              	   C   s`  | j }| j|||}|jj}|j}||kr"td| d| d| j||j||\}}	t	j
|t	jdd}
| j|j}t	j
||dd}||jN\}}| ||j|
 | jj|| | W d   n1 slw   Y  | t| j||||	}	||	| W d   n1 sw   Y  W d   n1 sw   Y  ||
}||}	||	fS )aP  Calls into Numba jitted code and propagate error using the Python
        calling convention.

        Parameters
        ----------
        func : function
            The Python function to be compiled. This function is compiled
            in nopython-mode.
        sig : numba.typing.Signature
            The function signature for *func*.
        args : Sequence[llvmlite.binding.Value]
            LLVM values to use as arguments.

        Returns
        -------
        (is_error, res) :  2-tuple of llvmlite.binding.Value.
            is_error : true iff *func* raised an exception.
            res : Returned value from *func* iff *is_error* is false.

        If *is_error* is true, this method will adapt the nopython exception
        into a Python exception. Caller should return NULL to Python to
        indicate an error.
        zmismatching signature z != z.
Tr[   N)r:   r9   Zcompile_subroutine	signaturer   errorsZLoweringErrorZcall_internal_no_propagateZfndescr
   r^   Zbool_tr   r`   rB   rA   r   Zraise_errorr   Zfix_returning_optionalrd   )r   r   sigr   r:   ZcresZ	got_rettyZrettyr  r@  Zis_error_ptrZres_typeZres_ptrZhas_errZno_errrB   r   r   r   call_jit_code>  s<   


zPythonAPI.call_jit_code)Fr   r   )F)r   )r   rJ   )r'   r(   r)   r6   r   r   r   r   r   r   r   r   r   r   r   rc   r   r   r   r   r   r   r   
contextlibcontextmanagerr   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/  r1  r2  r3  r4  r5  r7  r6  r8  r>  r?  rD  rF  rG  rI  rK  rN  rP  rS  rb   rU  rW  r[  r\  r^  r`  rb  rd  rg  ri  rj  rn  ry  r{  r|  r}  r~  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r-  r  r  r  r  r  r  r  r  r   r  r  r   r  r  r   r  r  r  r  r  r  r  r<   r  r/   rD   r  r  r  r  r  r  r  r  r   r!  r%  r'  r(  r*  r.  r   r   r   r   rj      sd   #			
		
	
	

	
)
	

	)rj   c                   @   s,   e Zd ZdZdd Zdd Zedd ZdS )	ObjModeUtilszHInternal utils for calling objmode dispatcher from within NPM code.
    c                 C   s
   || _ d S r   )r.   )r   r.   r   r   r   r     r   zObjModeUtils.__init__c                 C   s  | j j}| j j}|j}tj|| j j|dd}|j	d |_
d|_|d}t|jr^| j |jt|f}| j |}	t||	}
||
 || W d    n1 sYw   Y  ||}|t||P t|jrt| }| j | j |j}| j ||	g}| j | | j |	 n|jt|}|j|t|dd}| j | ||| W d    n1 sw   Y  || | | ||}|S )NZcached_objmode_dispatcherr   Zinternalrp  Zwith_objectmode)info)!r.   r:   r9   rm   r   ZGlobalVariabler_   Zget_unique_namer   r   Zinitializerlinkagert  r   Zis_serialiable
dispatcherr  r   r  r
   r   ru  rq  rd   _call_objmode_dispatcherr  r   compileZadd_dynamic_addrr  r   rA   rv  )r   r   r   r:   Ztyctxmr  rp  Zserialized_dispatchercompile_argsZfailed_unsercachedr%   compilerr  Zentry_ptr   r   r   load_dispatcher  sT   





zObjModeUtils.load_dispatcherc                 C   s   | \}}| |}|S r   )r6  )r8  r4  r   Zentryptr   r   r   r5    s   
z%ObjModeUtils._call_objmode_dispatcherN)r'   r(   r)   r6   r   r;  staticmethodr5  r   r   r   r   r1  |  s    7r1  )0collectionsr   r/  pickler  rR   Zllvmliter   Zllvmlite.irr   rv   Znumbar   Z
numba.corer   r   r   r	   r
   r   r   Znumba.core.utilsr   r   ZPY_UNICODE_1BYTE_KINDr   ZPY_UNICODE_2BYTE_KINDr   ZPY_UNICODE_4BYTE_KINDZpy_unicode_wchar_kindZPY_UNICODE_WCHAR_KINDobjectr   r  r	  r  r!   r4   r>   rE   r+   r;   r@   rF   rK   rh   rj   r1  r   r   r   r   <module>   s`    $
4           d