U
    9%e`                     @   s  d Z ddlZddlZddlmZ ddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddlZddlZddlZddlmZ ddlZddl m!Z!mZ ddl"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) dd	l*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 dd
l1m2Z2 ddl3m4Z4 ddl5Z5ddl6m7Z7 ddl8m9Z9 ddl6m:Z; ddl<m=Z=m>Z>m?Z?m@Z@mAZAmBZB ddlCmDZD zddlEZEW n eFk
r   dZEY nX zddlGZGW n eFk
r   Y n
X eGH  e- ZIdeI_Je- ZKdeK_Le- ZMe- ZNdeN_Oe!PdddgZQeQdZRejSdkZTeTZUe5VeUdZWe5Xe%jYdkdZZe5Xe%jYdkdZ[e5VeTdZ\dd Z]dZ^e5VeEdke^Z_e5Xe)j`dZadZbe5Vejcd  ebZdd!Zee5Vejcd" eeZfeg d#kZhe5Vdd$Zie5Veg d%kd&Zjeke	jlmd'dZne5Xend(Zoe5Vend)Zpe5Veg d%kd*Zqer Zsesjtd+kolesjgd,kZue5Veud-Zve5Veud.ZwzddlxZEdZyW n eFk
r   d/ZyY nX e5Xeyd0Zzzddl{ZEdZ|W n eFk
r   d/Z|Y nX e5Xe|d1Z}e	jlmd2dd3kZ~e5Xe~d4ZzddlZdZW n eFk
r>   d/ZY nX e5Xed5Zd6d7 ZG d8d9 d9eZG d:d; d;e5jZG d<d= d=eZejd>d? Zejd@dA ZdBdC ZdDZe	jdEkre	je eZne	je dFee	 f ZdGZdHdI ZdJdK ZdLdM ZdNdO ZdPdQ ZejdRdS ZdTdU ZdVdW ZejdXdY ZG dZd[ d[eZG d\d] d]eZG d^d_ d_eeZejd`da Zejdbdc Zddde ZedfdfdgZd~dhdiZdjdk ZG dldm dmeZdndo Zejdpdq ZddsdtZddvdwZdxdy ZG dzd{ d{e/Zd|d} ZdS )z&
Assorted utilities for use in tests.
    N)defaultdict)contextmanager)cached_property)testingtypes)errorstypingutilsconfigcpu)
cffi_utils)compile_extracompile_isolatedFlagsDEFAULT_FLAGSCompilerBaseDefaultPassBuilder)IRLegalization)
PreserveIR)rtsys)numpy_support)_nrt_python)overload_methodtypeof_implregister_modelunboxNativeValuemodels)OpaqueModelTZ	importantZlong_runningalways_test        zparfors not supported)   
   zneeds Python 3.10 or laterzneeds Python 3.10zNot supported on 32 bitc                 C   s   t jdkrt| S | S d S )N)r!      )r	   	PYVERSIONunittestZexpectedFailure)fn r'   R/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/numba/tests/support.pyexpected_failure_py311h   s    

r)   zSciPy needed for testzrequires cffizlinux only testlinuxzWindows-only testwinarmv7lzTest disabledppc64lez?Hits: 'Parameter area must exist to pass an argument in memory'ZNUMBA_USE_TYPEGUARDzTypeguard is not enabledzBroken if Typeguard is enabledz>Hits: 'mismatch in size of parameter area' in LowerCall_64SVR4Darwinarm64zpskip tests that contribute to triggering an AssertionError in LLVM's RuntimeDyLd on OSX arm64. (see: numba#8567)z1fenv.h-like functionality unreliable on OSX arm64FzLAPACK needs SciPy 1.0+zBLAS needs SciPy 1.0+SUBPROC_TEST1zneeds subprocess harnesszTest needs setuptoolsc                   C   s&   t jddd t jddtjdd dS )zUse in testing within a ` warnings.catch_warnings` block to filter out
    warnings that are unrelated/internally generated by Numba.
    ignoreZ	typeguard)modulez.*TBB_INTERFACE_VERSION.*znumba\.np\.ufunc\.parallel.*)actionmessagecategoryr3   N)warningsfilterwarningsr   ZNumbaWarningr'   r'   r'   r(   ignore_internal_warnings   s    r9   c                   @   s&   e Zd ZdZdd ZdefddZdS )CompilationCachez
    A cache of compilation results for various signatures and flags.
    This can make tests significantly faster (or less slow).
    c                 C   s$   t  | _t| jd| _i | _d S )Nr   )r   Context	typingctxr   Z
CPUContext	targetctxcr_cacheselfr'   r'   r(   __init__   s    
zCompilationCache.__init__Nc              
   C   sr   ddl m} ||||f}|| jkr.| j| }n@|| j| j  t| j| j||||i d}W 5 Q R X || j|< |S )ze
        Compile the function or retrieve an already compiled result
        from the cache.
        r   )
cpu_target)locals)Znumba.core.registryrB   r>   Znested_contextr<   r=   r   )r@   funcargsreturn_typeflagsrB   	cache_keycrr'   r'   r(   compile   s    
   
zCompilationCache.compile)__name__
__module____qualname____doc__rA   r   rJ   r'   r'   r'   r(   r:      s   r:   c                   @   s
  e Zd ZdZedd Zdd Zejdd Z	ejdd	 Z
d
d Zejdd ZeejfZeefefejfeejfgZefefejgZeefgZeejfZeej fZ!dd Z"dd Z#dd Z$dd Z%d)ddZ&d*ddZ'dd Z(d+d!d"Z)d,d#d$Z*d%d& Z+d'd( Z,dS )-TestCaseTc                 C   s   t jdS )N*   )nprandomZRandomStater?   r'   r'   r(   rR      s    zTestCase.randomc                 C   s6   t |trtj| }z|`W n tk
r0   Y nX dS )z
        Reset the warnings registry of a module.  This can be necessary
        as the warnings module is buggy in that regard.
        See http://bugs.python.org/issue4180
        N)
isinstancestrsysmodules__warningregistry__AttributeError)r@   r3   r'   r'   r(   reset_module_warnings   s    

zTestCase.reset_module_warningsc              	   c   s0   t jt jttf}| |}|V  W 5 Q R X dS )zr
        A context manager that asserts the enclosed code block fails
        compiling in nopython mode.
        N)r   ZLoweringErrorZTypingError	TypeErrorNotImplementedErrorassertRaises)r@   Z_accepted_errorscmr'   r'   r(   assertTypingError  s     zTestCase.assertTypingErrorc                 g   sb   dd |D }dV  t   dd |D }t|||D ]&\}}}||kr6| d|||f  q6dS )z
        A context manager that asserts the given objects have the
        same reference counts before and after executing the
        enclosed block.
        c                 S   s   g | ]}t |qS r'   rU   getrefcount.0xr'   r'   r(   
<listcomp>  s     z+TestCase.assertRefCount.<locals>.<listcomp>Nc                 S   s   g | ]}t |qS r'   r_   ra   r'   r'   r(   rd     s     z-Refcount changed from %d to %d for object: %r)gccollectzipfail)r@   objectsZold_refcountsZnew_refcountsoldnewobjr'   r'   r(   assertRefCount  s    zTestCase.assertRefCountc              
   G   sj   t   dd |D }|d }tt|dd  D ]2}|| }||kr2| d| d| d| d q2d S )	Nc                 S   s   g | ]}t |qS r'   r_   ra   r'   r'   r(   rd   "  s     z0TestCase.assertRefCountEqual.<locals>.<listcomp>r      z(Refcount for objects does not match. #0(z) != #(z) does not match.)re   rf   rangelenrh   )r@   ri   rcZrc_0iZrc_ir'   r'   r(   assertRefCountEqual   s    zTestCase.assertRefCountEqualc                 c   sf   t  }dV  t  }|j|j }|j|j }|j|j }|j|j }| ||d | ||d dS )z|
        A context manager that asserts no NRT leak was created during
        the execution of the enclosed block.
        Nz-number of data allocs != number of data freesz3number of meminfo allocs != number of meminfo frees)r   get_allocation_statsallocfreemi_allocmi_freeassertEqualr@   rj   rk   Ztotal_allocZ
total_freeZtotal_mi_allocZtotal_mi_freer'   r'   r(   assertNoNRTLeak*  s    zTestCase.assertNoNRTLeakc                 C   s   t |tjrdS t |tjr dS | jD ]}t ||r& dS q&| jD ]}t ||rB dS qB| jD ]}t ||r^ dS q^| jD ]}t ||rz dS qzdS )z
        This function returns a string description of the type family
        that the object in question belongs to.  Possible return values
        are: "exact", "complex", "approximate", "sequence", and "unknown"
        ndarrayenumsequenceexactcomplexapproximateunknown)	rS   rQ   r}   r~   Enum_sequence_typesets_exact_typesets_complex_types_approx_typesets)r@   Znumeric_objecttpr'   r'   r(   _detect_familyE  s"    







zTestCase._detect_familyc                 C   s4   t jdkr,t jdkr,|tdkr,tdS |S dS )z7
        Fix the given *dtype* for comparison.
        win32r    Zint32Zint64N)rU   platformmaxsizerQ   dtype)r@   r   r'   r'   r(   
_fix_dtypec  s
    
zTestCase._fix_dtypec                    s6    j dkrdg j S  fddt j jD S dS )z
        Return the strides of the given array, fixed for comparison.
        Strides for 0- or 1-sized dimensions are ignored.
        r   c                    s"   g | ]\}}|d kr| j  qS )rn   )itemsize)rb   Zstrideshapearrr'   r(   rd   w  s   z)TestCase._fix_strides.<locals>.<listcomp>N)sizendimrg   stridesr   )r@   r   r'   r   r(   _fix_strideso  s
    

zTestCase._fix_stridesc                 C   sB   |  |j|jd |  |j|jd |  | || |d dS )zG
        Test that two arrays have the same shape and strides.
        zshapes differzitemsizes differzstrides differN)rz   r   r   r   )r@   firstsecondr'   r'   r(   assertStridesEqual{  s
    zTestCase.assertStridesEqualr   rn   NFc           
   
   C   sb   z|  ||||||| W n* tk
rD } zt|}	W 5 d}~X Y nX dS | d|||	f  dS )ag  
        Versatile equality testing function with more built-in checks than
        standard assertEqual().

        For arrays, test that layout, dtype, shape are identical, and
        recursively call assertPreciseEqual() on the contents.

        For other sequences, recursively call assertPreciseEqual() on
        the contents.

        For scalars, test that two scalars or have similar types and are
        equal up to a computed precision.
        If the scalars are instances of exact types or if *prec* is
        'exact', they are compared exactly.
        If the scalars are instances of inexact types (float, complex)
        and *prec* is not 'exact', then the number of significant bits
        is computed according to the value of *prec*: 53 bits if *prec*
        is 'double', 24 bits if *prec* is single.  This number of bits
        can be lowered by raising the *ulps* value.
        ignore_sign_on_zero can be set to True if zeros are to be considered
        equal regardless of their sign bit.
        abs_tol if this is set to a float value its value is used in the
        following. If, however, this is set to the string "eps" then machine
        precision of the type(first) is used in the following instead. This
        kwarg is used to check if the absolute difference in value between first
        and second is less than the value set, if so the numbers being compared
        are considered equal. (This is to handle small numbers typically of
        magnitude less than machine precision).

        Any value of *prec* other than 'exact', 'single' or 'double'
        will raise an error.
        Nzwhen comparing %s and %s: %s)_assertPreciseEqualAssertionErrorrT   rh   )
r@   r   r   preculpsmsgignore_sign_on_zeroabs_tolexcZfailure_msgr'   r'   r(   assertPreciseEqual  s    $ zTestCase.assertPreciseEqualc              
      s  d  fdd	} |}	 |}
d|	|
f }rD|df 7 }j|	|
|d |	}|dkr4|j}||j |j|jd |j|jd	 |jj|jjd
 ||d |j|kr|	|}|j|kr |	|}t
|j|jD ] \}}|||| | qdS |dkrjt|t|d t
||D ] \}}|||| | q`dS |dkrd}nv|dkrd}nf|dkrވ|j|j |j|j|| | dS |dkr|j|j d}ndstdt|dr4t|dr4|j|j t|jt|jkr|d|j|jf }rr|df 7 }| z"t|rt|rW dS W n tk
r   Y nX |dk	r|dkrtt|j}nt|tr|}ntd| t|| |k rdS |p|dk}|s|dkr|dkr>d}n|dkrNd}ntd|f d|| d  }|t|t|  }nd}t|j r||j!|j!| ||j"|j"| nTt|tj#tj$frt%|rt%|t%| n|||| n|||| dS )!z-Recursive workhorse for assertPreciseEqual().Nc                    s   |d ks2| |  krdks2n t | s2t |rj| |d  sz6t d| t d|krzd| |f  W q tk
r   Y qX nj| ||d d S )Ng        r   rn   z%s != %s)deltar   )mathisinfrz   copysignrh   Z_formatMessagerZ   ZassertAlmostEqual)r   r   r   r   r   r@   r'   r(   _assertNumberEqual  s&    z8TestCase._assertPreciseEqual.<locals>._assertNumberEqualz Type Family mismatch. (%s != %s)z: %sr   r}   zdifferent number of dimensionszdifferent shapeszdifferent mutabilityzdifferent stridesr   r   T)r   r   Fr~   r   r   zunexpected familyr   z$Mismatching return types (%s vs. %s)epsz)abs_tol is not "eps" or a float, found %ssingle   double5   zunsupported precision %r   rn   )N)&r   rz   r   r   r   r   rG   Z	writeabler   Zastyperg   Zflatr   rq   ZassertIs	__class__valuer   hasattrrS   _bool_typesrh   cmathisnanrZ   rQ   Zfinfotyper   float
ValueErrorabsr   realimagZtimedelta64Z
datetime64Zisnat)r@   r   r   r   r   r   r   r   r   Zfirst_familyZsecond_familyZassertion_messageZcompare_familyr   abZexact_comparisonZrtolbitskr   r'   r   r(   r     s    


 


 
 


   









zTestCase._assertPreciseEqualc                 C   s4   t |d|d}|j}| }| }| || ||fS )z
        Compile the 0-argument *pyfunc* with the given *flags*, and check
        it returns the same result as the pure Python function.
        The got and expected results are returned.
        r'   )rG   )r   entry_pointr   )r@   ZpyfuncrG   rI   Zcfuncexpectedgotr'   r'   r(   run_nullary_funcD  s    zTestCase.run_nullary_func<   c                 C   s  | j }t| j}|||f}ddd |D }	tjdd|	g}
tj }d|d< ztjd |d	< W n t	k
rt   Y nX t
|d
kri n|}|| tj|
tjtj||dd}d|j d|j }| |jd| | d|j | d|j | d|j d
S )a4  
        Runs named unit test(s) as specified in the arguments as:
        test_module.test_class.test_name. test_module must always be supplied
        and if no further refinement is made with test_class and test_name then
        all tests in the module will be run. The tests will be run in a
        subprocess with environment variables specified in `envvars`.
        If given, envvars must be a map of form:
            environment variable name (str) -> value (str)
        It is most convenient to use this method in conjunction with
        @needs_subprocess as the decorator will cause the decorated test to be
        skipped unless the `SUBPROC_TEST` environment variable is set to 1
        (this special environment variable is set by this method such that the
        specified test(s) will not be skipped in the subprocess).


        Following execution in the subprocess this method will check the test(s)
        executed without error. The timeout kwarg can be used to allow more time
        for longer running tests, it defaults to 60 seconds.
        .c                 s   s   | ]}|d k	r|V  qd S Nr'   ra   r'   r'   r(   	<genexpr>i  s      z2TestCase.subprocess_test_runner.<locals>.<genexpr>z-mznumba.runtestsr1   r0   ZCOVERAGE_RCFILEZCOVERAGE_PROCESS_STARTNT)stdoutstderrtimeoutenvuniversal_newlinesz
captured stdout: z
captured stderr: r   OKFAILERROR)rL   r   rK   joinrU   
executableosenvironcopyKeyErrorpytypesMappingProxyTypeupdate
subprocessrunPIPEr   r   rz   
returncodeZassertInZassertNotIn)r@   test_module
test_class	test_nameenvvarsr   ZthemodZtheclspartsZfully_qualified_testcmdZenv_copystatusstreamsr'   r'   r(   subprocess_test_runnerQ  s0    




  zTestCase.subprocess_test_runnerc                    s*    fdd}t | tjr"|| S |S dS )zRuns the decorated test in a subprocess via invoking numba's test
        runner. kwargs timeout and envvars are passed through to
        subprocess_test_runner.c                    s    fdd}|S )Nc                    s@   t jdd dkr4| jj}| j| j|j d n|  d S )Nr0   r1   )r   r   r   r   r   )r   r   getr   rK   r   rL   )r@   rE   kwargs
class_name)r   rD   r   r'   r(   inner  s    z?TestCase.run_test_in_subprocess.<locals>.wrapper.<locals>.innerr'   )rD   r   r   r   )rD   r(   wrapper  s    z0TestCase.run_test_in_subprocess.<locals>.wrapperN)rS   r   FunctionType)Z	maybefuncr   r   r   r'   r   r(   run_test_in_subprocess}  s    zTestCase.run_test_in_subprocessc                    sp   |   }td|tjfi }|d t|t G dd dt}t	| fdd}t
|dd }||fS )	zUse to generate a dummy type unique to this test. Returns a python
        Dummy class and a corresponding Numba type DummyType.zDummyTypeFor{}Zmy_dummyc                   @   s   e Zd ZdS )z'TestCase.make_dummy_type.<locals>.DummyN)rK   rL   rM   r'   r'   r'   r(   Dummy  s   r   c                    s    S r   r'   )valcZ
dummy_typer'   r(   typeof_dummy  s    z.TestCase.make_dummy_type.<locals>.typeof_dummyc                 S   s   t |j S r   )r   contextZget_dummy_value)typrl   r   r'   r'   r(   unbox_dummy  s    z-TestCase.make_dummy_type.<locals>.unbox_dummy)idr   formatr   ZOpaquer   r   objectr   registerr   )r@   Ztest_idZ	DummyTyper   r   r   r'   r   r(   make_dummy_type  s    
zTestCase.make_dummy_typec                 C   s    ddl m} | s| d dS )a  
        Call this to ensure the test is skipped if no suitable external compiler
        is found. This is a method on the TestCase opposed to a stand-alone
        decorator so as to make it "lazy" via runtime evaluation opposed to
        running at test-discovery time.
        r   )external_compiler_worksz(No suitable external compiler was found.N)Znumba.pycc.platformr   skipTest)r@   r   r'   r'   r(   skip_if_no_external_compiler  s    	z%TestCase.skip_if_no_external_compiler)r   rn   NFN)r   rn   NFN)NNNr   )Nr   N)-rK   rL   rM   ZlongMessager   rR   rY   
contextlibr   r^   rm   rt   r|   boolrQ   Zbool_r   intrT   integerbytesbytes_r   r   r   Zinexactr   tuplelistr   ZfloatingZ_float_typesZcomplexfloatingr   r   r   r   r   r   r   r   r   r   r   r   r'   r'   r'   r(   rO      sV   









	     
0     
       
,
rO   c                   @   s   e Zd ZdZdZdS )SerialMixinz-Mixin to mark test for serial execution.
    FN)rK   rL   rM   rN   Z_numba_parallel_test_r'   r'   r'   r(   r    s   r  c              
   c   s4   t t| }tt| | z
dV  W 5 tt| | X dS )z
    Return a context manager that temporarily sets Numba config variable
    *name* to *value*.  *name* must be the name of an existing variable
    in numba.config.
    N)getattrr
   setattr)namer   	old_valuer'   r'   r(   override_config  s
    

r  c              	   c   sT   t j| }|t j| < t  z
dV  W 5 |dkr<t j| = n
|t j| < t  X dS )zk
    Return a context manager that temporarily sets an Numba config environment
    *name* to *value*.
    N)r   r   r   r
   Zreload_config)r
  r   rj   r'   r'   r(   override_env_config  s    



r  c                 C   s(   t | dd}i }t||| ||  S )zj
    Given a *code* string, compile it with globals *globs* and return
    the function named *name*.
    z<string>r   )rJ   rstripeval)r
  codeZglobsconsr'   r'   r(   compile_function  s    r  znumba-testsntz%s.%siQ c                   C   s(   zt t W n tk
r"   Y nX d S r   )r   mkdir_trashcan_dirFileExistsErrorr'   r'   r'   r(   _create_trashcan_dir  s    r  c                  C   s|   t   t } tttD ]\}tjt|}z&t|}|j	| k rPt
j|dd W q tk
rt } zW 5 d }~X Y qX qd S )NT)ignore_errors)time_trashcan_timeoutsortedr   listdirr  pathr   statst_mtimeshutilrmtreeOSError)Zfreshness_thresholdr&   ster'   r'   r(   _purge_trashcan_dir  s    

r&  c                 C   s   t   tj| d td}|S )N-)prefixdir)r&  tempfilemkdtempr  )r(  r  r'   r'   r(   _create_trashcan_subdir  s    r,  c                 C   s   t   t| S )a  
    Create a temporary directory with the given *prefix* that will survive
    at least as long as this process invocation.  The temporary directory
    will be eventually deleted when it becomes stale enough.

    This is necessary because a DLL file can't be deleted while in use
    under Windows.

    An interesting side-effect is to be able to inspect the test files
    shortly after a test suite run.
    )r  r,  )r(  r'   r'   r(   temp_directory  s    r-  c                 C   s"   ddl }|  t|  tj|  S )z
    Import and return a module of the given name.  Care is taken to
    avoid issues due to Python's internal directory caching.
    r   N)	importlibinvalidate_caches
__import__rU   rV   )modnamer.  r'   r'   r(   import_dynamic-  s    r2  c              
   c   s>   t t| }tt| t  zt t| V  W 5 tt| | X dS )zReturn a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.N)r  rU   r	  ioStringIO)stream_nameorig_stdoutr'   r'   r(   captured_output:  s
    
r7  c                   C   s   t dS )zCapture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello
")
    r   r7  r'   r'   r'   r(   captured_stdoutE  s    r9  c                   C   s   t dS )zCapture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello
")
    r   r8  r'   r'   r'   r(   captured_stderrN  s    r:  c               
   c   s2   t  "} tdd | V  W 5 Q R X W 5 Q R X d S )NZDEBUG_CACHET)r9  r  )outr'   r'   r(   capture_cache_logX  s    r<  c                   @   s    e Zd ZdZdd Zdd ZdS )EnableNRTStatsMixinz,Mixin to enable the NRT statistics counters.c                 C   s   t   d S r   )_nrtZmemsys_enable_statsr?   r'   r'   r(   setUpb  s    zEnableNRTStatsMixin.setUpc                 C   s   t   d S r   )r>  Zmemsys_disable_statsr?   r'   r'   r(   tearDowne  s    zEnableNRTStatsMixin.tearDownN)rK   rL   rM   rN   r?  r@  r'   r'   r'   r(   r=  _  s   r=  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )
MemoryLeakTc                 C   s   t   t | _d S r   )re   rf   r   ru   _MemoryLeak__init_statsr?   r'   r'   r(   memory_leak_setupm  s    zMemoryLeak.memory_leak_setupc                 C   s   | j r|   d S r   )_MemoryLeak__enable_leak_checkassert_no_memory_leakr?   r'   r'   r(   memory_leak_teardownr  s    zMemoryLeak.memory_leak_teardownc                 C   sZ   | j }t }|j|j }|j|j }|j|j }|j|j }| || | || d S r   )rB  r   ru   rv   rw   rx   ry   rz   r{   r'   r'   r(   rE  v  s    z MemoryLeak.assert_no_memory_leakc                 C   s
   d| _ d S )NF)rD  r?   r'   r'   r(   disable_leak_check  s    zMemoryLeak.disable_leak_checkN)rK   rL   rM   rD  rC  rF  rE  rG  r'   r'   r'   r(   rA  i  s
   
rA  c                       s(   e Zd Z fddZ fddZ  ZS )MemoryLeakMixinc                    s   t t|   |   d S r   )superrH  r?  rC  r?   r   r'   r(   r?    s    zMemoryLeakMixin.setUpc                    s"   t   |   tt|   d S r   )re   rf   rF  rI  rH  r@  r?   rJ  r'   r(   r@    s    zMemoryLeakMixin.tearDown)rK   rL   rM   r?  r@  __classcell__r'   r'   rJ  r(   rH    s   rH  c            	      c   s   ddl m}  dg}i }dd }z||D ]l}|d}| }|dd D ]}t||}qB|d }t||}t|sxtd	| ||||f< t||| q$dV  W 5 | D ]\\}}}t||| qX dS )
z
    Forbid LLVM code generation during the execution of the context
    manager's enclosed block.

    If code generation is invoked, a RuntimeError is raised.
    r   )codegenz%CPUCodeLibrary._finalize_final_modulec                  _   s   t dd S )Nzcodegen forbidden by test case)RuntimeError)rE   r   r'   r'   r(   rh     s    zforbid_codegen.<locals>.failr   Nz%r should be callable)
numba.corerL  itemsr	  splitr  callabler   )	rL  Zpatchpointsrj   rh   rl   attrnamer   r
  r   r'   r'   r(   forbid_codegen  s$    


rT  c              
   c   s   ddl m} t|j}|  t| }t \}}zt
||  t|dV  W 5 |  t	| t
||  t	| X dS )zt
    Temporarily redirect *fd* to a pipe's write end and return a file object
    wrapping the pipe's read end.
    r   )
_helperlibrN)numbarU  ctypesCDLL__file__Z_numba_flush_stdoutr   duppipeclosedup2r3  open)fdrU  ZlibnumbasaverV  wr'   r'   r(   redirect_fd  s    

rc  c                  C   s   t j } t| S )zRedirect C stdout
    )rU   
__stdout__filenorc  )r`  r'   r'   r(   redirect_c_stdout  s    
rf  c                 C   s   t |}t| ||dS )aK  Spawn a new process to run `func` with a temporary cache directory.

    The childprocess's stdout and stderr will be captured and redirected to
    the current process's stdout and stderr.

    Returns
    -------
    ret : dict
        exitcode: 0 for success. 1 for exception-raised.
        stdout: str
        stderr: str
    )verbose)r-  run_in_new_process_in_cache_dir)rD   Zcache_dir_prefixrg  	cache_dirr'   r'   r(   run_in_new_process_caching  s    rj  c              	   C   s   t d}| }td| |jt| |gd}|  |  | }| }|rz|	 rzt
  t
ddd t
| |r|	 rt
tjd t
dddtjd t
|tjd W 5 Q R X |j||d	S )
a  Spawn a new process to run `func` with a temporary cache directory.

    The childprocess's stdout and stderr will be captured and redirected to
    the current process's stdout and stderr.

    Similar to ``run_in_new_process_caching()`` but the ``cache_dir`` is a
    directory path instead of a name prefix for the directory path.

    Returns
    -------
    ret : dict
        exitcode: 0 for success. 1 for exception-raised.
        stdout: str
        stderr: str
    spawnZNUMBA_CACHE_DIR)targetrE   STDOUTP   r'  )fileZSTDERR)exitcoder   r   )mpZget_contextQueuer  Process_remote_runnerstartr   
get_nowaitstripprintcenterrU   r   rp  )rD   ri  rg  ctxqoutprocr   r   r'   r'   r(   rh    s(    
rh  c              
   C   s~   t  V}t 6}z
|   W n  tk
r:   t  d}Y nX d}W 5 Q R X ||  W 5 Q R X ||  t| dS )z+Used by `run_in_new_process_caching()`
    rn   r   N)	r:  r9  	Exception	traceback	print_excputgetvaluerU   exit)r&   r{  r   r   rp  r'   r'   r(   rt  
  s    

rt  c                   @   s   e Zd ZejefddZdS )CheckWarningsMixinc              	   c   sx   t jdd}t d d V  W 5 Q R X d}|D ]2}|D ](}|t|jkr8| |j| |d7 }q8q0| |t| d S )NT)recordalwaysr   rn   )r7   catch_warningssimplefilterrT   r5   rz   r6   rq   )r@   messagesr6   Zcatchfoundrb  mr'   r'   r(   check_warnings  s    
z!CheckWarningsMixin.check_warningsN)rK   rL   rM   r   r   RuntimeWarningr  r'   r'   r'   r(   r    s   r  c                  K   sN   | sdS g }|   D ].\}}t|tr0d|}|d|| qd|S )N z"{}"z{}={}z, )rP  rS   rT   r   appendr   )jit_optionsr;  keyr   r'   r'   r(   _format_jit_options)  s    

r  c              
   k   s   ztd}dt	t
 dd}tj||d }tf |}t|d}| j|d}|| W 5 Q R X t jd	| t|}|V  W 5 t j|d t j| t| X dS )
a  A context manager that creates and imports a temporary module
    from sources provided in ``source_lines``.

    Optionally it is possible to provide jit options for ``jit_module`` if it
    is explicitly used in ``source_lines`` like ``jit_module({jit_options})``.
    NZtest_temp_moduleztest_temp_module_{}r'  _z.pyrb  )r  r   )rU   rV   popr  remover!  r"  r-  r   rT   uuiduuid4replacer   r   r  r_  writeinsertr.  import_module)Zsource_linesr  Ztemp_module_nametempdirZtemp_module_pathflinesr   r'   r'   r(   create_temp_module4  s     	


r     c           	      C   sr   |dkrg }t jg| d| g }tj|tjtj|d}|j|d\}}|jdkrjd}t||j| f ||fS )zRun a snippet of Python code in a subprocess with flags, if any are
    given. 'env' is passed to subprocess.Popen(). 'timeout' is passed to
    popen.communicate().

    Returns the stdout and stderr of the subprocess after its termination.
    N-c)r   r   r   )r   r   z/process failed with code %s: stderr follows
%s
)	rU   r   r   Popenr   communicater   r   decode)	r  rG   r   r   r   popenr;  errr   r'   r'   r(   run_in_subprocessR  s    
 
r  r"   c              	      s  t d}t }td}|dkr.td|ddt|dd|d	|j	g}t
j|t
jd
  j}t| j}|  d fdd	}	zftj jd}
|
  |   |    dkrt|tj nd}|	|    |	  | }W 5 |
  |  X W 5 Q R X |S )a)  Runs strace whilst executing the function work() in the current process,
    captures the listed syscalls (list of strings). Takes an optional timeout in
    seconds, default is 10, if this is exceeded the process will be sent a
    SIGKILL. Returns a list of lines that are output by strace.
    zw+tstraceNz'No valid 'strace' binary could be foundz-qz-pz-e,z-o)r   r  c                    s*    j }|dkr&d| d|  }t|d S )Nr   z0strace exited non-zero, process return code was:z. )r   rM  )problemretr   r  r'   r(   check_return  s    zstrace.<locals>.check_return)rl  z)If this is SIGKILL, increase the timeout?)r  )r*  NamedTemporaryFiler   getpidr!  whichr   rT   r   r
  r   r  r   pid	threadingTimerkillru  cancelThreadr  flushpollsignalSIGINTwait	readlines)ZworkZsyscallsr   ZntfZ
parent_pidZstrace_binaryr   Z
strace_pidZthread_timeoutr  Zthread_commsr  Zstrace_datar'   r  r(   r  e  sD    
   r  c                  C   sR   t jdsdS dd } d}zt| |g}W n tk
rB   Y dS X |d|kS )z)Checks if strace is supported and workingr*   Fc                   S   s   t tjddg d S )Nr  zexit())r   r   rU   r   r'   r'   r'   r(   force_clone  s    z%strace_supported.<locals>.force_clonecloner  )rU   r   
startswithr  r}  r   )r  Zsyscalltracer'   r'   r(   strace_supported  s    r  c                   @   s   e Zd ZdZdd ZdS )IRPreservingTestPipelinez Same as the standard pipeline, but preserves the func_ir into the
    metadata store after legalisation, useful for testing IR changesc                 C   s.   t | jd}d|_|tt |  |gS )NZir_preserving_custom_pipeF)r   Zdefine_nopython_pipelinestateZ
_finalizedZadd_pass_afterr   r   finalize)r@   Zpipeliner'   r'   r(   define_pipelines  s     z)IRPreservingTestPipeline.define_pipelinesN)rK   rL   rM   rN   r  r'   r'   r'   r(   r    s   r  c               	   C   s  ddl } ddl m} tjtjt}tj|ddd}tj|sPt	
d ttj|d}| }W 5 Q R X | j||d}|d }td	d
 }|dd D ]:}	|	d d }
|
 D ] }||d  |d   d7  < qqdddddg}tjj|f| }tj|st	
d ttj|d}| }W 5 Q R X | j||d}|d d d d }
|
 D ]"}||d  |d   d7  < qhtd td t| D ]:\}}| D ]&\}}td| d|dd|  qqdS )a-  This is a utility function that prints out the map of NumPy to Python
    versions and how many of that combination are being tested across all the
    declared config for azure-pipelines. It is useful to run when updating the
    azure-pipelines config to be able to quickly see what the coverage is.r   N)Loaderz..zazure-pipelines.ymlz&'azure-pipelines.yml' is not availablertjobsc                   S   s   t tS r   )r   r  r'   r'   r'   r(   <lambda>      z$print_azure_matrix.<locals>.<lambda>r   
parametersmatrixZNUMPYPYTHONrn   ZbuildscriptsZazurezazure-windows.ymlz$'azure-windows.yml' is not availableZstrategyzNumPy | Python | Countz----------------------- z |  z<4z  |   )yamlr  r   r  dirnameabspathrZ  r   isfiler@   r   r_  readloadr   valuesrx  r  rP  )r  r  	base_pathZ
azure_piper  dataZpipe_ymlZ	templatesZ	py2np_mapZtmpltr  setupZwinpathZazure_windowsZwindows_ymlZnpverZpyspyvercountr'   r'   r(   print_azure_matrix  s<    
 
 r  )T)NNr  )r"   )rN   r   r   collectionsr   r~   re   r   r   r   r  r!  r   rU   r*  r  r  r3  rX  multiprocessingrq  r7   r~  r   r  r.  r   r   	functoolsr   numpyrQ   rW  r   rO  r   r   r	   r
   r   Znumba.core.typingr   Znumba.core.compilerr   r   r   r   r   r   Znumba.core.typed_passesr   Znumba.core.untyped_passesr   r%   Znumba.core.runtimer   Znumba.npr   r   r>  Znumba.core.extendingr   r   r   r   r   r   Znumba.core.datamodel.modelsr   ZscipyImportErrorZcoverageZprocess_startupZenable_pyobj_flagsZenable_pyobjectZforce_pyobj_flagsZforce_pyobjectZno_pyobj_flagsZ	nrt_flagsZnrtZmake_tag_decoratortagr   r   Z_32bitZis_parfors_unsupportedZskipIfZskip_parfors_unsupportedZ
skipUnlessr$   Zskip_unless_py10_or_laterZskip_unless_py10Zskip_if_32bitr)   Z_msgZskip_unless_scipyZ	SUPPORTEDZskip_unless_cffiZ_lnx_reasonr  Z
linux_onlyZ_win_reasonZwindows_onlymachineZ
_is_armv7lZdisabled_testZskip_ppc64le_issue4563r   r   r   Zhas_typeguardZskip_unless_typeguardZskip_if_typeguardZskip_ppc64le_issue6465unameZ_unamesystemZIS_OSX_ARM64Zskip_m1_llvm_rtdyld_failureZskip_m1_fenv_errorsZscipy.linalg.cython_lapackZ
has_lapackZneeds_lapackZscipy.linalg.cython_blasZhas_blasZ
needs_blasZ
_exec_condZneeds_subprocess
setuptoolsZhas_setuptoolsZneeds_setuptoolsr9   r   r:   rO   r  r  r  r  r  r
  r  r   
gettempdirgetuidr  r  r&  r,  r-  r2  r7  r9  r:  r<  r=  rA  rH  rT  rc  rf  rK   rj  rh  rt  r  r  r  r  r  r  r  r  r'   r'   r'   r(   <module>   s`    

  


   R



	



"

'


A