o
    1&i                  	   @   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/ dd
l0m1Z1 ddl2m3Z3 ddl4Z4ddl5m6Z6 ddl7m8Z8 ddl5m9Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA ddlBmCZC zddlDZDW n eEy   dZDY nw zddlFZFW n	 eEy   Y nw eFG  e, ZHdeH_Ie, ZJdeJ_Ke, ZLe, ZMdeM_Ne!Og dZPePdZQejRdkZSeSZTe4UeTdZVe4We%jXdkdZYe4We%jXdkdZZe4We%jXdkdZ[e4Ue%jXdkoMej\ddZ]e4Uej\do^e^ dkd Z_e4UeSd!Z`e8jad"kZbe4Uebd#Zcedeee	jfgd$dZh	 e4Uehd%Zid&d' Zjd(d) Zkd*d+ Zld,d- Zmd.Zne4UeDdu enZoe4We)jpd/Zqd0Zre4Uej\d erZsd1Zte4Uej\d etZue^ d2kZve4Udd3Zwe4Ue^ d4kd5Zxede	jfgd6dZye4Weyd7Zze4Ueyd8Z{e4Ue^ d4kd9Z|e4Ue^ d4kd:Z}e~ Zejd;kZe4Ued<Zeoej^d=kZzddlZDdZW n eEy)   d>ZY nw e4Wed?ZzddlZDdZW n eEyD   d>ZY nw e4Wed@Ze	jfgdAddBkZe4WedCZzddlZdZW n eEefyp   d>ZY nw e4WedDZdEdF ZG dGdH dHe4jZG dIdJ dJeZejdKdL ZejdMdN ZdOdP ZdQZe	jdRkre	je eZne	je dSee	 f ZdTZdUdV ZdWdX ZdYdZ Zd[d\ Zd]d^ Zejd_d` Zdadb Zdcdd Zejdedf ZG dgdh dheZG didj djeZG dkdl dleeZejdmdn Zejdodp Zdqdr Zdsdt ZedfdudvZddwdxZdydz ZG d{d| d|eZd}d~ Zejdd ZdddZdddZdd ZG dd de.Zdd 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FlagsDEFAULT_FLAGSCompilerBaseDefaultPassBuilder)IRLegalization)
PreserveIR)rtsys)numpy_support)_nrt_python)overload_methodtypeof_implregister_modelunboxNativeValuemodels)OpaqueModelT)Z	importantZlong_runningalways_testr           zparfors not supported)   
   zneeds Python 3.10 or laterzneeds Python 3.10r       zneeds Python 3.12r       winz'Not supported on Python 3.13 on Windowslinuxaarch64zNot supported on Linux aarch64zNot supported on 32 bit   r   zNot supported on numpy 2.0+Z_NUMBA_REDUCED_TESTINGzSkipped for reduced testingc                 C      t jdkr
t| S | S )N)r       r	   	PYVERSIONunittestexpectedFailurefn r3   >C:\wamp64\www\opt\env\Lib\site-packages\numba/tests/support.pyexpected_failure_py311      

r5   c                 C   r+   )Nr"   r-   r1   r3   r3   r4   expected_failure_py312   r6   r7   c                 C   r+   )Nr$   r-   r1   r3   r3   r4   expected_failure_py313   r6   r8   c                 C   r+   )Nr)   )r   numpy_versionr/   r0   r1   r3   r3   r4   expected_failure_np2   r6   r:   zSciPy needed for testzrequires cffizlinux only testzWindows-only test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_64SVR4zInvalid PPC CTR loopDarwinz-fenv.h-like functionality unreliable on macOS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categoryrB   N)warningsfilterwarningsr   ZNumbaWarningr3   r3   r3   r4   ignore_internal_warnings   s   
rH   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 d!Z(d*d"d#Z)d$d% Z*d&d' Z+dS )+TestCaseTc                 C   s   t jdS )N*   )nprandomZRandomStateselfr3   r3   r4   rL     s   zTestCase.randomc                 C   s4   t |tr
tj| }z|`W dS  ty   Y dS w )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)rN   rB   r3   r3   r4   reset_module_warnings  s   


zTestCase.reset_module_warningsc                 c   sH    t jt jttf}| |}|V  W d   dS 1 sw   Y  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)rN   Z_accepted_errorscmr3   r3   r4   assertTypingError  s   "zTestCase.assertTypingErrorc                 g   sd    dd |D }dV  t   dd |D }t|||D ]\}}}||kr/| d|||f  qdS )z
        A context manager that asserts the given objects have the
        same reference counts before and after executing the
        enclosed block.
        c                 S      g | ]}t |qS r3   rQ   getrefcount.0xr3   r3   r4   
<listcomp>0      z+TestCase.assertRefCount.<locals>.<listcomp>Nc                 S   r[   r3   r\   r^   r3   r3   r4   ra   3  rb   z-Refcount changed from %d to %d for object: %r)gccollectzipfail)rN   objectsZold_refcountsZnew_refcountsoldnewobjr3   r3   r4   assertRefCount)  s   zTestCase.assertRefCountc              
   G   sj   t   dd |D }|d }tt|dd  D ]}|| }||kr2| d| d| d| d qd S )	Nc                 S   r[   r3   r\   r^   r3   r3   r4   ra   ;  rb   z0TestCase.assertRefCountEqual.<locals>.<listcomp>r      z(Refcount for objects does not match. #0(z) != #(z) does not match.)rc   rd   rangelenrf   )rN   rg   rcZrc_0iZrc_ir3   r3   r4   assertRefCountEqual9  s   
zTestCase.assertRefCountEqualc                 c   sh    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rN   rh   ri   Ztotal_allocZ
total_freeZtotal_mi_allocZtotal_mi_freer3   r3   r4   assertNoNRTLeakC  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 ||r+ dS q!| jD ]
}t ||r9 dS q/| jD ]
}t ||rG dS q=d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)	rO   rK   r{   r|   Enum_sequence_typesets_exact_typesets_complex_types_approx_typesets)rN   Znumeric_objecttpr3   r3   r4   _detect_family^  s*   







zTestCase._detect_familyc                 C   s0   t jdkrt jdkr|tdkrtdS |S )z7
        Fix the given *dtype* for comparison.
        win32r   Zint32Zint64)rQ   platformmaxsizerK   dtype)rN   r   r3   r3   r4   
_fix_dtype|  s   
zTestCase._fix_dtypec                    s2    j dkrdg j S  fddt j j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 )rl   )itemsize)r_   Zstrideshapearrr3   r4   ra     s
    z)TestCase._fix_strides.<locals>.<listcomp>)sizendimre   stridesr   )rN   r   r3   r   r4   _fix_strides  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)rx   r   r   r   )rN   firstsecondr3   r3   r4   assertStridesEqual  s
   zTestCase.assertStridesEqualr~   rl   NFc           
   
   C   sb   z|  ||||||| W dS  ty$ } z
t|}	W Y d}~nd}~ww | 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AssertionErrorrP   rf   )
rN   r   r   preculpsmsgignore_sign_on_zeroabs_tolexcZfailure_msgr3   r3   r4   assertPreciseEqual  s   $zTestCase.assertPreciseEqualc              
      s  d  fdd	} |}	 |}
d|	|
f }r"|df 7 }j|	|
|d |	}|dkr|j}||j |j|jd |j|jd	 |jj|jjd
 ||d |j|krt|	|}|j|kr~|	|}t
|j|jD ]\}}|||| | qdS |dkrjt|t|d t
||D ]\}}|||| | qdS |dkrd}n5|dv rd}n.|dkr|j|j |j|j|| | dS |dkr|j|j d}nJ dt|drt|dr|j|j t|jt|jkr2d|j|jf }r-|df 7 }| zt|rBt|rBW dS W n
 tyM   Y nw |dur{|dkratt|j}nt|trj|}ntd| t|| |k r{dS |p|dk}|s|dkr|dkrd}n|dkrd}ntd|f d|| d  }|t|t|  }nd}t|jr||j |j | ||j!|j!| dS t|tj"tj#frt$|rt$|t$| dS |||| dS |||| dS )!z-Recursive workhorse for assertPreciseEqual().Nc                    s   |d u s| |  krdksn t | st |rOj| |d  sMzt d| t d|kr@d| |f  W d S W d S  tyL   Y d S w d S j| ||d d S )Ng        r   rl   z%s != %s)deltar   )mathisinfrx   copysignrf   Z_formatMessagerV   ZassertAlmostEqual)r   r   r   r   r   rN   r3   r4   _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 %rr*   rl   N)%r   rx   r   r   r   r   flagsZ	writeabler   Zastypere   Zflatr   ro   ZassertIs	__class__valuehasattrrO   _bool_typesrf   cmathisnanrV   rK   Zfinfotyper   float
ValueErrorabsr   realimagZtimedelta64Z
datetime64Zisnat)rN   r   r   r   r   r   r   r   r   Zfirst_familyZsecond_familyZassertion_messageZcompare_familyr   abZexact_comparisonZrtolbitskr   r3   r   r4   r     s   














zTestCase._assertPreciseEqual<   r@   c                 C   s@  | j }t| j}	|||f}
ddd |
D }g }|dur2| D ]\}}||  ||  q!tjg|dd|}tj	
 }||d< z	tj	d |d	< W n	 tyY   Y nw t|du rbi n|}|| tj|tjtj||d
d}d|j d|j }| |jd| d}||jv r| | |S | d|j |S )a  
        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)
        If given, flags must be a map of form:
            flag including the `-` (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
        the same value of ``_subproc_test_env``
        (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 ur|V  qd S r   r3   r^   r3   r3   r4   	<genexpr>y  s    z2TestCase.subprocess_test_runner.<locals>.<genexpr>Nz-mznumba.runtestsr?   ZCOVERAGE_RCFILEZCOVERAGE_PROCESS_STARTT)stdoutstderrtimeoutenvuniversal_newlinesz
captured stdout: z
captured stderr: r   zNO TESTS RANOK)
__module__r   __name__joinitemsappendrQ   
executableosenvironcopyKeyErrorpytypesMappingProxyTypeupdate
subprocessrunPIPEr   r   rx   
returncodeskipTestZassertIn)rN   test_module
test_class	test_nameenvvarsr   r   _subproc_test_envZthemodZtheclspartsZfully_qualified_testZ
flags_argsflagr   cmdZenv_copystatusstreamsZno_tests_ranr3   r3   r4   subprocess_test_runner]  sF   







zTestCase.subprocess_test_runnerc                    s&    fdd}t | tjr|| S |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                    sH   t jdd jkr| jj}| j| j|j jd d S |  d S )Nr?   )r   r   r   r   r   r   )r   r   getr   r   r   r   )rN   argskwargs
class_name)r   funcr   r3   r4   inner  s   
z?TestCase.run_test_in_subprocess.<locals>.wrapper.<locals>.innerr3   )r   r   r   r   )r   r4   wrapper  s   z0TestCase.run_test_in_subprocess.<locals>.wrapper)rO   r   FunctionType)Z	maybefuncr   r   r   r3   r   r4   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)r   r   __qualname__r3   r3   r3   r4   Dummy  s    r   c                    s    S r   r3   )valcZ
dummy_typer3   r4   typeof_dummy  s   z.TestCase.make_dummy_type.<locals>.typeof_dummyc                 S   s   t |j S r   )r   contextZget_dummy_value)typrj   r   r3   r3   r4   unbox_dummy  s   z-TestCase.make_dummy_type.<locals>.unbox_dummy)idr   formatr   ZOpaquer   r   objectr   registerr   )rN   Ztest_idZ	DummyTyper   r   r   r3   r   r4   make_dummy_type  s   
zTestCase.make_dummy_typec                 C   s$   ddl m} | s| d dS 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   r   )rN   r   r3   r3   r4   skip_if_no_external_compiler  s   	z%TestCase.skip_if_no_external_compiler)r~   rl   NFN)NNNr   Nr@   )Nr   N),r   r   r   ZlongMessager   rL   rU   
contextlibr   rZ   rk   rr   rz   boolrK   Zbool_r   intrP   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   r3   r3   r3   r4   rI     sP    









	
0
 

:rI   c                   @   s   e Zd ZdZdZdS )SerialMixinz-Mixin to mark test for serial execution.
    FN)r   r   r   __doc__Z_numba_parallel_test_r3   r3   r3   r4   r    s    r  c              
   c   s@    t t| }tt| | zdV  W tt| | dS tt| | w )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_valuer3   r3   r4   override_config  s   
r  c              	   c   sx    t j| }|t j| < t  zdV  W |du rt j| = n|t j| < t  dS |du r2t j| = n|t j| < t  w )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   rh   r3   r3   r4   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   )compilerstripeval)r  codeZglobsconsr3   r3   r4   compile_function  s   r  znumba-testsntz%s.%siQ c                   C   s&   zt t W d S  ty   Y d S w r   )r   mkdir_trashcan_dirFileExistsErrorr3   r3   r3   r4   _create_trashcan_dir"  s
   r  c                  C   s|   t   t } tttD ].}tjt|}zt|}|j	| k r(t
j|dd W q ty; } zW Y d }~qd }~ww d S )NT)ignore_errors)time_trashcan_timeoutsortedr   listdirr  pathr   statst_mtimeshutilrmtreeOSError)Zfreshness_thresholdr2   ster3   r3   r4   _purge_trashcan_dir(  s   

r)  c                 C   s   t   tj| d td}|S )N-)prefixdir)r)  tempfilemkdtempr  )r+  r!  r3   r3   r4   _create_trashcan_subdir5  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+  r3   r3   r4   temp_directory:  s   r0  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__rQ   rR   )modnamer1  r3   r3   r4   import_dynamicJ  s   
r5  c              
   c   sJ    t t| }tt| t  zt t| V  W tt| | dS tt| | w )zReturn a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.N)r
  rQ   r  ioStringIO)stream_nameorig_stdoutr3   r3   r4   captured_outputW  s   
r:  c                   C      t dS )zCapture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello
")
    r   r:  r3   r3   r3   r4   captured_stdoutb     r=  c                   C   r;  )zCapture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello
")
    r   r<  r3   r3   r3   r4   captured_stderrk  r>  r?  c               	   c   sn    t  )} tdd | V  W d    n1 sw   Y  W d    d S W d    d S 1 s0w   Y  d S )NZDEBUG_CACHET)r=  r  )outr3   r3   r4   capture_cache_logu  s   "rA  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      t   d S r   )_nrtZmemsys_enable_statsrM   r3   r3   r4   setUp     zEnableNRTStatsMixin.setUpc                 C   rC  r   )rD  Zmemsys_disable_statsrM   r3   r3   r4   tearDown  rF  zEnableNRTStatsMixin.tearDownN)r   r   r   r	  rE  rG  r3   r3   r3   r4   rB  |  s    rB  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   )rc   rd   r   rs   _MemoryLeak__init_statsrM   r3   r3   r4   memory_leak_setup  s   zMemoryLeak.memory_leak_setupc                 C   s   | j r	|   d S d S r   )_MemoryLeak__enable_leak_checkassert_no_memory_leakrM   r3   r3   r4   memory_leak_teardown  s   zMemoryLeak.memory_leak_teardownc                 C   sZ   | j }t }|j|j }|j|j }|j|j }|j|j }| || | || d S r   )rI  r   rs   rt   ru   rv   rw   rx   ry   r3   r3   r4   rL    s   z MemoryLeak.assert_no_memory_leakc                 C   s
   d| _ d S )NF)rK  rM   r3   r3   r4   disable_leak_check  s   
zMemoryLeak.disable_leak_checkN)r   r   r   rK  rJ  rM  rL  rN  r3   r3   r3   r4   rH    s    
rH  c                       s(   e Zd Z fddZ fddZ  ZS )MemoryLeakMixinc                    s   t t|   |   d S r   )superrO  rE  rJ  rM   r   r3   r4   rE    s   zMemoryLeakMixin.setUpc                    s"   t   |   tt|   d S r   )rc   rd   rM  rP  rO  rG  rM   rQ  r3   r4   rG    s   zMemoryLeakMixin.tearDown)r   r   r   rE  rG  __classcell__r3   r3   rQ  r4   rO    s    rO  c            	      c   s    ddl m}  dg}i }dd }zP|D ]6}|d}| }|dd D ]}t||}q"|d }t||}t|s=J d	| ||||f< t||| qdV  W | D ]\\}}}t||| qRdS | D ]\\}}}t||| qew )
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)Nzcodegen forbidden by test case)RuntimeError)r   r   r3   r3   r4   rf     s   zforbid_codegen.<locals>.failr   Nz%r should be callable)
numba.corerS  splitr
  callabler  r   )	rS  Zpatchpointsrh   rf   r  r   rj   attrnamer   r3   r3   r4   forbid_codegen  s,   

rZ  c              
   c   s    ddl m} t|j}|  t| }t \}}z$t	||  t
|dV  W |  t| t	||  t| dS |  t| t	||  t| w )zt
    Temporarily redirect *fd* to a pipe's write end and return a file object
    wrapping the pipe's read end.
    r   )
_helperlibrN)numbar[  ctypesCDLL__file__Z_numba_flush_stdoutr   duppipedup2r6  openclose)fdr[  Zlibnumbasaver\  wr3   r3   r4   redirect_fd  s"   


ri  c                  C      t j } t| S )zRedirect C stdout
    )rQ   
__stdout__filenori  rf  r3   r3   r4   redirect_c_stdout     
rn  c                  C   rj  )zRedirect C stderr
    )rQ   
__stderr__rl  ri  rm  r3   r3   r4   redirect_c_stderr  ro  rq  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)r0  run_in_new_process_in_cache_dir)r   Zcache_dir_prefixrr  	cache_dirr3   r3   r4   run_in_new_process_caching  s   ru  c                 C   s   t d}| }td|T |jt| |gd}|  |  | }| }|r=|	 r=t
  t
ddd t
| |r[|	 r[t
tjd t
dddtjd t
|tjd W d	   n1 sew   Y  |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
    ZspawnZNUMBA_CACHE_DIR)targetr   STDOUTP   r*  )fileZSTDERRN)exitcoder   r   )mpZget_contextQueuer  Process_remote_runnerstartr   
get_nowaitstripprintcenterrQ   r   rz  )r   rt  rr  ctxqoutprocr   r   r3   r3   r4   rs    s,   
rs  c              
   C   s   t  9}t }z|   W n ty   t  d}Y nw d}W d   n1 s)w   Y  ||  W d   n1 s?w   Y  ||  t| dS )z+Used by `run_in_new_process_caching()`
    rl   r   N)	r?  r=  	Exception	traceback	print_excputgetvaluerQ   exit)r2   r  r   r   rz  r3   r3   r4   r~  .  s   

r~  c                   @   s   e Zd ZejefddZdS )CheckWarningsMixinc                 c   s    t jdd}t d d V  W d    n1 sw   Y  d}|D ]}|D ]}|t|jv r;| |j| |d7 }q'q#| |t| d S )NT)recordalwaysr   rl   )rF   catch_warningssimplefilterrP   rD   rx   rE   ro   )rN   messagesrE   Zcatchfoundrh  mr3   r3   r4   check_warnings?  s   
z!CheckWarningsMixin.check_warningsN)r   r   r   r   r   RuntimeWarningr  r3   r3   r3   r4   r  >  s    r  c                  K   sN   | sdS g }|   D ]\}}t|trd|}|d|| q
d|S )N z"{}"z{}={}z, )r   rO   rP   r   r   r   )jit_optionsr@  keyr   r3   r3   r4   _format_jit_optionsM  s   


r  c              
   k   s    zet d}dtt dd}tj||d }t	d
i |}t
|d}| j|d}|| W d   n1 s>w   Y  tjd	| t|}|V  W tj|d tj| t| dS tj|d tj| t| w )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})``.
    Ztest_temp_moduleztest_temp_module_{}r*  _z.pyrh  )r  Nr   r3   )r0  r   rP   uuiduuid4replacer   r!  r   r  rd  writerQ   insertr1  import_modulerR   popremover$  r%  )Zsource_linesr  tempdirZtemp_module_nameZtemp_module_pathflinesr   r3   r3   r4   create_temp_moduleX  s*   	
r     c           	      C   sr   |du rg }t jg| d| g }tj|tjtj|d}|j|d\}}|jdkr5d}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
)	rQ   r   r   Popenr   communicater   r   decode)	r  r   r   r   r   popenr@  errr   r3   r3   r4   run_in_subprocessv  s   

r  r!   c              	      s6  t d}t }td}|du rtd|ddt|dd|d	|j	g}t
j|t
jd
  j}t| j}|  d fdd	}	z;tj jd}
|
  |   |    du ret|tj nd}|	|    |	  | }W |
  |  n	|
  |  w W d   |S 1 sw   Y  |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   rT  )problemretr   r  r3   r4   check_return  s   zstrace.<locals>.check_return)rv  z)If this is SIGKILL, increase the timeout?)r  )r-  NamedTemporaryFiler   getpidr$  whichr   rP   r   r  r   r  r   pid	threadingTimerkillr  Threadr  flushpollsignalSIGINTwait	readlinescancel)ZworkZsyscallsr   ZntfZ
parent_pidZstrace_binaryr   Z
strace_pidZthread_timeoutr  Zthread_commsr  Zstrace_datar3   r  r4   r    sH   




66r  c                  C   sP   t jdsdS dd } d}zt| |g}W n
 ty    Y dS w |d|v 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   rQ   r   r3   r3   r3   r4   force_clone  s   z%strace_supported.<locals>.force_clonecloner  )rQ   r   
startswithr  r  r   )r  Zsyscalltracer3   r3   r4   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)rN   Zpipeliner3   r3   r4   define_pipelines  s   z)IRPreservingTestPipeline.define_pipelinesN)r   r   r   r	  r  r3   r3   r3   r4   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|s't	dt
tj|d}| }W d   n1 s?w   Y  | j||d}|d }td	d
 }|dd D ]}	|	d d }
|
 D ]}||d  |d   d7  < qgq[g d}tjj|g|R  }tj|st	dt
tj|d}| }W d   n1 sw   Y  | j||d}|d d d d }
|
 D ]}||d  |d   d7  < qtd td t| D ]\}}| D ]\}}td| d|dd|  qqtdd
 }t| D ]\}}| D ]\}}||| |< qq
td td dd
 }t| |dD ]\}}| D ]\}}td|dd| d|  q<q4d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)Loader..zazure-pipelines.ymlz&'azure-pipelines.yml' is not availablertjobsc                   S      t tS r   r   r  r3   r3   r3   r4   <lambda>       z$print_azure_matrix.<locals>.<lambda>r*   
parametersmatrixZNUMPYZPYTHONrl   )r  r  ZbuildscriptsZazurezazure-windows.ymlz$'azure-windows.yml' is not availableZstrategyzNumPy | Python | Countz----------------------- z |  z<4z  |   c                   S   r  r   r  r3   r3   r3   r4   r    r  z
Python | NumPy | Countc                 S   s   t | d dd S )Nr   r   rl   )r  rW  )r`   r3   r3   r4   r  "  rb   )r  )yamlr  r   r!  dirnameabspathr`  r   isfilerT  rd  readloadr   valuesr  r  r   )r  r  	base_pathZ
azure_piper  dataZpipe_ymlZ	templatesZ	py2np_mapZtmpltr  setupZwinpathZazure_windowsZwindows_ymlZnpverZpyspyvercountZrev_mapZsorterZnpsr3   r3   r4   print_azure_matrix  s^   

 r  )T)NNr  )r!   )r	  r   r   collectionsr   r|   rc   r   r   r   r  r$  r   rQ   r-  r  r  r6  r^  multiprocessingr{  rF   r  r   r  r1  r   r   	functoolsr   numpyrK   r]  r   rV  r   r   r	   r
   r   Znumba.core.typingr   Znumba.core.compilerr   r   r   r   r   Znumba.core.typed_passesr   Znumba.core.untyped_passesr   r/   Znumba.core.runtimer   Znumba.npr   r   rD  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_unless_py312r  Zskip_if_py313_on_windowsmachineZskip_if_linux_aarch64Zskip_if_32bitr9   Z
IS_NUMPY_2Zskip_if_numpy_2r  r  r   r   ZREDUCED_TESTINGZskip_if_reduced_testingr5   r7   r8   r:   Z_msgZskip_unless_scipyZ	SUPPORTEDZskip_unless_cffiZ_lnx_reasonZ
linux_onlyZ_win_reasonZwindows_onlyZ
_is_armv7lZdisabled_testZskip_ppc64le_issue4563Zhas_typeguardZskip_unless_typeguardZskip_if_typeguardZskip_ppc64le_issue6465Zskip_ppc64le_invalid_ctr_loopunameZ_unamesystemZIS_MACOSZskip_macos_fenv_errorsZIS_MACOS_ARM64Zscipy.linalg.cython_lapackZ
has_lapackZneeds_lapackZscipy.linalg.cython_blasZhas_blasZ
needs_blasZ
_exec_condZneeds_subprocess
setuptoolsZhas_setuptoolsr&  Zneeds_setuptoolsrH   rI   r   r  r  r  r  r  r  r!  r   
gettempdirgetuidr  r  r)  r/  r0  r5  r:  r=  r?  rA  rB  rH  rO  rZ  ri  rn  rq  r   ru  rs  r~  r  r  r  r  r  r  r  r  r3   r3   r3   r4   <module>   s    

	

   V



	

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