o
    ۾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   H/home/ubuntu/.local/lib/python3.10/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
   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   rD   r4   rF   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   rH   rB   rJ   r   r   r   r   f   s   
zNativeValue.__init__NN)r'   r(   r)   r6   r   r   r   r   r   rG   `   s    rG   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.   rO   rP   rQ   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.
        )	rM   strsysintern	enumeraterO   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`)rW   rO   rV   r.   r:   rP   r
   alloca_oncepyobjif_elseis_not_nulllist_getitemrA   err_set_stringload)r   rZ   r:   rV   retbr_not_nullbr_nullgetitemr   r   r   
read_const   s&   
zEnvironmentManager.read_constN)r'   r(   r)   r   r[   rj   r   r   r   r   rL   l   s    rL   _IteratorLoop)rH   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:   basic_blockfunctionmodule_PythonAPI__serializedAttributeErrorget_argument_typer   pyobjectr`   
as_pointerpyobjptrr   PointerTypeIntTypevoidptrctypessizeofc_longlongulongc_ulonglonglonglong	ulonglong
DoubleTypedoubler   USE_LEGACY_TYPE_SYSTEMget_value_typeintp
py_ssize_tc_intpcstringr   py_gil_state_size	gil_state	ArrayType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   )rL   )r   rO   rP   rQ   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:   if_unlikelyrp   typepointeereturn_typer`   rd   rf   get_null_objectr9   	call_convreturn_user_excRuntimeError)r   envptrreturn_pyobject	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 )N	Py_IncRefnamer   FunctionTypeVoidTyper`   _get_functionr:   callr   r=   r   fnr   r   r   incref      zPythonAPI.increfc                 C   r   )N	Py_DecRefr   r   r   r   r   r   decref   r   zPythonAPI.decrefc                 C   0   t | j| jg}| j|dd}| j||gS )N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 )Nrn       Tvar_argPyArg_ParseTupleAndKeywordsr   	r   rx   ry   r`   r   r   r:   r   list)r   argskwsfmtkeywordsobjscharptr
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 )Nrn   r   Tr   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 )Nrn   r   Tr   PyArg_UnpackTupler   )r   rx   ry   r`   r   r   r   r   intrM   rR   r9   insert_const_stringr:   rq   r   r   )
r   r   r   n_min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   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   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 )NPyErr_SetStringr   )r   r   r   r`   r   r   rM   rR   get_c_objectr9   r   rq   r:   r   )r   exctypemsgr   r   r   r   r   rd   #  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   PyErr_Formatr   )r   r   r   r`   r   r   rM   rR   r   r9   r   rq   r:   r   tuple)r   r   r   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.
        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 )NPyErr_SetObjectr   
r   r   r   r`   r   rM   rR   r   r:   r   )r   r   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 )N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 )N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   PyErr_Fetchr   )r   r   r   rw   r   r:   r   )r   ptypvalptbr   r   r   r   r   	err_fetchS     zPythonAPI.err_fetchc                 C   r   )Nr   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likely)
ranger   r:   re   r
   rb   r   ra   r   r   )r   keep_newr   r   r   r   r3   r   	new_errorif_error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)	dllimport)r9   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   rq   rd   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 )NPy_FatalErrorr   noreturn)r   r   r   r   r   
attributesaddr9   r   rq   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
        PyDict_GetItemStringr   )
r   r   r`   r   r   r9   r   rq   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  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   
PyDict_Newr   _PyDict_NewPresized)	r   r   r`   r   r:   r   r   r   r   )r   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   PyDict_SetItemr   r   r   ry   r`   r   r:   r   )r   dictobj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   PyDict_SetItemStringr   )r   r   ry   r`   r   r   r9   r   rq   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   	keyvaluesr  kvr   r   r   	dict_pack  s   
zPythonAPI.dict_packc                 C   0   t | j| jg}| j|dd}| j||gS )NPyFloat_FromDoubler   )r   r   r`   r   r   r:   r   )r   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 )NPyNumber_AsSsize_tr   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   )NPyNumber_Longr   r   r   r-  r   r   r   r   r   number_long  r   zPythonAPI.number_longc                 C   r'  )NPyLong_AsUnsignedLongLongr   r   r   r   r`   r   r:   r   r1  r   r   r   long_as_ulonglong  r   zPythonAPI.long_as_ulonglongc                 C   r'  )NPyLong_AsLongLongr   r4  r1  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.
        PyLong_AsVoidPtrr   r   r   rz   r`   r   r:   r   r1  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   re   )r   ival	func_namenative_int_typesignedr   r   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 )NPyLong_FromLongr   r   r   r`   r~   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 )NPyLong_FromUnsignedLongFr>  )r@  r~   r   r;  r   r   r   long_from_ulong	     zPythonAPI.long_from_ulongc                 C   rD  )NPyLong_FromSsize_tTrF  )r@  r   rG  r   r   r   long_from_ssize_t  rI  zPythonAPI.long_from_ssize_tc                 C   rD  )NPyLong_FromLongLongTrF  )r@  r   rG  r   r   r   long_from_longlong  rI  zPythonAPI.long_from_longlongc                 C   rD  )NPyLong_FromUnsignedLongLongFrF  )r@  r   rG  r   r   r   long_from_ulonglong  rI  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   widthr~   rC  r:   sextr   rM  OverflowErrorr   r;  bitsr   r   r   long_from_signed_int     zPythonAPI.long_from_signed_intc                 C   rP  )zH
        Same as long_from_signed_int, but for unsigned values.
        rQ  )	r   rR  r   rH  r:   zextr   rO  rT  rU  r   r   r   long_from_unsigned_int%  rX  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 )N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   ra  )NSubtractrc  rd  re  r   r   r   number_subtract?  r5   zPythonAPI.number_subtractc                 C   ra  )NMultiplyrc  rd  re  r   r   r   number_multiplyB  r5   zPythonAPI.number_multiplyc                 C   ra  )N
TrueDividerc  rd  re  r   r   r   number_truedivideE  r5   zPythonAPI.number_truedividec                 C   ra  )NFloorDividerc  rd  re  r   r   r   number_floordivideH  r5   zPythonAPI.number_floordividec                 C   ra  )N	Remainderrc  rd  re  r   r   r   number_remainderK  r5   zPythonAPI.number_remainderc                 C   ra  )NMatrixMultiplyrc  rd  re  r   r   r   number_matrix_multiplyN  r5   z PythonAPI.number_matrix_multiplyc                 C   ra  )NLshiftrc  rd  re  r   r   r   number_lshiftQ  r5   zPythonAPI.number_lshiftc                 C   ra  )NRshiftrc  rd  re  r   r   r   number_rshiftT  r5   zPythonAPI.number_rshiftc                 C   ra  )NAndrc  rd  re  r   r   r   
number_andW  r5   zPythonAPI.number_andc                 C   ra  )NOrrc  rd  re  r   r   r   	number_orZ  r5   zPythonAPI.number_orc                 C   ra  )NXorrc  rd  re  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   PyNumber_InPlacePower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 )NPyNumber_Negativer   r   r   r   r   r   number_negativef  r   zPythonAPI.number_negativec                 C   r  )NPyNumber_Positiver   r   r   r   r   r   number_positivek  r   zPythonAPI.number_positivec                 C   r   )NPyNumber_Floatr   r   )r   r3   r   r   r   r   r   number_floatp  r   zPythonAPI.number_floatc                 C   r  )NPyNumber_Invertr   r   r   r   r   r   number_invertu  r   zPythonAPI.number_invertc                 C   r'  )NPyFloat_AsDoubler   )r   r   r   r`   r   r:   r   )r   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:   rY  r~   bool_from_long)r   bvallongvalr   r   r   bool_from_bool  s   
zPythonAPI.bool_from_boolc                 C   r'  )NPyBool_FromLongr   rB  )r   r;  r   r   r   r   r   r    r   zPythonAPI.bool_from_longc                 C   s:   t | jt  t  g}| j|dd}| j|||gS )NPyComplex_FromDoublesr   )r   r   r`   r   r   r:   r   )r   realval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 )N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  )N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   numba_unpack_slicer   )r
   r_   r:   r   r   r   ry   r`   rv   r   r   re   r   )r   r=   pstartpstop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 )NPySequence_GetSlicer   r   r   r`   r   r   r:   r   )r   r=   r  r  r   r   r   r   r   sequence_getslice  s
   zPythonAPI.sequence_getslicec                 C   r   )NPySequence_Tupler   r   r   r   r   r   sequence_tuple  r   zPythonAPI.sequence_tuplec                 C   r  )NPySequence_Concatr   r   )r   obj1obj2r   r   r   r   r   sequence_concat     zPythonAPI.sequence_concatc                 C   r'  )N
PyList_Newr   r  )r   szvalr   r   r   r   r   list_new  r   zPythonAPI.list_newc                 C   r'  )N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   PyList_Appendr   r  )r   r  r3   r   r   r   r   r   list_append  r  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   PyList_SetItemr   r   r   ry   r`   r   r   r:   r   )r   r  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.
        PyList_GetItemr   )r   r   r`   r   r   rM   r   r9   get_constantr   r   r:   r   )r   r  r  r   r   r   r   r   rc     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   PyList_SetSlicer   )	r   r   r   ry   r`   r   r   r:   r   )r   r  r  r  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
        PyTuple_GetItemr   )r   r   r`   r   r   r9   r  r   r   r:   r   )r   tupr  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   PyTuple_Packr   )r   r   r`   r   r   r9   r  r   r   rW   extendr:   r   )r   itemsr   r   nr   r   r   r   
tuple_pack  s   
zPythonAPI.tuple_packc                 C   r'  )NPyTuple_Sizer   r  )r   r  r   r   r   r   r   
tuple_size  r   zPythonAPI.tuple_sizec                 C   s6   t | j| jg}| j|dd}| j|| |gS )NPyTuple_Newr   r  )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   PyTuple_SetItemr   Nr  )r   	tuple_valrZ   itemr   
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 )N	PySet_Newr   )r   r   r   r`   r   r:   r   )r   iterabler   r   r   r   r   set_new  s
   zPythonAPI.set_newc                 C   r  )Nr   	PySet_Addr   r  )r   setrH   r   r   r   r   r   set_add#  r  zPythonAPI.set_addc                 C   4   t t d| jg}| j|dd}| j||gS )Nr   PySet_Clearr   r  r   r  r   r   r   r   r   	set_clear(     zPythonAPI.set_clearc                 C   r'  )N
PySet_Sizer   r  r  r   r   r   set_size-  r   zPythonAPI.set_sizec                 C   r  )Nr   _PySet_Updater   r  )r   r  r  r   r   r   r   r   
set_update2  r  zPythonAPI.set_updatec                 C   sR   t t d| j| j | j | j g}| j|dd}| j	|||||fS )Nr   _PySet_NextEntryr   )
r   r   ry   r`   r   rv   r   r   r:   r   )r   r  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 )Nr  r   r  r   r  bb_bodybb_endc                      s      d S r   )branchr   r  r:   r   r   rl   L  r?   z'PythonAPI.set_iterate.<locals>.do_breakFr   )r:   r
   r_   r   r`   alloca_once_valuer   r   append_basic_blockr  
goto_blockr  r   if_thenrk   re   position_at_end)	r   r  r  r  r  r  rl   rfinishedr   r  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().
        numba_gil_ensure)
r   rx   r   r   r   r   r
   r_   r:   r   )r   gilptrtyr   r   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().
        numba_gil_release)r   rx   r   r   r   r   r:   r   )r   gilr  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).
        PyEval_SaveThreadr   )r   r   rz   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.
        PyEval_RestoreThreadr   N)r   r   r   rz   r   r:   r   )r   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 )Nnumba_get_pyobject_private_datar   r9  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 )Nnumba_set_pyobject_private_datar   )r   r   r   r`   rz   r   r:   r   )r   r=   ptrr   r   r   r   r   object_set_private_data  s   z!PythonAPI.object_set_private_datac                 C   r   )N!numba_reset_pyobject_private_datar   r   r   r   r   r   object_reset_private_data  r   z#PythonAPI.object_reset_private_datac                 C   r'  )N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   PyObject_CallFunctionObjArgsr   )r   r   r`   r   r   rX   r9   get_constant_nullr   ru   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   PyObject_CallMethodr   O)r9   r   rq   r   r   r`   r   r   rW   r  rX   r  r   ru   r:   r   )
r   r  methodr  cnamer   r   r   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   PyObject_Callr   )	r  r   r   r   r`   r   r:   r   r   )r   r  r   r   args_was_noner   r   resultr   r   r   r     s   

zPythonAPI.callc                 C   r  )zJEmit a call to ``PyObject_Type(obj)`` to get the type of ``obj``.
        PyObject_Typer   r   r   r   r   r   object_type  s   zPythonAPI.object_typec                 C   r  )Nr   PyObject_IsTruer   r  r   r   r   r   object_istrue  r  zPythonAPI.object_istruec                 C   r  )Nr   PyObject_Notr   r  r   r   r   r   
object_not  r  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   PyObject_RichComparer   isr#  zis notr$  )innot inPySequence_ContainsNr)     zUnknown operator {op!r})op)rZ   r   r   r`   ry   r   r9   r  r   int32r:   r   icmp_unsignedr  r
   r  r   	if_likelynot_truncrA   re   NotImplementedErrorformat)r   r]  r^  opstropsopidr   r   lopidbitflagstatusnegoneis_goodoutptr	truncatedr   r   r   object_richcompare  sD   



zPythonAPI.object_richcomparec                 C   r   )NPyIter_Nextr   r   )r   iterobjr   r   r   r   r   	iter_next  r   zPythonAPI.iter_nextc                 C   r   )N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 )NPyObject_GetAttrStringr   )
r9   r   rq   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  )NPyObject_GetAttrr   r   )r   r=   rF  r   r   r   r   r   object_getattr  r  zPythonAPI.object_getattrc                 C   sP   | j | j|}ttd| j| j| jg}| j|dd}| j	
||||gS )Nr   PyObject_SetAttrStringr   )r9   r   rq   r   r   ry   r`   r   r   r:   r   )r   r=   rF  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   PyObject_SetAttrr   r  )r   r=   rF  r3   r   r   r   r   r   object_setattr  s   zPythonAPI.object_setattrc                 C      |  |||  S r   )rK  r   r   r=   rF  r   r   r   object_delattr_string     zPythonAPI.object_delattr_stringc                 C   rN  r   )rM  r   rO  r   r   r   object_delattr!  rQ  zPythonAPI.object_delattrc                 C   s6   t | j| j| jg}| j|dd}| j|||fS )z!
        Return obj[key]
        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   PyObject_SetItemr   r  )r   r=   rU  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   PyObject_DelItemr   r  rT  r   r   r   object_delitem6  s   zPythonAPI.object_delitemc                 C   4   t | j| jg}d}| j||d}| j||gS )N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.
        PyUnicode_AsUTF8AndSizer   r$  N)r
   r_   r:   r   r   r   r   r`   rv   r   r   r/  r   r   re   )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   numba_extract_unicoder   r$  N)r
   r_   r:   r   r   ry   r   r   r   r`   rv   r   r   r/  r   r   re   )r   r^  rb  p_kindp_asciip_hashr   r  r   rc  rd  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 )N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[  )NPyUnicode_FromStringr   r  )r   ro  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   PyUnicode_FromKindAndDatar   )	r   r   r`   ry   r   r   r   r:   r   )r   kindro  rp  r   r  r   r   r   r   string_from_kind_and_data  s   z#PythonAPI.string_from_kind_and_datac                 C   r[  )N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   PyBytes_AsStringAndSizer   r$  r+  )r   r   ry   r`   r   rv   r   r   r:   r   icmp_signedr   r   )	r   r=   p_bufferrb  r   r  r   r  rd  r   r   r   bytes_as_string_and_size  s   z"PythonAPI.bytes_as_string_and_sizec                 C   rk  )NPyBytes_FromStringAndSizer   rm  rn  r   r   r   bytes_from_string_and_size  rr  z$PythonAPI.bytes_from_string_and_sizec                 C   r[  )NPyObject_Hashr   )r   r   r   r`   r   r:   r   ry  r   r   r   object_hash  r`  zPythonAPI.object_hashc                 C   r   )N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 )N_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   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.
        _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   "NRT_adapt_ndarray_to_python_acqrefr   r   	nocapture)r9   
enable_nrtr   ry   unserializeserialize_objectbox_typer   r`   rz   r   r   add_attributer  r   r.  ndimr   mutabler
   r  r:   r   bitcast)r   arytyarydtypeptrinttyserial_aryty_pytyper   r   r  writable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.
        NRT_meminfo_new_from_pyobjectr   r  r,  noalias)r:   rq   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 )NNRT_meminfo_as_pyobjectr  )r:   rq   r   r   r`   r
   r  r  r  r  r   )r   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 )NNRT_meminfo_from_pyobjectr  )r:   rq   r   r   r
   r  r`   r  r  r  r   )r   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   NRT_adapt_ndarray_from_pythonr   r   r  r,  r9   r  r   r   ry   r`   rz   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 )NNRT_adapt_buffer_from_pythonr   r   r  r,  )r9   r  r   r   r   rx   r   rz   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  rq   )r   r   r   r   r   r   r     s   zPythonAPI._get_functionc                 C   s   | j | jS r   )r:   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
   r  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
   r0  r:   rb   r  r   r   r   r"  *  s   "zPythonAPI.if_object_okc                 C   s>   |  |}| |}| j| jd}| || | | d S )Nz%s)r  r_  r9   r   rq   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   rq   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:   rf   )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   )
rW   r  r9   r  r   r   r"  r   r   r  )r   r  r  seqr   r  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   numba_unpickler   r   r,     )
r   r   r`   rz   ry   r   r:   extract_valuere   r   )r   	structptrr   r   r  r  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.
        "numba_runtime_build_excinfo_structr   r   )r   	struct_gv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   dumpsrW   r   r  idr
   make_bytearrayhashlibsha1digestr9   insert_unique_constrq   r   literal_structr  rz   r   ry   r   r   r  get_null_value)	r   r=   r  r   bdatar  arr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  )	rq   rr   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
   rb   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)rM   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
   rI   r  r:   r@   r9   re   rB   )r   r2   r3   r0   r  rB   r  r   r   r   rE     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   rx   r9   get_data_typeget_generator_stater:   rG   )r   r=   r2   
gen_ptr_tyrH   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   Nnumba_make_generator)r9   r  
is_pointerget_abi_sizeofget_generator_descr   r   r`   r   llvm_cpython_wrapper_namer   rz   has_finalizerllvm_finalizer_namer   rx   r   r:   r  r   r   )r   r3   r2   rO   lltygen_struct_sizegendescgenfntygenfnfinalizerty	finalizerr   r   
state_size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   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 )Nnumba_adapt_bufferr   r   r  r,  )r   r   r   rx   r   rz   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   numba_complex_adaptorr   )r   r   ry   r`   r   r   r:   r   )r   r  cmplxr   r   r   r   r   complex_adaptor  r  zPythonAPI.complex_adaptorc                 C   s<   t | j| jt | jg}| j|dd}| j|||gS )Nnumba_extract_record_datar   )	r   r   rz   r`   rx   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   numba_get_bufferr   )	r   r   ry   r`   rx   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 )Nnumba_release_bufferr   )r   r   r   rx   r   r   r:   r   )r   r  r   r   r   r   r   release_buffer  s   zPythonAPI.release_bufferc                 C   r  )N@   numba_extract_np_datetimer   r  r   r   r   r   extract_np_datetime  r  zPythonAPI.extract_np_datetimec                 C   r  )Nr	  numba_extract_np_timedeltar   r  r   r   r   r   extract_np_timedelta!  r  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	  numba_create_np_datetimer   	r   r   ry   r   r   r`   r   r:   r   r   r3   	unit_coder   r   r   r   r   create_np_datetime&     zPythonAPI.create_np_datetimec                 C   r  )Nr   r	  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 )Nrn   r   numba_recreate_recordr   )
r   r   r`   rx   ry   r   rj   r[   r:   r   )r   pdatarp  dtyper0   r   r   	dtypeaddrr   r   r   recreate_record2  s   zPythonAPI.recreate_recordc                 C   s0   | j | j|}| j tjt|}| ||S r   )r9   r   rq   r  r   r   rW   rq  )r   ro  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   compile_subroutine	signaturer   errorsLoweringErrorcall_internal_no_propagatefndescr
   r_   bool_tr   ra   rB   rA   r   raise_errorr   fix_returning_optionalre   )r   r   sigr   r:   cres	got_rettyrettyr:  r  is_error_ptrres_typeres_ptrhas_errno_errrB   r   r   r   call_jit_code>  s<   


zPythonAPI.call_jit_code)Fr   r   )F)r   )r   rK   )r'   r(   r)   r6   r   r   r   r   r   r   r   r   r   r   r   rd   r   r   r   r   r   r   r   
contextlibcontextmanagerr   r   r  r	  r  r  r  r  r  r!  r&  r*  r/  r2  r5  r7  r:  r@  rC  rH  rK  rM  rO  rW  rZ  r[  r`  rf  rh  rj  rl  rn  rp  rr  rt  rv  rx  rz  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  r  r  r  r	  r  r  r  r   r  r  r!  r?  rB  rD  rG  rI  rK  rM  rP  rR  rV  rX  rZ  r_  re  rj  rq  rt  rw  rz  r~  r  r  r  r   r  r  r  r  r  r  r  r  r  r   r  r  r"  r  r  r   r  r  r  r  r  r  r  r<   r  r/   rE   r  r  r  r  r   r  r  r  r  r  r  r  r  r  r0  r   r   r   r   rm      sd   #			
		
	
	

	
)
	

	)rm   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 )Ncached_objmode_dispatcherr   internalr  with_objectmode)info)!r.   r:   r9   rq   r   GlobalVariabler`   get_unique_namer   r   initializerlinkager  r   is_serialiable
dispatcherr  r   r  r
   r   r  r  re   _call_objmode_dispatcherr  r   compileadd_dynamic_addrr  r   rA   r  )r   r   r   r:   tyctxmr  r  serialized_dispatchercompile_argsfailed_unsercachedr%   compilerr  entry_ptr   r   r   load_dispatcher  sT   





zObjModeUtils.load_dispatcherc                 C   s   | \}}| |}|S r   )r?  )rD  r=  r   entryptr   r   r   r>    s   
z%ObjModeUtils._call_objmode_dispatcherN)r'   r(   r)   r6   r   rI  staticmethodr>  r   r   r   r   r3  |  s    7r3  )0collectionsr   r1  pickler  rS   llvmliter   llvmlite.irr   r{   numbar   
numba.corer   r   r   r	   r
   r   r   numba.core.utilsr   r   PY_UNICODE_1BYTE_KINDr   PY_UNICODE_2BYTE_KINDr   PY_UNICODE_4BYTE_KINDpy_unicode_wchar_kindPY_UNICODE_WCHAR_KINDobjectr   r  r  r  r!   r4   r>   rF   r+   r;   r@   rG   rL   rk   rm   r3  r   r   r   r   <module>   s`    $
4           d