nnilayy commited on
Commit
0d830fb
·
verified ·
1 Parent(s): 5c75d57

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so +3 -0
  3. lib/python3.10/site-packages/babel/locale-data/en_SS.dat +0 -0
  4. lib/python3.10/site-packages/babel/locale-data/fo_DK.dat +0 -0
  5. lib/python3.10/site-packages/babel/locale-data/fr_GF.dat +0 -0
  6. lib/python3.10/site-packages/babel/locale-data/ie_EE.dat +0 -0
  7. lib/python3.10/site-packages/babel/locale-data/kw.dat +0 -0
  8. lib/python3.10/site-packages/babel/locale-data/mic_CA.dat +0 -0
  9. lib/python3.10/site-packages/babel/locale-data/prg.dat +0 -0
  10. lib/python3.10/site-packages/babel/locale-data/ps_AF.dat +0 -0
  11. lib/python3.10/site-packages/babel/locale-data/sw_KE.dat +0 -0
  12. lib/python3.10/site-packages/numba/tests/__init__.py +33 -0
  13. lib/python3.10/site-packages/numba/tests/cache_usecases.py +172 -0
  14. lib/python3.10/site-packages/numba/tests/cffi_usecases.py +197 -0
  15. lib/python3.10/site-packages/numba/tests/complex_usecases.py +93 -0
  16. lib/python3.10/site-packages/numba/tests/ctypes_usecases.py +114 -0
  17. lib/python3.10/site-packages/numba/tests/doctest_usecase.py +31 -0
  18. lib/python3.10/site-packages/numba/tests/enum_usecases.py +55 -0
  19. lib/python3.10/site-packages/numba/tests/parfor_iss9490_usecase.py +78 -0
  20. lib/python3.10/site-packages/numba/tests/test_analysis.py +1007 -0
  21. lib/python3.10/site-packages/numba/tests/test_annotations.py +252 -0
  22. lib/python3.10/site-packages/numba/tests/test_array_exprs.py +742 -0
  23. lib/python3.10/site-packages/numba/tests/test_array_manipulation.py +1588 -0
  24. lib/python3.10/site-packages/numba/tests/test_asnumbatype.py +170 -0
  25. lib/python3.10/site-packages/numba/tests/test_auto_constants.py +38 -0
  26. lib/python3.10/site-packages/numba/tests/test_boundscheck.py +268 -0
  27. lib/python3.10/site-packages/numba/tests/test_byteflow.py +94 -0
  28. lib/python3.10/site-packages/numba/tests/test_cfunc.py +408 -0
  29. lib/python3.10/site-packages/numba/tests/test_codegen.py +264 -0
  30. lib/python3.10/site-packages/numba/tests/test_ctypes.py +255 -0
  31. lib/python3.10/site-packages/numba/tests/test_deprecations.py +262 -0
  32. lib/python3.10/site-packages/numba/tests/test_dispatcher.py +1193 -0
  33. lib/python3.10/site-packages/numba/tests/test_exceptions.py +475 -0
  34. lib/python3.10/site-packages/numba/tests/test_function_type.py +1408 -0
  35. lib/python3.10/site-packages/numba/tests/test_gdb_bindings.py +277 -0
  36. lib/python3.10/site-packages/numba/tests/test_gil.py +182 -0
  37. lib/python3.10/site-packages/numba/tests/test_hashing.py +529 -0
  38. lib/python3.10/site-packages/numba/tests/test_heapq.py +484 -0
  39. lib/python3.10/site-packages/numba/tests/test_inlining.py +279 -0
  40. lib/python3.10/site-packages/numba/tests/test_ir_utils.py +273 -0
  41. lib/python3.10/site-packages/numba/tests/test_jitmethod.py +70 -0
  42. lib/python3.10/site-packages/numba/tests/test_listimpl.py +527 -0
  43. lib/python3.10/site-packages/numba/tests/test_llvm_version_check.py +42 -0
  44. lib/python3.10/site-packages/numba/tests/test_mandelbrot.py +28 -0
  45. lib/python3.10/site-packages/numba/tests/test_mathlib.py +559 -0
  46. lib/python3.10/site-packages/numba/tests/test_misc_coverage_support.py +75 -0
  47. lib/python3.10/site-packages/numba/tests/test_nested_calls.py +153 -0
  48. lib/python3.10/site-packages/numba/tests/test_new_type_system.py +37 -0
  49. lib/python3.10/site-packages/numba/tests/test_npdatetime.py +1180 -0
  50. lib/python3.10/site-packages/numba/tests/test_nrt.py +857 -0
.gitattributes CHANGED
@@ -89,3 +89,4 @@ lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so
89
  lib/python3.10/site-packages/av/container/output.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
90
  lib/python3.10/site-packages/av/container/streams.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
91
  lib/python3.10/site-packages/av/data/stream.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
89
  lib/python3.10/site-packages/av/container/output.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
90
  lib/python3.10/site-packages/av/container/streams.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
91
  lib/python3.10/site-packages/av/data/stream.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
92
+ lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:971d0d600b4e6f4731d029f1f83d780b6ac9a80d69b1e4cec0f3ab6d30db253c
3
+ size 429249
lib/python3.10/site-packages/babel/locale-data/en_SS.dat ADDED
Binary file (908 Bytes). View file
 
lib/python3.10/site-packages/babel/locale-data/fo_DK.dat ADDED
Binary file (674 Bytes). View file
 
lib/python3.10/site-packages/babel/locale-data/fr_GF.dat ADDED
Binary file (719 Bytes). View file
 
lib/python3.10/site-packages/babel/locale-data/ie_EE.dat ADDED
Binary file (653 Bytes). View file
 
lib/python3.10/site-packages/babel/locale-data/kw.dat ADDED
Binary file (7.24 kB). View file
 
lib/python3.10/site-packages/babel/locale-data/mic_CA.dat ADDED
Binary file (636 Bytes). View file
 
lib/python3.10/site-packages/babel/locale-data/prg.dat ADDED
Binary file (17.3 kB). View file
 
lib/python3.10/site-packages/babel/locale-data/ps_AF.dat ADDED
Binary file (678 Bytes). View file
 
lib/python3.10/site-packages/babel/locale-data/sw_KE.dat ADDED
Binary file (47 kB). View file
 
lib/python3.10/site-packages/numba/tests/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ from os.path import dirname, join
3
+ import multiprocessing
4
+ import sys
5
+ import time
6
+ import unittest
7
+ import warnings
8
+
9
+ from unittest.suite import TestSuite
10
+ from numba.testing import load_testsuite
11
+
12
+
13
+ try:
14
+ import faulthandler
15
+ except ImportError:
16
+ faulthandler = None
17
+ else:
18
+ try:
19
+ # May fail in IPython Notebook with UnsupportedOperation
20
+ faulthandler.enable()
21
+ except Exception as e:
22
+ msg = "Failed to enable faulthandler due to:\n{err}"
23
+ warnings.warn(msg.format(err=e))
24
+
25
+ def load_tests(loader, tests, pattern):
26
+ suite = TestSuite()
27
+ suite.addTests(load_testsuite(loader, dirname(__file__)))
28
+ # Numba CUDA tests are located in a separate directory:
29
+ cuda_dir = join(dirname(dirname(__file__)), 'cuda/tests')
30
+ suite.addTests(loader.discover(cuda_dir))
31
+
32
+ return suite
33
+
lib/python3.10/site-packages/numba/tests/cache_usecases.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file will be copied to a temporary directory in order to
3
+ exercise caching compiled Numba functions.
4
+
5
+ See test_dispatcher.py.
6
+ """
7
+
8
+ import sys
9
+
10
+ import numpy as np
11
+
12
+ from numba import jit, prange
13
+ from numba.core import types
14
+
15
+ from numba.tests.ctypes_usecases import c_sin
16
+ from numba.tests.support import TestCase, captured_stderr
17
+
18
+
19
+ @jit(cache=True, nopython=True)
20
+ def simple_usecase(x):
21
+ return x
22
+
23
+ def simple_usecase_caller(x):
24
+ return simple_usecase(x)
25
+
26
+
27
+ @jit(cache=True, nopython=True)
28
+ def add_usecase(x, y):
29
+ return x + y + Z
30
+
31
+
32
+ @jit(cache=True, forceobj=True)
33
+ def add_objmode_usecase(x, y):
34
+ object()
35
+ return x + y + Z
36
+
37
+
38
+ @jit(nopython=True)
39
+ def add_nocache_usecase(x, y):
40
+ return x + y + Z
41
+
42
+
43
+ @jit(cache=True, nopython=True)
44
+ def inner(x, y):
45
+ return x + y + Z
46
+
47
+ @jit(cache=True, nopython=True)
48
+ def outer(x, y):
49
+ return inner(-y, x)
50
+
51
+ @jit(cache=False, nopython=True)
52
+ def outer_uncached(x, y):
53
+ return inner(-y, x)
54
+
55
+
56
+ @jit(cache=True, forceobj=True)
57
+ def looplifted(n):
58
+ object()
59
+ res = 0
60
+ for i in range(n):
61
+ res = res + i
62
+ return res
63
+
64
+
65
+ @jit(cache=True, nopython=True)
66
+ def use_c_sin(x):
67
+ return c_sin(x)
68
+
69
+ @jit(cache=True, nopython=True)
70
+ def use_c_sin_nest1(x):
71
+ return use_c_sin(x)
72
+
73
+ @jit(cache=True, nopython=True)
74
+ def use_c_sin_nest2(x):
75
+ return use_c_sin_nest1(x)
76
+
77
+
78
+ @jit(cache=True, nopython=True)
79
+ def ambiguous_function(x):
80
+ return x + 2
81
+
82
+ renamed_function1 = ambiguous_function
83
+
84
+ @jit(cache=True, nopython=True)
85
+ def ambiguous_function(x):
86
+ return x + 6
87
+
88
+ renamed_function2 = ambiguous_function
89
+
90
+
91
+ def make_closure(x):
92
+ @jit(cache=True, nopython=True)
93
+ def closure(y):
94
+ return x + y
95
+
96
+ return closure
97
+
98
+ closure1 = make_closure(3)
99
+ closure2 = make_closure(5)
100
+ closure3 = make_closure(7)
101
+ closure4 = make_closure(9)
102
+
103
+
104
+ biggie = np.arange(10**6)
105
+
106
+ @jit(cache=True, nopython=True)
107
+ def use_big_array():
108
+ return biggie
109
+
110
+
111
+ Z = 1
112
+
113
+ # Exercise returning a record instance. This used to hardcode the dtype
114
+ # pointer's value in the bitcode.
115
+
116
+ packed_record_type = np.dtype([('a', np.int8), ('b', np.float64)])
117
+ aligned_record_type = np.dtype([('a', np.int8), ('b', np.float64)], align=True)
118
+
119
+ packed_arr = np.empty(2, dtype=packed_record_type)
120
+ for i in range(packed_arr.size):
121
+ packed_arr[i]['a'] = i + 1
122
+ packed_arr[i]['b'] = i + 42.5
123
+
124
+ aligned_arr = np.array(packed_arr, dtype=aligned_record_type)
125
+
126
+ @jit(cache=True, nopython=True)
127
+ def record_return(ary, i):
128
+ return ary[i]
129
+
130
+
131
+ class _TestModule(TestCase):
132
+ """
133
+ Tests for functionality of this module's functions.
134
+ Note this does not define any "test_*" method, instead check_module()
135
+ should be called by hand.
136
+ """
137
+
138
+ def check_module(self, mod):
139
+ self.assertPreciseEqual(mod.add_usecase(2, 3), 6)
140
+ self.assertPreciseEqual(mod.add_objmode_usecase(2, 3), 6)
141
+ self.assertPreciseEqual(mod.outer_uncached(3, 2), 2)
142
+ self.assertPreciseEqual(mod.outer(3, 2), 2)
143
+
144
+ packed_rec = mod.record_return(mod.packed_arr, 1)
145
+ self.assertPreciseEqual(tuple(packed_rec), (2, 43.5))
146
+ aligned_rec = mod.record_return(mod.aligned_arr, 1)
147
+ self.assertPreciseEqual(tuple(aligned_rec), (2, 43.5))
148
+
149
+
150
+ @jit(cache=True)
151
+ def first_class_function_mul(x):
152
+ return x * x
153
+
154
+
155
+ @jit(cache=True)
156
+ def first_class_function_add(x):
157
+ return x + x
158
+
159
+
160
+ @jit(cache=True)
161
+ def first_class_function_usecase(f, x):
162
+ return f(x)
163
+
164
+
165
+ def self_test():
166
+ mod = sys.modules[__name__]
167
+ _TestModule().check_module(mod)
168
+
169
+
170
+ @jit(parallel=True, cache=True, nopython=True)
171
+ def parfor_usecase(ary):
172
+ return ary * ary + ary
lib/python3.10/site-packages/numba/tests/cffi_usecases.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import numpy as np
4
+
5
+ import numba.core.typing.cffi_utils as cffi_support
6
+ from numba.tests.support import import_dynamic, temp_directory
7
+ from numba.core.types import complex128
8
+
9
+
10
+ def load_inline_module():
11
+ """
12
+ Create an inline module, return the corresponding ffi and dll objects.
13
+ """
14
+ from cffi import FFI
15
+
16
+ # We can't rely on libc availability on Windows anymore, so we use our
17
+ # own compiled wrappers (see https://bugs.python.org/issue23606).
18
+
19
+ defs = """
20
+ double _numba_test_sin(double x);
21
+ double _numba_test_cos(double x);
22
+ double _numba_test_funcptr(double (*func)(double));
23
+ bool _numba_test_boolean(void);
24
+ """
25
+
26
+ ffi = FFI()
27
+ ffi.cdef(defs)
28
+ # Load the _helperlib namespace
29
+ from numba import _helperlib
30
+ return ffi, ffi.dlopen(_helperlib.__file__)
31
+
32
+
33
+ def load_ool_module():
34
+ """
35
+ Compile an out-of-line module, return the corresponding ffi and
36
+ module objects.
37
+ """
38
+ from cffi import FFI
39
+
40
+ numba_complex = """
41
+ typedef struct _numba_complex {
42
+ double real;
43
+ double imag;
44
+ } numba_complex;
45
+ """
46
+
47
+ bool_define = """
48
+ #ifdef _MSC_VER
49
+ #define false 0
50
+ #define true 1
51
+ #define bool int
52
+ #else
53
+ #include <stdbool.h>
54
+ #endif
55
+ """
56
+
57
+ defs = numba_complex + """
58
+ bool boolean(void);
59
+ double sin(double x);
60
+ double cos(double x);
61
+ int foo(int a, int b, int c);
62
+ void vsSin(int n, float* x, float* y);
63
+ void vdSin(int n, double* x, double* y);
64
+ void vector_real(numba_complex *c, double *real, int n);
65
+ void vector_imag(numba_complex *c, double *imag, int n);
66
+ """
67
+
68
+ source = numba_complex + bool_define + """
69
+ static bool boolean(void)
70
+ {
71
+ return true;
72
+ }
73
+
74
+ static int foo(int a, int b, int c)
75
+ {
76
+ return a + b * c;
77
+ }
78
+
79
+ void vsSin(int n, float* x, float* y) {
80
+ int i;
81
+ for (i=0; i<n; i++)
82
+ y[i] = sin(x[i]);
83
+ }
84
+
85
+ void vdSin(int n, double* x, double* y) {
86
+ int i;
87
+ for (i=0; i<n; i++)
88
+ y[i] = sin(x[i]);
89
+ }
90
+
91
+ static void vector_real(numba_complex *c, double *real, int n) {
92
+ int i;
93
+ for (i = 0; i < n; i++)
94
+ real[i] = c[i].real;
95
+ }
96
+
97
+ static void vector_imag(numba_complex *c, double *imag, int n) {
98
+ int i;
99
+ for (i = 0; i < n; i++)
100
+ imag[i] = c[i].imag;
101
+ }
102
+ """
103
+
104
+ ffi = FFI()
105
+ ffi.set_source('cffi_usecases_ool', source)
106
+ ffi.cdef(defs, override=True)
107
+ tmpdir = temp_directory('test_cffi')
108
+ ffi.compile(tmpdir=tmpdir)
109
+ sys.path.append(tmpdir)
110
+ try:
111
+ mod = import_dynamic('cffi_usecases_ool')
112
+ cffi_support.register_module(mod)
113
+ cffi_support.register_type(mod.ffi.typeof('struct _numba_complex'),
114
+ complex128)
115
+ return mod.ffi, mod
116
+ finally:
117
+ sys.path.remove(tmpdir)
118
+
119
+
120
+ def init():
121
+ """
122
+ Initialize module globals. This can invoke external utilities, hence not
123
+ being executed implicitly at module import.
124
+ """
125
+ global ffi, cffi_sin, cffi_cos, cffi_bool
126
+
127
+ if ffi is None:
128
+ ffi, dll = load_inline_module()
129
+ cffi_sin = dll._numba_test_sin
130
+ cffi_cos = dll._numba_test_cos
131
+ cffi_bool = dll._numba_test_boolean
132
+ del dll
133
+
134
+ def init_ool():
135
+ """
136
+ Same as init() for OOL mode.
137
+ """
138
+ global ffi_ool, cffi_sin_ool, cffi_cos_ool, cffi_foo, cffi_bool_ool
139
+ global vsSin, vdSin, vector_real, vector_imag
140
+
141
+ if ffi_ool is None:
142
+ ffi_ool, mod = load_ool_module()
143
+ cffi_sin_ool = mod.lib.sin
144
+ cffi_cos_ool = mod.lib.cos
145
+ cffi_foo = mod.lib.foo
146
+ cffi_bool_ool = mod.lib.boolean
147
+ vsSin = mod.lib.vsSin
148
+ vdSin = mod.lib.vdSin
149
+ vector_real = mod.lib.vector_real
150
+ vector_imag = mod.lib.vector_imag
151
+ del mod
152
+
153
+ ffi = ffi_ool = None
154
+
155
+
156
+ def use_cffi_sin(x):
157
+ return cffi_sin(x) * 2
158
+
159
+ def use_two_funcs(x):
160
+ return cffi_sin(x) - cffi_cos(x)
161
+
162
+ def use_cffi_sin_ool(x):
163
+ return cffi_sin_ool(x) * 2
164
+
165
+ def use_cffi_boolean_true():
166
+ return cffi_bool_ool()
167
+
168
+ def use_two_funcs_ool(x):
169
+ return cffi_sin_ool(x) - cffi_cos_ool(x)
170
+
171
+ def use_func_pointer(fa, fb, x):
172
+ if x > 0:
173
+ return fa(x)
174
+ else:
175
+ return fb(x)
176
+
177
+ def use_user_defined_symbols():
178
+ return cffi_foo(1, 2, 3)
179
+
180
+ # The from_buffer method is member of cffi.FFI, and also of CompiledFFI objects
181
+ # (cffi_usecases_ool.ffi is a CompiledFFI object) so we use both in these
182
+ # functions.
183
+
184
+ def vector_sin_float32(x, y):
185
+ vsSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y))
186
+
187
+ def vector_sin_float64(x, y):
188
+ vdSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y))
189
+
190
+
191
+ # For testing pointer to structs from buffers
192
+
193
+ def vector_extract_real(x, y):
194
+ vector_real(ffi.from_buffer(x), ffi.from_buffer(y), len(x))
195
+
196
+ def vector_extract_imag(x, y):
197
+ vector_imag(ffi.from_buffer(x), ffi.from_buffer(y), len(x))
lib/python3.10/site-packages/numba/tests/complex_usecases.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cmath
2
+
3
+
4
+ def div_usecase(x, y):
5
+ return x / y
6
+
7
+
8
+ def real_usecase(x):
9
+ return x.real
10
+
11
+ def imag_usecase(x):
12
+ return x.imag
13
+
14
+ def conjugate_usecase(x):
15
+ return x.conjugate()
16
+
17
+
18
+ def acos_usecase(x):
19
+ return cmath.acos(x)
20
+
21
+ def cos_usecase(x):
22
+ return cmath.cos(x)
23
+
24
+ def asin_usecase(x):
25
+ return cmath.asin(x)
26
+
27
+ def sin_usecase(x):
28
+ return cmath.sin(x)
29
+
30
+ def atan_usecase(x):
31
+ return cmath.atan(x)
32
+
33
+ def tan_usecase(x):
34
+ return cmath.tan(x)
35
+
36
+ def acosh_usecase(x):
37
+ return cmath.acosh(x)
38
+
39
+ def cosh_usecase(x):
40
+ return cmath.cosh(x)
41
+
42
+ def asinh_usecase(x):
43
+ return cmath.asinh(x)
44
+
45
+ def sinh_usecase(x):
46
+ return cmath.sinh(x)
47
+
48
+ def atanh_usecase(x):
49
+ return cmath.atanh(x)
50
+
51
+ def tanh_usecase(x):
52
+ return cmath.tanh(x)
53
+
54
+ def exp_usecase(x):
55
+ return cmath.exp(x)
56
+
57
+ def isfinite_usecase(x):
58
+ return cmath.isfinite(x)
59
+
60
+ def isinf_usecase(x):
61
+ return cmath.isinf(x)
62
+
63
+ def isnan_usecase(x):
64
+ return cmath.isnan(x)
65
+
66
+ def log_usecase(x):
67
+ return cmath.log(x)
68
+
69
+ def log_base_usecase(x, base):
70
+ return cmath.log(x, base)
71
+
72
+ def log10_usecase(x):
73
+ return cmath.log10(x)
74
+
75
+ def phase_usecase(x):
76
+ return cmath.phase(x)
77
+
78
+ def polar_usecase(x):
79
+ return cmath.polar(x)
80
+
81
+ _two = 2.0
82
+
83
+ def polar_as_complex_usecase(x):
84
+ # HACK: clear errno by invoking float.__pow__
85
+ # (workaround for http://bugs.python.org/issue24489)
86
+ _two ** _two
87
+ return complex(*cmath.polar(x))
88
+
89
+ def rect_usecase(r, phi):
90
+ return cmath.rect(r, phi)
91
+
92
+ def sqrt_usecase(x):
93
+ return cmath.sqrt(x)
lib/python3.10/site-packages/numba/tests/ctypes_usecases.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import *
2
+ import sys
3
+
4
+ import numpy as np
5
+
6
+
7
+ is_windows = sys.platform.startswith('win32')
8
+
9
+ # We can't rely on libc availability on Windows anymore, so we use our
10
+ # own compiled wrappers (see https://bugs.python.org/issue23606).
11
+
12
+ from numba import _helperlib
13
+ libnumba = CDLL(_helperlib.__file__)
14
+ del _helperlib
15
+
16
+ # A typed C function (cdecl under Windows)
17
+
18
+ c_sin = libnumba._numba_test_sin
19
+ c_sin.argtypes = [c_double]
20
+ c_sin.restype = c_double
21
+
22
+ def use_c_sin(x):
23
+ return c_sin(x)
24
+
25
+ c_cos = libnumba._numba_test_cos
26
+ c_cos.argtypes = [c_double]
27
+ c_cos.restype = c_double
28
+
29
+ def use_two_funcs(x):
30
+ return c_sin(x) - c_cos(x)
31
+
32
+ # Typed C functions accepting an array pointer
33
+ # (either as a "void *" or as a typed pointer)
34
+
35
+ c_vsquare = libnumba._numba_test_vsquare
36
+ c_vsquare.argtypes = [c_int, c_void_p, c_void_p]
37
+
38
+ c_vcube = libnumba._numba_test_vsquare
39
+ c_vcube.argtypes = [c_int, POINTER(c_double), POINTER(c_double)]
40
+
41
+ def use_c_vsquare(x):
42
+ out = np.empty_like(x)
43
+ c_vsquare(x.size, x.ctypes, out.ctypes)
44
+ return out
45
+
46
+ def use_c_vcube(x):
47
+ out = np.empty_like(x)
48
+ c_vcube(x.size, x.ctypes, out.ctypes)
49
+ return out
50
+
51
+ # An untyped C function
52
+
53
+ c_untyped = libnumba._numba_test_exp
54
+
55
+ def use_c_untyped(x):
56
+ return c_untyped(x)
57
+
58
+ # A C function wrapped in a CFUNCTYPE
59
+
60
+ ctype_wrapping = CFUNCTYPE(c_double, c_double)(use_c_sin)
61
+
62
+ def use_ctype_wrapping(x):
63
+ return ctype_wrapping(x)
64
+
65
+ # A Python API function
66
+
67
+ savethread = pythonapi.PyEval_SaveThread
68
+ savethread.argtypes = []
69
+ savethread.restype = c_void_p
70
+
71
+ restorethread = pythonapi.PyEval_RestoreThread
72
+ restorethread.argtypes = [c_void_p]
73
+ restorethread.restype = None
74
+
75
+ if is_windows:
76
+ # A function with the stdcall calling convention
77
+ c_sleep = windll.kernel32.Sleep
78
+ c_sleep.argtypes = [c_uint]
79
+ c_sleep.restype = None
80
+
81
+ def use_c_sleep(x):
82
+ c_sleep(x)
83
+
84
+
85
+ def use_c_pointer(x):
86
+ """
87
+ Running in Python will cause a segfault.
88
+ """
89
+ threadstate = savethread()
90
+ x += 1
91
+ restorethread(threadstate)
92
+ return x
93
+
94
+
95
+ def use_func_pointer(fa, fb, x):
96
+ if x > 0:
97
+ return fa(x)
98
+ else:
99
+ return fb(x)
100
+
101
+
102
+ mydct = {'what': 1232121}
103
+
104
+ def call_me_maybe(arr):
105
+ return mydct[arr[0].decode('ascii')]
106
+
107
+ # Create a callback into the python interpreter
108
+ py_call_back = CFUNCTYPE(c_int, py_object)(call_me_maybe)
109
+
110
+
111
+ def take_array_ptr(ptr):
112
+ return ptr
113
+
114
+ c_take_array_ptr = CFUNCTYPE(c_void_p, c_void_p)(take_array_ptr)
lib/python3.10/site-packages/numba/tests/doctest_usecase.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test that all docstrings are the same:
3
+
4
+ >>> len({f.__doc__ for f in (a, b, c, d)})
5
+ 1
6
+ """
7
+ from numba import guvectorize, int64, njit, vectorize
8
+
9
+
10
+ def a():
11
+ """>>> x = 1"""
12
+ return 1
13
+
14
+
15
+ @njit
16
+ def b():
17
+ """>>> x = 1"""
18
+ return 1
19
+
20
+
21
+ @guvectorize([(int64[:], int64, int64[:])], "(n),()->(n)")
22
+ def c(x, y, res):
23
+ """>>> x = 1"""
24
+ for i in range(x.shape[0]):
25
+ res[i] = x[i] + y
26
+
27
+
28
+ @vectorize([int64(int64, int64)])
29
+ def d(x, y):
30
+ """>>> x = 1"""
31
+ return x + y
lib/python3.10/site-packages/numba/tests/enum_usecases.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum, IntEnum
2
+
3
+
4
+ class Color(Enum):
5
+ red = 1
6
+ green = 2
7
+ blue = 3
8
+
9
+
10
+ class Shake(Enum):
11
+ vanilla = 7
12
+ chocolate = 4
13
+ cookies = 9
14
+ # Same as Color.blue
15
+ mint = 3
16
+
17
+
18
+ class Planet(Enum):
19
+ MERCURY = (3.303e+23, 2.4397e6)
20
+ VENUS = (4.869e+24, 6.0518e6)
21
+ EARTH = (5.976e+24, 6.37814e6)
22
+ MARS = (6.421e+23, 3.3972e6)
23
+ JUPITER = (1.9e+27, 7.1492e7)
24
+ SATURN = (5.688e+26, 6.0268e7)
25
+ URANUS = (8.686e+25, 2.5559e7)
26
+ NEPTUNE = (1.024e+26, 2.4746e7)
27
+
28
+
29
+ class HeterogeneousEnum(Enum):
30
+ red = 1.0
31
+ green = 2.0
32
+ blue = 3j
33
+
34
+
35
+ class Shape(IntEnum):
36
+ # Same as Color.green
37
+ circle = 2
38
+ # Same as RequestError.internal_error
39
+ square = 500
40
+
41
+
42
+ class RequestError(IntEnum):
43
+ dummy = 2
44
+ not_found = 404
45
+ internal_error = 500
46
+
47
+ class IntEnumWithNegatives(IntEnum):
48
+ # Used for testing of hash, need to make sure -1 -> -2 to comply with CPy
49
+ one = 1
50
+ two = 2
51
+ too = 2
52
+ three = 3
53
+ negone = -1
54
+ negtwo = -2
55
+ negthree = -3
lib/python3.10/site-packages/numba/tests/parfor_iss9490_usecase.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is a testcase for https://github.com/numba/numba/issues/9490.
3
+ The bug is very sensitive to the control-flow and variable uses.
4
+ It is impossible to shrink the reproducer in any meaningful way.
5
+
6
+ The test is also sensitive to PYTHONHASHSEED.
7
+ PYTHONHASHSEED=1 will trigger the bug.
8
+
9
+ Example of traceback:
10
+
11
+ File "/numba/parfors/parfor.py", line 2070, in _arrayexpr_to_parfor
12
+ index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars,
13
+ scope, loc)
14
+ File "/numba/parfors/parfor.py", line 1981, in _mk_parfor_loops
15
+ for size_var in size_vars:
16
+ TypeError: Failed in nopython mode pipeline (step: convert to parfors)
17
+ 'NoneType' object is not iterable
18
+ """
19
+
20
+ import numba
21
+ import numpy as np
22
+
23
+
24
+ @numba.jit(nopython=True, parallel=True)
25
+ def stable_fit(X, y, threshold=3):
26
+ min_obs = int(X.shape[1] * 1.5)
27
+ beta = np.zeros((X.shape[1], y.shape[1]), dtype=np.float64)
28
+ residuals = np.full_like(y, np.nan)
29
+ stable = np.empty((y.shape[1]))
30
+ for idx in numba.prange(y.shape[1]):
31
+ y_sub = y[:, idx]
32
+ isna = np.isnan(y_sub)
33
+ X_sub = X[~isna]
34
+ y_sub = y_sub[~isna]
35
+ is_stable = False
36
+
37
+ # Run until minimum observations
38
+ # or until stability is reached
39
+ for jdx in range(len(y_sub), min_obs - 1, -2):
40
+ # Timeseries gets reduced by two elements
41
+ # each iteration
42
+ y_ = y_sub[-jdx:]
43
+ X_ = X_sub[-jdx:]
44
+ beta_sub = np.linalg.solve(np.dot(X_.T, X_), np.dot(X_.T, y_))
45
+ resid_sub = np.dot(X_, beta_sub) - y_
46
+ # Check for stability
47
+ rmse = np.sqrt(np.mean(resid_sub ** 2))
48
+ first = np.fabs(resid_sub[0]) / rmse < threshold
49
+ last = np.fabs(resid_sub[-1]) / rmse < threshold
50
+ slope = np.fabs(beta_sub[1]) / rmse < threshold
51
+ # Break if stability is reached
52
+ is_stable = slope & first & last
53
+ if is_stable:
54
+ break
55
+
56
+ beta[:, idx] = beta_sub
57
+ residuals[-jdx:, idx] = resid_sub
58
+ stable[idx] = is_stable
59
+ return beta, residuals, stable.astype(np.bool_)
60
+
61
+
62
+ def check():
63
+ np.random.seed(0)
64
+ X_shape = (10, 4)
65
+ y_shape = (10, 5)
66
+ X = np.random.random(X_shape)
67
+ y = np.random.random(y_shape)
68
+
69
+ got_beta, got_residuals, got_stable = stable_fit(X, y)
70
+ exp_beta, exp_residuals, exp_stable = stable_fit.py_func(X, y)
71
+
72
+ np.testing.assert_allclose(got_beta, exp_beta)
73
+ np.testing.assert_allclose(got_residuals, exp_residuals)
74
+ np.testing.assert_allclose(got_stable, exp_stable)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ check()
lib/python3.10/site-packages/numba/tests/test_analysis.py ADDED
@@ -0,0 +1,1007 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tests numba.analysis functions
2
+ import collections
3
+ import types as pytypes
4
+
5
+ import numpy as np
6
+ from numba.core.compiler import run_frontend, Flags, StateDict
7
+ from numba import jit, njit, literal_unroll
8
+ from numba.core import types, errors, ir, rewrites, ir_utils, cpu
9
+ from numba.core import postproc
10
+ from numba.core.inline_closurecall import InlineClosureCallPass
11
+ from numba.tests.support import (TestCase, MemoryLeakMixin, SerialMixin,
12
+ IRPreservingTestPipeline)
13
+ from numba.core.analysis import dead_branch_prune, rewrite_semantic_constants
14
+ from numba.core.untyped_passes import (ReconstructSSA, TranslateByteCode,
15
+ IRProcessing, DeadBranchPrune,
16
+ PreserveIR)
17
+ from numba.core.compiler import DefaultPassBuilder, CompilerBase, PassManager
18
+
19
+
20
+ _GLOBAL = 123
21
+
22
+ enable_pyobj_flags = Flags()
23
+ enable_pyobj_flags.enable_pyobject = True
24
+
25
+
26
+ def compile_to_ir(func):
27
+ func_ir = run_frontend(func)
28
+ state = StateDict()
29
+ state.func_ir = func_ir
30
+ state.typemap = None
31
+ state.calltypes = None
32
+ # Transform to SSA
33
+ ReconstructSSA().run_pass(state)
34
+ # call this to get print etc rewrites
35
+ rewrites.rewrite_registry.apply('before-inference', state)
36
+ return func_ir
37
+
38
+
39
+ class TestBranchPruneBase(MemoryLeakMixin, TestCase):
40
+ """
41
+ Tests branch pruning
42
+ """
43
+ _DEBUG = False
44
+
45
+ # find *all* branches
46
+ def find_branches(self, the_ir):
47
+ branches = []
48
+ for blk in the_ir.blocks.values():
49
+ tmp = [_ for _ in blk.find_insts(cls=ir.Branch)]
50
+ branches.extend(tmp)
51
+ return branches
52
+
53
+ def assert_prune(self, func, args_tys, prune, *args, **kwargs):
54
+ # This checks that the expected pruned branches have indeed been pruned.
55
+ # func is a python function to assess
56
+ # args_tys is the numba types arguments tuple
57
+ # prune arg is a list, one entry per branch. The value in the entry is
58
+ # encoded as follows:
59
+ # True: using constant inference only, the True branch will be pruned
60
+ # False: using constant inference only, the False branch will be pruned
61
+ # None: under no circumstances should this branch be pruned
62
+ # *args: the argument instances to pass to the function to check
63
+ # execution is still valid post transform
64
+ # **kwargs:
65
+ # - flags: args to pass to `jit` default is `nopython=True`,
66
+ # e.g. permits use of e.g. object mode.
67
+
68
+ func_ir = compile_to_ir(func)
69
+ before = func_ir.copy()
70
+ if self._DEBUG:
71
+ print("=" * 80)
72
+ print("before inline")
73
+ func_ir.dump()
74
+
75
+ # run closure inlining to ensure that nonlocals in closures are visible
76
+ inline_pass = InlineClosureCallPass(func_ir,
77
+ cpu.ParallelOptions(False),)
78
+ inline_pass.run()
79
+
80
+ # Remove all Dels, and re-run postproc
81
+ post_proc = postproc.PostProcessor(func_ir)
82
+ post_proc.run()
83
+
84
+ rewrite_semantic_constants(func_ir, args_tys)
85
+ if self._DEBUG:
86
+ print("=" * 80)
87
+ print("before prune")
88
+ func_ir.dump()
89
+
90
+ dead_branch_prune(func_ir, args_tys)
91
+
92
+ after = func_ir
93
+ if self._DEBUG:
94
+ print("after prune")
95
+ func_ir.dump()
96
+
97
+ before_branches = self.find_branches(before)
98
+ self.assertEqual(len(before_branches), len(prune))
99
+
100
+ # what is expected to be pruned
101
+ expect_removed = []
102
+ for idx, prune in enumerate(prune):
103
+ branch = before_branches[idx]
104
+ if prune is True:
105
+ expect_removed.append(branch.truebr)
106
+ elif prune is False:
107
+ expect_removed.append(branch.falsebr)
108
+ elif prune is None:
109
+ pass # nothing should be removed!
110
+ elif prune == 'both':
111
+ expect_removed.append(branch.falsebr)
112
+ expect_removed.append(branch.truebr)
113
+ else:
114
+ assert 0, "unreachable"
115
+
116
+ # compare labels
117
+ original_labels = set([_ for _ in before.blocks.keys()])
118
+ new_labels = set([_ for _ in after.blocks.keys()])
119
+ # assert that the new labels are precisely the original less the
120
+ # expected pruned labels
121
+ try:
122
+ self.assertEqual(new_labels, original_labels - set(expect_removed))
123
+ except AssertionError as e:
124
+ print("new_labels", sorted(new_labels))
125
+ print("original_labels", sorted(original_labels))
126
+ print("expect_removed", sorted(expect_removed))
127
+ raise e
128
+
129
+ supplied_flags = kwargs.pop('flags', {'nopython': True})
130
+ # NOTE: original testing used `compile_isolated` hence use of `cres`.
131
+ cres = jit(args_tys, **supplied_flags)(func).overloads[args_tys]
132
+ if args is None:
133
+ res = cres.entry_point()
134
+ expected = func()
135
+ else:
136
+ res = cres.entry_point(*args)
137
+ expected = func(*args)
138
+ self.assertEqual(res, expected)
139
+
140
+
141
+ class TestBranchPrune(TestBranchPruneBase, SerialMixin):
142
+
143
+ def test_single_if(self):
144
+
145
+ def impl(x):
146
+ if 1 == 0:
147
+ return 3.14159
148
+
149
+ self.assert_prune(impl, (types.NoneType('none'),), [True], None)
150
+
151
+ def impl(x):
152
+ if 1 == 1:
153
+ return 3.14159
154
+
155
+ self.assert_prune(impl, (types.NoneType('none'),), [False], None)
156
+
157
+ def impl(x):
158
+ if x is None:
159
+ return 3.14159
160
+
161
+ self.assert_prune(impl, (types.NoneType('none'),), [False], None)
162
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10)
163
+
164
+ def impl(x):
165
+ if x == 10:
166
+ return 3.14159
167
+
168
+ self.assert_prune(impl, (types.NoneType('none'),), [True], None)
169
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10)
170
+
171
+ def impl(x):
172
+ if x == 10:
173
+ z = 3.14159 # noqa: F841 # no effect
174
+
175
+ self.assert_prune(impl, (types.NoneType('none'),), [True], None)
176
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10)
177
+
178
+ def impl(x):
179
+ z = None
180
+ y = z
181
+ if x == y:
182
+ return 100
183
+
184
+ self.assert_prune(impl, (types.NoneType('none'),), [False], None)
185
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10)
186
+
187
+ def test_single_if_else(self):
188
+
189
+ def impl(x):
190
+ if x is None:
191
+ return 3.14159
192
+ else:
193
+ return 1.61803
194
+
195
+ self.assert_prune(impl, (types.NoneType('none'),), [False], None)
196
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10)
197
+
198
+ def test_single_if_const_val(self):
199
+
200
+ def impl(x):
201
+ if x == 100:
202
+ return 3.14159
203
+
204
+ self.assert_prune(impl, (types.NoneType('none'),), [True], None)
205
+ self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100)
206
+
207
+ def impl(x):
208
+ # switch the condition order
209
+ if 100 == x:
210
+ return 3.14159
211
+
212
+ self.assert_prune(impl, (types.NoneType('none'),), [True], None)
213
+ self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100)
214
+
215
+ def test_single_if_else_two_const_val(self):
216
+
217
+ def impl(x, y):
218
+ if x == y:
219
+ return 3.14159
220
+ else:
221
+ return 1.61803
222
+
223
+ self.assert_prune(impl, (types.IntegerLiteral(100),) * 2, [None], 100,
224
+ 100)
225
+ self.assert_prune(impl, (types.NoneType('none'),) * 2, [False], None,
226
+ None)
227
+ self.assert_prune(impl, (types.IntegerLiteral(100),
228
+ types.NoneType('none'),), [True], 100, None)
229
+ self.assert_prune(impl, (types.IntegerLiteral(100),
230
+ types.IntegerLiteral(1000)), [None], 100, 1000)
231
+
232
+ def test_single_if_else_w_following_undetermined(self):
233
+
234
+ def impl(x):
235
+ x_is_none_work = False
236
+ if x is None:
237
+ x_is_none_work = True
238
+ else:
239
+ dead = 7 # noqa: F841 # no effect
240
+
241
+ if x_is_none_work:
242
+ y = 10
243
+ else:
244
+ y = -3
245
+ return y
246
+
247
+ self.assert_prune(impl, (types.NoneType('none'),), [False, None], None)
248
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10)
249
+
250
+ def impl(x):
251
+ x_is_none_work = False
252
+ if x is None:
253
+ x_is_none_work = True
254
+ else:
255
+ pass
256
+
257
+ if x_is_none_work:
258
+ y = 10
259
+ else:
260
+ y = -3
261
+ return y
262
+
263
+ # Python 3.10 creates a block with a NOP in it for the `pass` which
264
+ # means it gets pruned.
265
+ self.assert_prune(impl, (types.NoneType('none'),), [False, None],
266
+ None)
267
+
268
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10)
269
+
270
+ def test_double_if_else_rt_const(self):
271
+
272
+ def impl(x):
273
+ one_hundred = 100
274
+ x_is_none_work = 4
275
+ if x is None:
276
+ x_is_none_work = 100
277
+ else:
278
+ dead = 7 # noqa: F841 # no effect
279
+
280
+ if x_is_none_work == one_hundred:
281
+ y = 10
282
+ else:
283
+ y = -3
284
+
285
+ return y, x_is_none_work
286
+
287
+ self.assert_prune(impl, (types.NoneType('none'),), [False, None], None)
288
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10)
289
+
290
+ def test_double_if_else_non_literal_const(self):
291
+
292
+ def impl(x):
293
+ one_hundred = 100
294
+ if x == one_hundred:
295
+ y = 3.14159
296
+ else:
297
+ y = 1.61803
298
+ return y
299
+
300
+ # no prune as compilation specialization on literal value not permitted
301
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10)
302
+ self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100)
303
+
304
+ def test_single_two_branches_same_cond(self):
305
+
306
+ def impl(x):
307
+ if x is None:
308
+ y = 10
309
+ else:
310
+ y = 40
311
+
312
+ if x is not None:
313
+ z = 100
314
+ else:
315
+ z = 400
316
+
317
+ return z, y
318
+
319
+ self.assert_prune(impl, (types.NoneType('none'),), [False, True], None)
320
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True, False], 10)
321
+
322
+ def test_cond_is_kwarg_none(self):
323
+
324
+ def impl(x=None):
325
+ if x is None:
326
+ y = 10
327
+ else:
328
+ y = 40
329
+
330
+ if x is not None:
331
+ z = 100
332
+ else:
333
+ z = 400
334
+
335
+ return z, y
336
+
337
+ self.assert_prune(impl, (types.Omitted(None),),
338
+ [False, True], None)
339
+ self.assert_prune(impl, (types.NoneType('none'),), [False, True], None)
340
+ self.assert_prune(impl, (types.IntegerLiteral(10),), [True, False], 10)
341
+
342
+ def test_cond_is_kwarg_value(self):
343
+
344
+ def impl(x=1000):
345
+ if x == 1000:
346
+ y = 10
347
+ else:
348
+ y = 40
349
+
350
+ if x != 1000:
351
+ z = 100
352
+ else:
353
+ z = 400
354
+
355
+ return z, y
356
+
357
+ self.assert_prune(impl, (types.Omitted(1000),), [None, None], 1000)
358
+ self.assert_prune(impl, (types.IntegerLiteral(1000),), [None, None],
359
+ 1000)
360
+ self.assert_prune(impl, (types.IntegerLiteral(0),), [None, None], 0)
361
+ self.assert_prune(impl, (types.NoneType('none'),), [True, False], None)
362
+
363
+ def test_cond_rewrite_is_correct(self):
364
+ # this checks that when a condition is replaced, it is replace by a
365
+ # true/false bit that correctly represents the evaluated condition
366
+ def fn(x):
367
+ if x is None:
368
+ return 10
369
+ return 12
370
+
371
+ def check(func, arg_tys, bit_val):
372
+ func_ir = compile_to_ir(func)
373
+
374
+ # check there is 1 branch
375
+ before_branches = self.find_branches(func_ir)
376
+ self.assertEqual(len(before_branches), 1)
377
+
378
+ # check the condition in the branch is a binop
379
+ pred_var = before_branches[0].cond
380
+ pred_defn = ir_utils.get_definition(func_ir, pred_var)
381
+ self.assertEqual(pred_defn.op, 'call')
382
+ condition_var = pred_defn.args[0]
383
+ condition_op = ir_utils.get_definition(func_ir, condition_var)
384
+ self.assertEqual(condition_op.op, 'binop')
385
+
386
+ # do the prune, this should kill the dead branch and rewrite the
387
+ #'condition to a true/false const bit
388
+ if self._DEBUG:
389
+ print("=" * 80)
390
+ print("before prune")
391
+ func_ir.dump()
392
+ dead_branch_prune(func_ir, arg_tys)
393
+ if self._DEBUG:
394
+ print("=" * 80)
395
+ print("after prune")
396
+ func_ir.dump()
397
+
398
+ # after mutation, the condition should be a const value `bit_val`
399
+ new_condition_defn = ir_utils.get_definition(func_ir, condition_var)
400
+ self.assertTrue(isinstance(new_condition_defn, ir.Const))
401
+ self.assertEqual(new_condition_defn.value, bit_val)
402
+
403
+ check(fn, (types.NoneType('none'),), 1)
404
+ check(fn, (types.IntegerLiteral(10),), 0)
405
+
406
+ def test_global_bake_in(self):
407
+
408
+ def impl(x):
409
+ if _GLOBAL == 123:
410
+ return x
411
+ else:
412
+ return x + 10
413
+
414
+ self.assert_prune(impl, (types.IntegerLiteral(1),), [False], 1)
415
+
416
+ global _GLOBAL
417
+ tmp = _GLOBAL
418
+
419
+ try:
420
+ _GLOBAL = 5
421
+
422
+ def impl(x):
423
+ if _GLOBAL == 123:
424
+ return x
425
+ else:
426
+ return x + 10
427
+
428
+ self.assert_prune(impl, (types.IntegerLiteral(1),), [True], 1)
429
+ finally:
430
+ _GLOBAL = tmp
431
+
432
+ def test_freevar_bake_in(self):
433
+
434
+ _FREEVAR = 123
435
+
436
+ def impl(x):
437
+ if _FREEVAR == 123:
438
+ return x
439
+ else:
440
+ return x + 10
441
+
442
+ self.assert_prune(impl, (types.IntegerLiteral(1),), [False], 1)
443
+
444
+ _FREEVAR = 12
445
+
446
+ def impl(x):
447
+ if _FREEVAR == 123:
448
+ return x
449
+ else:
450
+ return x + 10
451
+
452
+ self.assert_prune(impl, (types.IntegerLiteral(1),), [True], 1)
453
+
454
+ def test_redefined_variables_are_not_considered_in_prune(self):
455
+ # see issue #4163, checks that if a variable that is an argument is
456
+ # redefined in the user code it is not considered const
457
+
458
+ def impl(array, a=None):
459
+ if a is None:
460
+ a = 0
461
+ if a < 0:
462
+ return 10
463
+ return 30
464
+
465
+ self.assert_prune(impl,
466
+ (types.Array(types.float64, 2, 'C'),
467
+ types.NoneType('none'),),
468
+ [None, None],
469
+ np.zeros((2, 3)), None)
470
+
471
+ def test_comparison_operators(self):
472
+ # see issue #4163, checks that a variable that is an argument and has
473
+ # value None survives TypeError from invalid comparison which should be
474
+ # dead
475
+
476
+ def impl(array, a=None):
477
+ x = 0
478
+ if a is None:
479
+ return 10 # dynamic exec would return here
480
+ # static analysis requires that this is executed with a=None,
481
+ # hence TypeError
482
+ if a < 0:
483
+ return 20
484
+ return x
485
+
486
+ self.assert_prune(impl,
487
+ (types.Array(types.float64, 2, 'C'),
488
+ types.NoneType('none'),),
489
+ [False, 'both'],
490
+ np.zeros((2, 3)), None)
491
+
492
+ self.assert_prune(impl,
493
+ (types.Array(types.float64, 2, 'C'),
494
+ types.float64,),
495
+ [None, None],
496
+ np.zeros((2, 3)), 12.)
497
+
498
+ def test_redefinition_analysis_same_block(self):
499
+ # checks that a redefinition in a block with prunable potential doesn't
500
+ # break
501
+
502
+ def impl(array, x, a=None):
503
+ b = 2
504
+ if x < 4:
505
+ b = 12
506
+ if a is None: # known true
507
+ a = 7 # live
508
+ else:
509
+ b = 15 # dead
510
+ if a < 0: # valid as a result of the redefinition of 'a'
511
+ return 10
512
+ return 30 + b + a
513
+
514
+ self.assert_prune(impl,
515
+ (types.Array(types.float64, 2, 'C'),
516
+ types.float64, types.NoneType('none'),),
517
+ [None, False, None],
518
+ np.zeros((2, 3)), 1., None)
519
+
520
+ def test_redefinition_analysis_different_block_can_exec(self):
521
+ # checks that a redefinition in a block that may be executed prevents
522
+ # pruning
523
+
524
+ def impl(array, x, a=None):
525
+ b = 0
526
+ if x > 5:
527
+ a = 11 # a redefined, cannot tell statically if this will exec
528
+ if x < 4:
529
+ b = 12
530
+ if a is None: # cannot prune, cannot determine if re-defn occurred
531
+ b += 5
532
+ else:
533
+ b += 7
534
+ if a < 0:
535
+ return 10
536
+ return 30 + b
537
+
538
+ self.assert_prune(impl,
539
+ (types.Array(types.float64, 2, 'C'),
540
+ types.float64, types.NoneType('none'),),
541
+ [None, None, None, None],
542
+ np.zeros((2, 3)), 1., None)
543
+
544
+ def test_redefinition_analysis_different_block_cannot_exec(self):
545
+ # checks that a redefinition in a block guarded by something that
546
+ # has prune potential
547
+
548
+ def impl(array, x=None, a=None):
549
+ b = 0
550
+ if x is not None:
551
+ a = 11
552
+ if a is None:
553
+ b += 5
554
+ else:
555
+ b += 7
556
+ return 30 + b
557
+
558
+ self.assert_prune(impl,
559
+ (types.Array(types.float64, 2, 'C'),
560
+ types.NoneType('none'), types.NoneType('none')),
561
+ [True, None],
562
+ np.zeros((2, 3)), None, None)
563
+
564
+ self.assert_prune(impl,
565
+ (types.Array(types.float64, 2, 'C'),
566
+ types.NoneType('none'), types.float64),
567
+ [True, None],
568
+ np.zeros((2, 3)), None, 1.2)
569
+
570
+ self.assert_prune(impl,
571
+ (types.Array(types.float64, 2, 'C'),
572
+ types.float64, types.NoneType('none')),
573
+ [None, None],
574
+ np.zeros((2, 3)), 1.2, None)
575
+
576
+ def test_closure_and_nonlocal_can_prune(self):
577
+ # Closures must be inlined ahead of branch pruning in case nonlocal
578
+ # is used. See issue #6585.
579
+ def impl():
580
+ x = 1000
581
+
582
+ def closure():
583
+ nonlocal x
584
+ x = 0
585
+
586
+ closure()
587
+
588
+ if x == 0:
589
+ return True
590
+ else:
591
+ return False
592
+
593
+ self.assert_prune(impl, (), [False,],)
594
+
595
+ def test_closure_and_nonlocal_cannot_prune(self):
596
+ # Closures must be inlined ahead of branch pruning in case nonlocal
597
+ # is used. See issue #6585.
598
+ def impl(n):
599
+ x = 1000
600
+
601
+ def closure(t):
602
+ nonlocal x
603
+ x = t
604
+
605
+ closure(n)
606
+
607
+ if x == 0:
608
+ return True
609
+ else:
610
+ return False
611
+
612
+ self.assert_prune(impl, (types.int64,), [None,], 1)
613
+
614
+
615
+ class TestBranchPrunePredicates(TestBranchPruneBase, SerialMixin):
616
+ # Really important thing to remember... the branch on predicates end up as
617
+ # POP_JUMP_IF_<bool> and the targets are backwards compared to normal, i.e.
618
+ # the true condition is far jump and the false the near i.e. `if x` would
619
+ # end up in Numba IR as e.g. `branch x 10, 6`.
620
+
621
+ _TRUTHY = (1, "String", True, 7.4, 3j)
622
+ _FALSEY = (0, "", False, 0.0, 0j, None)
623
+
624
+ def _literal_const_sample_generator(self, pyfunc, consts):
625
+ """
626
+ This takes a python function, pyfunc, and manipulates its co_const
627
+ __code__ member to create a new function with different co_consts as
628
+ supplied in argument consts.
629
+
630
+ consts is a dict {index: value} of co_const tuple index to constant
631
+ value used to update a pyfunc clone's co_const.
632
+ """
633
+ pyfunc_code = pyfunc.__code__
634
+
635
+ # translate consts spec to update the constants
636
+ co_consts = {k: v for k, v in enumerate(pyfunc_code.co_consts)}
637
+ for k, v in consts.items():
638
+ co_consts[k] = v
639
+ new_consts = tuple([v for _, v in sorted(co_consts.items())])
640
+
641
+ # create code object with mutation
642
+ new_code = pyfunc_code.replace(co_consts=new_consts)
643
+
644
+ # get function
645
+ return pytypes.FunctionType(new_code, globals())
646
+
647
+ def test_literal_const_code_gen(self):
648
+ def impl(x):
649
+ _CONST1 = "PLACEHOLDER1"
650
+ if _CONST1:
651
+ return 3.14159
652
+ else:
653
+ _CONST2 = "PLACEHOLDER2"
654
+ return _CONST2 + 4
655
+
656
+ new = self._literal_const_sample_generator(impl, {1:0, 3:20})
657
+ iconst = impl.__code__.co_consts
658
+ nconst = new.__code__.co_consts
659
+ self.assertEqual(iconst, (None, "PLACEHOLDER1", 3.14159,
660
+ "PLACEHOLDER2", 4))
661
+ self.assertEqual(nconst, (None, 0, 3.14159, 20, 4))
662
+ self.assertEqual(impl(None), 3.14159)
663
+ self.assertEqual(new(None), 24)
664
+
665
+ def test_single_if_const(self):
666
+
667
+ def impl(x):
668
+ _CONST1 = "PLACEHOLDER1"
669
+ if _CONST1:
670
+ return 3.14159
671
+
672
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
673
+ for const in c_inp:
674
+ func = self._literal_const_sample_generator(impl, {1: const})
675
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
676
+ None)
677
+
678
+ def test_single_if_negate_const(self):
679
+
680
+ def impl(x):
681
+ _CONST1 = "PLACEHOLDER1"
682
+ if not _CONST1:
683
+ return 3.14159
684
+
685
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
686
+ for const in c_inp:
687
+ func = self._literal_const_sample_generator(impl, {1: const})
688
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
689
+ None)
690
+
691
+ def test_single_if_else_const(self):
692
+
693
+ def impl(x):
694
+ _CONST1 = "PLACEHOLDER1"
695
+ if _CONST1:
696
+ return 3.14159
697
+ else:
698
+ return 1.61803
699
+
700
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
701
+ for const in c_inp:
702
+ func = self._literal_const_sample_generator(impl, {1: const})
703
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
704
+ None)
705
+
706
+ def test_single_if_else_negate_const(self):
707
+
708
+ def impl(x):
709
+ _CONST1 = "PLACEHOLDER1"
710
+ if not _CONST1:
711
+ return 3.14159
712
+ else:
713
+ return 1.61803
714
+
715
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
716
+ for const in c_inp:
717
+ func = self._literal_const_sample_generator(impl, {1: const})
718
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
719
+ None)
720
+
721
+ def test_single_if_freevar(self):
722
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
723
+ for const in c_inp:
724
+
725
+ def func(x):
726
+ if const:
727
+ return 3.14159, const
728
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
729
+ None)
730
+
731
+ def test_single_if_negate_freevar(self):
732
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
733
+ for const in c_inp:
734
+
735
+ def func(x):
736
+ if not const:
737
+ return 3.14159, const
738
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
739
+ None)
740
+
741
+ def test_single_if_else_freevar(self):
742
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
743
+ for const in c_inp:
744
+
745
+ def func(x):
746
+ if const:
747
+ return 3.14159, const
748
+ else:
749
+ return 1.61803, const
750
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
751
+ None)
752
+
753
+ def test_single_if_else_negate_freevar(self):
754
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
755
+ for const in c_inp:
756
+
757
+ def func(x):
758
+ if not const:
759
+ return 3.14159, const
760
+ else:
761
+ return 1.61803, const
762
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
763
+ None)
764
+
765
+ # globals in this section have absurd names after their test usecase names
766
+ # so as to prevent collisions and permit tests to run in parallel
767
+ def test_single_if_global(self):
768
+ global c_test_single_if_global
769
+
770
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
771
+ for c in c_inp:
772
+ c_test_single_if_global = c
773
+
774
+ def func(x):
775
+ if c_test_single_if_global:
776
+ return 3.14159, c_test_single_if_global
777
+
778
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
779
+ None)
780
+
781
+ def test_single_if_negate_global(self):
782
+ global c_test_single_if_negate_global
783
+
784
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
785
+ for c in c_inp:
786
+ c_test_single_if_negate_global = c
787
+
788
+ def func(x):
789
+ if c_test_single_if_negate_global:
790
+ return 3.14159, c_test_single_if_negate_global
791
+
792
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
793
+ None)
794
+
795
+ def test_single_if_else_global(self):
796
+ global c_test_single_if_else_global
797
+
798
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
799
+ for c in c_inp:
800
+ c_test_single_if_else_global = c
801
+
802
+ def func(x):
803
+ if c_test_single_if_else_global:
804
+ return 3.14159, c_test_single_if_else_global
805
+ else:
806
+ return 1.61803, c_test_single_if_else_global
807
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
808
+ None)
809
+
810
+ def test_single_if_else_negate_global(self):
811
+ global c_test_single_if_else_negate_global
812
+
813
+ for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True):
814
+ for c in c_inp:
815
+ c_test_single_if_else_negate_global = c
816
+
817
+ def func(x):
818
+ if not c_test_single_if_else_negate_global:
819
+ return 3.14159, c_test_single_if_else_negate_global
820
+ else:
821
+ return 1.61803, c_test_single_if_else_negate_global
822
+ self.assert_prune(func, (types.NoneType('none'),), [prune],
823
+ None)
824
+
825
+ def test_issue_5618(self):
826
+
827
+ @njit
828
+ def foo():
829
+ values = np.zeros(1)
830
+ tmp = 666
831
+ if tmp:
832
+ values[0] = tmp
833
+ return values
834
+
835
+ self.assertPreciseEqual(foo.py_func()[0], 666.)
836
+ self.assertPreciseEqual(foo()[0], 666.)
837
+
838
+
839
+ class TestBranchPruneSSA(MemoryLeakMixin, TestCase):
840
+ # Tests SSA rewiring of phi nodes after branch pruning.
841
+
842
+ class SSAPrunerCompiler(CompilerBase):
843
+ def define_pipelines(self):
844
+ # This is a simple pipeline that does branch pruning on IR in SSA
845
+ # form, then types and lowers as per the standard nopython pipeline.
846
+ pm = PassManager("testing pm")
847
+ pm.add_pass(TranslateByteCode, "analyzing bytecode")
848
+ pm.add_pass(IRProcessing, "processing IR")
849
+ # SSA early
850
+ pm.add_pass(ReconstructSSA, "ssa")
851
+ pm.add_pass(DeadBranchPrune, "dead branch pruning")
852
+ # type and then lower as usual
853
+ pm.add_pass(PreserveIR, "preserves the IR as metadata")
854
+ dpb = DefaultPassBuilder
855
+ typed_passes = dpb.define_typed_pipeline(self.state)
856
+ pm.passes.extend(typed_passes.passes)
857
+ lowering_passes = dpb.define_nopython_lowering_pipeline(self.state)
858
+ pm.passes.extend(lowering_passes.passes)
859
+ pm.finalize()
860
+ return [pm]
861
+
862
+ def test_ssa_update_phi(self):
863
+ # This checks that dead branch pruning is rewiring phi nodes correctly
864
+ # after a block containing an incoming for a phi is removed.
865
+
866
+ @njit(pipeline_class=self.SSAPrunerCompiler)
867
+ def impl(p=None, q=None):
868
+ z = 1
869
+ r = False
870
+ if p is None:
871
+ r = True # live
872
+
873
+ if r and q is not None:
874
+ z = 20 # dead
875
+
876
+ # one of the incoming blocks for z is dead, the phi needs an update
877
+ # were this not done, it would refer to variables that do not exist
878
+ # and result in a lowering error.
879
+ return z, r
880
+
881
+ self.assertPreciseEqual(impl(), impl.py_func())
882
+
883
+ def test_ssa_replace_phi(self):
884
+ # This checks that when a phi only has one incoming, because the other
885
+ # has been pruned, that a direct assignment is used instead.
886
+
887
+ @njit(pipeline_class=self.SSAPrunerCompiler)
888
+ def impl(p=None):
889
+ z = 0
890
+ if p is None:
891
+ z = 10
892
+ else:
893
+ z = 20
894
+
895
+ return z
896
+
897
+ self.assertPreciseEqual(impl(), impl.py_func())
898
+ func_ir = impl.overloads[impl.signatures[0]].metadata['preserved_ir']
899
+
900
+ # check the func_ir, make sure there's no phi nodes
901
+ for blk in func_ir.blocks.values():
902
+ self.assertFalse([*blk.find_exprs('phi')])
903
+
904
+
905
+ class TestBranchPrunePostSemanticConstRewrites(TestBranchPruneBase):
906
+ # Tests that semantic constants rewriting works by virtue of branch pruning
907
+
908
+ def test_array_ndim_attr(self):
909
+
910
+ def impl(array):
911
+ if array.ndim == 2:
912
+ if array.shape[1] == 2:
913
+ return 1
914
+ else:
915
+ return 10
916
+
917
+ self.assert_prune(impl, (types.Array(types.float64, 2, 'C'),), [False,
918
+ None],
919
+ np.zeros((2, 3)))
920
+ self.assert_prune(impl, (types.Array(types.float64, 1, 'C'),), [True,
921
+ 'both'],
922
+ np.zeros((2,)))
923
+
924
+ def test_tuple_len(self):
925
+
926
+ def impl(tup):
927
+ if len(tup) == 3:
928
+ if tup[2] == 2:
929
+ return 1
930
+ else:
931
+ return 0
932
+
933
+ self.assert_prune(impl, (types.UniTuple(types.int64, 3),), [False,
934
+ None],
935
+ tuple([1, 2, 3]))
936
+ self.assert_prune(impl, (types.UniTuple(types.int64, 2),), [True,
937
+ 'both'],
938
+ tuple([1, 2]))
939
+
940
+ def test_attr_not_len(self):
941
+ # The purpose of this test is to make sure that the conditions guarding
942
+ # the rewrite part do not themselves raise exceptions.
943
+ # This produces an `ir.Expr` call node for `float.as_integer_ratio`,
944
+ # which is a getattr() on `float`.
945
+
946
+ @njit
947
+ def test():
948
+ float.as_integer_ratio(1.23)
949
+
950
+ # this should raise a TypingError
951
+ with self.assertRaises(errors.TypingError) as e:
952
+ test()
953
+
954
+ self.assertIn("Unknown attribute 'as_integer_ratio'", str(e.exception))
955
+
956
+ def test_ndim_not_on_array(self):
957
+
958
+ FakeArray = collections.namedtuple('FakeArray', ['ndim'])
959
+ fa = FakeArray(ndim=2)
960
+
961
+ def impl(fa):
962
+ if fa.ndim == 2:
963
+ return fa.ndim
964
+ else:
965
+ object()
966
+
967
+ # check prune works for array ndim
968
+ self.assert_prune(impl, (types.Array(types.float64, 2, 'C'),), [False],
969
+ np.zeros((2, 3)))
970
+
971
+ # check prune fails for something with `ndim` attr that is not array
972
+ FakeArrayType = types.NamedUniTuple(types.int64, 1, FakeArray)
973
+ self.assert_prune(impl, (FakeArrayType,), [None], fa,
974
+ flags={'nopython':False, 'forceobj':True})
975
+
976
+ def test_semantic_const_propagates_before_static_rewrites(self):
977
+ # see issue #5015, the ndim needs writing in as a const before
978
+ # the rewrite passes run to make e.g. getitems static where possible
979
+ @njit
980
+ def impl(a, b):
981
+ return a.shape[:b.ndim]
982
+
983
+ args = (np.zeros((5, 4, 3, 2)), np.zeros((1, 1)))
984
+
985
+ self.assertPreciseEqual(impl(*args), impl.py_func(*args))
986
+
987
+ def test_tuple_const_propagation(self):
988
+ @njit(pipeline_class=IRPreservingTestPipeline)
989
+ def impl(*args):
990
+ s = 0
991
+ for arg in literal_unroll(args):
992
+ s += len(arg)
993
+ return s
994
+
995
+ inp = ((), (1, 2, 3), ())
996
+ self.assertPreciseEqual(impl(*inp), impl.py_func(*inp))
997
+
998
+ ol = impl.overloads[impl.signatures[0]]
999
+ func_ir = ol.metadata['preserved_ir']
1000
+ # make sure one of the inplace binop args is a Const
1001
+ binop_consts = set()
1002
+ for blk in func_ir.blocks.values():
1003
+ for expr in blk.find_exprs('inplace_binop'):
1004
+ inst = blk.find_variable_assignment(expr.rhs.name)
1005
+ self.assertIsInstance(inst.value, ir.Const)
1006
+ binop_consts.add(inst.value.value)
1007
+ self.assertEqual(binop_consts, {len(x) for x in inp})
lib/python3.10/site-packages/numba/tests/test_annotations.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from io import StringIO
3
+
4
+ import numba
5
+ from numba.core import types
6
+ from numba import jit, njit
7
+ from numba.tests.support import override_config, TestCase
8
+ import unittest
9
+
10
+ try:
11
+ import jinja2
12
+ except ImportError:
13
+ jinja2 = None
14
+
15
+ try:
16
+ import pygments
17
+ except ImportError:
18
+ pygments = None
19
+
20
+
21
+ @unittest.skipIf(jinja2 is None, "please install the 'jinja2' package")
22
+ class TestAnnotation(TestCase):
23
+
24
+ @TestCase.run_test_in_subprocess # annotations compound per module
25
+ def test_exercise_code_path(self):
26
+ """
27
+ Ensures template.html is available
28
+ """
29
+
30
+ def foo(n, a):
31
+ s = a
32
+ for i in range(n):
33
+ s += i
34
+ return s
35
+
36
+ cfunc = njit((types.int32, types.int32))(foo)
37
+ cres = cfunc.overloads[cfunc.signatures[0]]
38
+ ta = cres.type_annotation
39
+
40
+ buf = StringIO()
41
+ ta.html_annotate(buf)
42
+ output = buf.getvalue()
43
+ buf.close()
44
+ self.assertIn("foo", output)
45
+
46
+ @TestCase.run_test_in_subprocess # annotations compound per module
47
+ def test_exercise_code_path_with_lifted_loop(self):
48
+ """
49
+ Ensures that lifted loops are handled correctly in obj mode
50
+ """
51
+ # the functions to jit
52
+ def bar(x):
53
+ return x
54
+
55
+ def foo(x):
56
+ h = 0.
57
+ for i in range(x): # py 38 needs two loops for one to lift?!
58
+ h = h + i
59
+ for k in range(x):
60
+ h = h + k
61
+ if x:
62
+ h = h - bar(x)
63
+ return h
64
+
65
+ # compile into an isolated context
66
+ cfunc = jit((types.intp,), forceobj=True, looplift=True)(foo)
67
+ cres = cfunc.overloads[cfunc.signatures[0]]
68
+
69
+ ta = cres.type_annotation
70
+
71
+ buf = StringIO()
72
+ ta.html_annotate(buf)
73
+ output = buf.getvalue()
74
+ buf.close()
75
+ self.assertIn("bar", output)
76
+ self.assertIn("foo", output)
77
+ self.assertIn("LiftedLoop", output)
78
+
79
+ @TestCase.run_test_in_subprocess # annotations compound per module
80
+ def test_html_output_with_lifted_loop(self):
81
+ """
82
+ Test some format and behavior of the html annotation with lifted loop
83
+ """
84
+ @numba.jit(forceobj=True)
85
+ def udt(x):
86
+ object() # to force object mode
87
+ z = 0
88
+ for i in range(x): # this line is tagged
89
+ z += i
90
+ return z
91
+
92
+ # Regex pattern to check for the "lifted_tag" in the line of the loop
93
+ re_lifted_tag = re.compile(
94
+ r'<td class="lifted_tag">\s*'
95
+ r'\s*<details>'
96
+ r'\s*<summary>'
97
+ r'\s*<code>'
98
+ r'\s*[0-9]+:'
99
+ r'\s*[&nbsp;]+for i in range\(x\): # this line is tagged\s*',
100
+ re.MULTILINE)
101
+
102
+ # Compile int64 version
103
+ sig_i64 = (types.int64,)
104
+ udt.compile(sig_i64) # compile with lifted loop
105
+ cres = udt.overloads[sig_i64]
106
+
107
+ # Make html output
108
+ buf = StringIO()
109
+ cres.type_annotation.html_annotate(buf)
110
+ output = buf.getvalue()
111
+ buf.close()
112
+
113
+ # There should be only one function output.
114
+ self.assertEqual(output.count("Function name: udt"), 1)
115
+
116
+ sigfmt = "with signature: {} -&gt; pyobject"
117
+ self.assertEqual(output.count(sigfmt.format(sig_i64)), 1)
118
+ # Ensure the loop is tagged
119
+ self.assertEqual(len(re.findall(re_lifted_tag, output)), 1,
120
+ msg='%s not found in %s' % (re_lifted_tag, output))
121
+
122
+ # Compile float64 version
123
+ sig_f64 = (types.float64,)
124
+ udt.compile(sig_f64)
125
+ cres = udt.overloads[sig_f64]
126
+
127
+ # Make html output
128
+ buf = StringIO()
129
+ cres.type_annotation.html_annotate(buf)
130
+ output = buf.getvalue()
131
+ buf.close()
132
+
133
+ # There should be two function output
134
+ self.assertEqual(output.count("Function name: udt"), 2)
135
+ self.assertEqual(output.count(sigfmt.format(sig_i64)), 1)
136
+ self.assertEqual(output.count(sigfmt.format(sig_f64)), 1)
137
+ # Ensure the loop is tagged in both output
138
+ self.assertEqual(len(re.findall(re_lifted_tag, output)), 2)
139
+
140
+ @unittest.skipIf(pygments is None, "please install the 'pygments' package")
141
+ def test_pretty_print(self):
142
+
143
+ @numba.njit
144
+ def foo(x, y):
145
+ return x, y
146
+
147
+ foo(1, 2)
148
+ # Exercise the method
149
+ foo.inspect_types(pretty=True)
150
+
151
+ # Exercise but supply a not None file kwarg, this is invalid
152
+ with self.assertRaises(ValueError) as raises:
153
+ foo.inspect_types(pretty=True, file='should be None')
154
+ self.assertIn('`file` must be None if `pretty=True`',
155
+ str(raises.exception))
156
+
157
+
158
+ class TestTypeAnnotation(unittest.TestCase):
159
+
160
+ def findpatloc(self, lines, pat):
161
+ for i, ln in enumerate(lines):
162
+ if pat in ln:
163
+ return i
164
+ raise ValueError("can't find {!r}".format(pat))
165
+
166
+ def getlines(self, func):
167
+ strbuf = StringIO()
168
+ func.inspect_types(strbuf)
169
+ return strbuf.getvalue().splitlines()
170
+
171
+ def test_delete(self):
172
+ @numba.njit
173
+ def foo(appleorange, berrycherry):
174
+ return appleorange + berrycherry
175
+
176
+ foo(1, 2)
177
+
178
+ lines = self.getlines(foo)
179
+
180
+ # Ensure deletion show up after their use
181
+ sa = self.findpatloc(lines, 'appleorange = arg(0, name=appleorange)')
182
+ sb = self.findpatloc(lines, 'berrycherry = arg(1, name=berrycherry)')
183
+
184
+ ea = self.findpatloc(lines, 'del appleorange')
185
+ eb = self.findpatloc(lines, 'del berrycherry')
186
+
187
+ self.assertLess(sa, ea)
188
+ self.assertLess(sb, eb)
189
+
190
+ def _lifetimes_impl(self, extend):
191
+ with override_config('EXTEND_VARIABLE_LIFETIMES', extend):
192
+ @njit
193
+ def foo(a):
194
+ b = a
195
+ return b
196
+ x = 10
197
+ b = foo(x)
198
+ self.assertEqual(b, x)
199
+
200
+ lines = self.getlines(foo)
201
+
202
+ sa = self.findpatloc(lines, 'a = arg(0, name=a)')
203
+ sb = self.findpatloc(lines, 'b = a')
204
+
205
+ cast_ret = self.findpatloc(lines, 'cast(value=b)')
206
+
207
+ dela = self.findpatloc(lines, 'del a')
208
+ delb = self.findpatloc(lines, 'del b')
209
+
210
+ return sa, sb, cast_ret, dela, delb
211
+
212
+ def test_delete_standard_lifetimes(self):
213
+ # without extended lifetimes, dels occur as soon as dead
214
+ #
215
+ # label 0
216
+ # a = arg(0, name=a) :: int64
217
+ # b = a :: int64
218
+ # del a
219
+ # $8return_value.2 = cast(value=b) :: int64
220
+ # del b
221
+ # return $8return_value.2
222
+
223
+ sa, sb, cast_ret, dela, delb = self._lifetimes_impl(extend=0)
224
+
225
+ self.assertLess(sa, dela)
226
+ self.assertLess(sb, delb)
227
+ # del a is before cast and del b is after
228
+ self.assertLess(dela, cast_ret)
229
+ self.assertGreater(delb, cast_ret)
230
+
231
+ def test_delete_extended_lifetimes(self):
232
+ # with extended lifetimes, dels are last in block:
233
+ #
234
+ # label 0
235
+ # a = arg(0, name=a) :: int64
236
+ # b = a :: int64
237
+ # $8return_value.2 = cast(value=b) :: int64
238
+ # del a
239
+ # del b
240
+ # return $8return_value.2
241
+
242
+ sa, sb, cast_ret, dela, delb = self._lifetimes_impl(extend=1)
243
+
244
+ self.assertLess(sa, dela)
245
+ self.assertLess(sb, delb)
246
+ # dels are after the cast
247
+ self.assertGreater(dela, cast_ret)
248
+ self.assertGreater(delb, cast_ret)
249
+
250
+
251
+ if __name__ == '__main__':
252
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_array_exprs.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ from io import StringIO
3
+
4
+ import numpy as np
5
+
6
+ from numba import njit, vectorize
7
+ from numba import typeof
8
+ from numba.core import utils, types, typing, ir, compiler, cpu, cgutils
9
+ from numba.core.compiler import Compiler, Flags
10
+ from numba.core.registry import cpu_target
11
+ from numba.tests.support import (MemoryLeakMixin, TestCase, temp_directory,
12
+ create_temp_module)
13
+ from numba.extending import (
14
+ overload,
15
+ models,
16
+ lower_builtin,
17
+ register_model,
18
+ make_attribute_wrapper,
19
+ type_callable,
20
+ typeof_impl
21
+ )
22
+ import operator
23
+ import textwrap
24
+
25
+ import unittest
26
+
27
+
28
+ class Namespace(dict):
29
+ def __getattr__(s, k):
30
+ return s[k] if k in s else super(Namespace, s).__getattr__(k)
31
+
32
+ def axy(a, x, y):
33
+ return a * x + y
34
+
35
+ def ax2(a, x, y):
36
+ return a * x + y
37
+
38
+ def pos_root(As, Bs, Cs):
39
+ return (-Bs + (((Bs ** 2.) - (4. * As * Cs)) ** 0.5)) / (2. * As)
40
+
41
+ def neg_root_common_subexpr(As, Bs, Cs):
42
+ _2As = 2. * As
43
+ _4AsCs = 2. * _2As * Cs
44
+ _Bs2_4AsCs = (Bs ** 2. - _4AsCs)
45
+ return (-Bs - (_Bs2_4AsCs ** 0.5)) / _2As
46
+
47
+ def neg_root_complex_subexpr(As, Bs, Cs):
48
+ _2As = 2. * As
49
+ _4AsCs = 2. * _2As * Cs
50
+ _Bs2_4AsCs = (Bs ** 2. - _4AsCs) + 0j # Force into the complex domain.
51
+ return (-Bs - (_Bs2_4AsCs ** 0.5)) / _2As
52
+
53
+ vaxy = vectorize(axy)
54
+
55
+ def call_stuff(a0, a1):
56
+ return np.cos(vaxy(a0, np.sin(a1) - 1., 1.))
57
+
58
+ def are_roots_imaginary(As, Bs, Cs):
59
+ return (Bs ** 2 - 4 * As * Cs) < 0
60
+
61
+ def div_add(As, Bs, Cs):
62
+ return As / Bs + Cs
63
+
64
+ def cube(As):
65
+ return As ** 3
66
+
67
+ def explicit_output(a, b, out):
68
+ np.cos(a, out)
69
+ return np.add(out, b, out)
70
+
71
+ def variable_name_reuse(a, b, c, d):
72
+ u = a + b
73
+ u = u - a * b
74
+ u = u * c + d
75
+ return u
76
+
77
+
78
+ # From issue #1264
79
+ def distance_matrix(vectors):
80
+ n_vectors = vectors.shape[0]
81
+ result = np.empty((n_vectors, n_vectors), dtype=np.float64)
82
+
83
+ for i in range(n_vectors):
84
+ for j in range(i, n_vectors):
85
+ result[i,j] = result[j,i] = np.sum(
86
+ (vectors[i] - vectors[j]) ** 2) ** 0.5
87
+
88
+ return result
89
+
90
+
91
+ class RewritesTester(Compiler):
92
+ @classmethod
93
+ def mk_pipeline(cls, args, return_type=None, flags=None, locals={},
94
+ library=None, typing_context=None, target_context=None):
95
+ if not flags:
96
+ flags = Flags()
97
+ flags.nrt = True
98
+ if typing_context is None:
99
+ typing_context = cpu_target.typing_context
100
+ if target_context is None:
101
+ target_context = cpu_target.target_context
102
+ return cls(typing_context, target_context, library, args, return_type,
103
+ flags, locals)
104
+
105
+ @classmethod
106
+ def mk_no_rw_pipeline(cls, args, return_type=None, flags=None, locals={},
107
+ library=None, **kws):
108
+ if not flags:
109
+ flags = Flags()
110
+ flags.no_rewrites = True
111
+ return cls.mk_pipeline(args, return_type, flags, locals, library, **kws)
112
+
113
+
114
+ class TestArrayExpressions(MemoryLeakMixin, TestCase):
115
+
116
+ def _compile_function(self, fn, arg_tys):
117
+ """
118
+ Compile the given function both without and with rewrites enabled.
119
+ """
120
+ control_pipeline = RewritesTester.mk_no_rw_pipeline(arg_tys)
121
+ cres_0 = control_pipeline.compile_extra(fn)
122
+ control_cfunc = cres_0.entry_point
123
+
124
+ test_pipeline = RewritesTester.mk_pipeline(arg_tys)
125
+ cres_1 = test_pipeline.compile_extra(fn)
126
+ test_cfunc = cres_1.entry_point
127
+
128
+ return control_pipeline, control_cfunc, test_pipeline, test_cfunc
129
+
130
+ def test_simple_expr(self):
131
+ '''
132
+ Using a simple array expression, verify that rewriting is taking
133
+ place, and is fusing loops.
134
+ '''
135
+ A = np.linspace(0,1,10)
136
+ X = np.linspace(2,1,10)
137
+ Y = np.linspace(1,2,10)
138
+ arg_tys = [typeof(arg) for arg in (A, X, Y)]
139
+
140
+ control_pipeline, nb_axy_0, test_pipeline, nb_axy_1 = \
141
+ self._compile_function(axy, arg_tys)
142
+
143
+ control_pipeline2 = RewritesTester.mk_no_rw_pipeline(arg_tys)
144
+ cres_2 = control_pipeline2.compile_extra(ax2)
145
+ nb_ctl = cres_2.entry_point
146
+
147
+ expected = nb_axy_0(A, X, Y)
148
+ actual = nb_axy_1(A, X, Y)
149
+ control = nb_ctl(A, X, Y)
150
+ np.testing.assert_array_equal(expected, actual)
151
+ np.testing.assert_array_equal(control, actual)
152
+
153
+ ir0 = control_pipeline.state.func_ir.blocks
154
+ ir1 = test_pipeline.state.func_ir.blocks
155
+ ir2 = control_pipeline2.state.func_ir.blocks
156
+ self.assertEqual(len(ir0), len(ir1))
157
+ self.assertEqual(len(ir0), len(ir2))
158
+ # The rewritten IR should be smaller than the original.
159
+ self.assertGreater(len(ir0[0].body), len(ir1[0].body))
160
+ self.assertEqual(len(ir0[0].body), len(ir2[0].body))
161
+
162
+ def _get_array_exprs(self, block):
163
+ for instr in block:
164
+ if isinstance(instr, ir.Assign):
165
+ if isinstance(instr.value, ir.Expr):
166
+ if instr.value.op == 'arrayexpr':
167
+ yield instr
168
+
169
+ def _array_expr_to_set(self, expr, out=None):
170
+ '''
171
+ Convert an array expression tree into a set of operators.
172
+ '''
173
+ if out is None:
174
+ out = set()
175
+ if not isinstance(expr, tuple):
176
+ raise ValueError("{0} not a tuple".format(expr))
177
+ operation, operands = expr
178
+ processed_operands = []
179
+ for operand in operands:
180
+ if isinstance(operand, tuple):
181
+ operand, _ = self._array_expr_to_set(operand, out)
182
+ processed_operands.append(operand)
183
+ processed_expr = operation, tuple(processed_operands)
184
+ out.add(processed_expr)
185
+ return processed_expr, out
186
+
187
+ def _test_root_function(self, fn=pos_root):
188
+ A = np.random.random(10)
189
+ B = np.random.random(10) + 1. # Increase likelihood of real
190
+ # root (could add 2 to force all
191
+ # roots to be real).
192
+ C = np.random.random(10)
193
+ arg_tys = [typeof(arg) for arg in (A, B, C)]
194
+
195
+ control_pipeline = RewritesTester.mk_no_rw_pipeline(arg_tys)
196
+ control_cres = control_pipeline.compile_extra(fn)
197
+ nb_fn_0 = control_cres.entry_point
198
+
199
+ test_pipeline = RewritesTester.mk_pipeline(arg_tys)
200
+ test_cres = test_pipeline.compile_extra(fn)
201
+ nb_fn_1 = test_cres.entry_point
202
+
203
+ np_result = fn(A, B, C)
204
+ nb_result_0 = nb_fn_0(A, B, C)
205
+ nb_result_1 = nb_fn_1(A, B, C)
206
+ np.testing.assert_array_almost_equal(np_result, nb_result_0)
207
+ np.testing.assert_array_almost_equal(nb_result_0, nb_result_1)
208
+
209
+ return Namespace(locals())
210
+
211
+ def _test_cube_function(self, fn=cube):
212
+ A = np.arange(10, dtype=np.float64)
213
+ arg_tys = (typeof(A),)
214
+
215
+ control_pipeline = RewritesTester.mk_no_rw_pipeline(arg_tys)
216
+ control_cres = control_pipeline.compile_extra(fn)
217
+ nb_fn_0 = control_cres.entry_point
218
+
219
+ test_pipeline = RewritesTester.mk_pipeline(arg_tys)
220
+ test_cres = test_pipeline.compile_extra(fn)
221
+ nb_fn_1 = test_cres.entry_point
222
+
223
+ expected = A ** 3
224
+ self.assertPreciseEqual(expected, nb_fn_0(A))
225
+ self.assertPreciseEqual(expected, nb_fn_1(A))
226
+
227
+ return Namespace(locals())
228
+
229
+ def _test_explicit_output_function(self, fn):
230
+ """
231
+ Test function having a (a, b, out) signature where *out* is
232
+ an output array the function writes into.
233
+ """
234
+ A = np.arange(10, dtype=np.float64)
235
+ B = A + 1
236
+ arg_tys = (typeof(A),) * 3
237
+
238
+ control_pipeline, control_cfunc, test_pipeline, test_cfunc = \
239
+ self._compile_function(fn, arg_tys)
240
+
241
+ def run_func(fn):
242
+ out = np.zeros_like(A)
243
+ fn(A, B, out)
244
+ return out
245
+
246
+ expected = run_func(fn)
247
+ self.assertPreciseEqual(expected, run_func(control_cfunc))
248
+ self.assertPreciseEqual(expected, run_func(test_cfunc))
249
+
250
+ return Namespace(locals())
251
+
252
+ def _assert_array_exprs(self, block, expected_count):
253
+ """
254
+ Assert the *block* has the expected number of array expressions
255
+ in it.
256
+ """
257
+ rewrite_count = len(list(self._get_array_exprs(block)))
258
+ self.assertEqual(rewrite_count, expected_count)
259
+
260
+ def _assert_total_rewrite(self, control_ir, test_ir, trivial=False):
261
+ """
262
+ Given two dictionaries of Numba IR blocks, check to make sure the
263
+ control IR has no array expressions, while the test IR
264
+ contains one and only one.
265
+ """
266
+ # Both IRs have the same number of blocks (presumably 1)
267
+ self.assertEqual(len(control_ir), len(test_ir))
268
+ control_block = control_ir[0].body
269
+ test_block = test_ir[0].body
270
+ self._assert_array_exprs(control_block, 0)
271
+ self._assert_array_exprs(test_block, 1)
272
+ if not trivial:
273
+ # If the expression wasn't trivial, the block length should
274
+ # have decreased (since a sequence of exprs was replaced
275
+ # with a single nested array expr).
276
+ self.assertGreater(len(control_block), len(test_block))
277
+
278
+ def _assert_no_rewrite(self, control_ir, test_ir):
279
+ """
280
+ Given two dictionaries of Numba IR blocks, check to make sure
281
+ the control IR and the test IR both have no array expressions.
282
+ """
283
+ self.assertEqual(len(control_ir), len(test_ir))
284
+ # All blocks should be identical, and not rewritten
285
+ for k, v in control_ir.items():
286
+ control_block = v.body
287
+ test_block = test_ir[k].body
288
+ self.assertEqual(len(control_block), len(test_block))
289
+ self._assert_array_exprs(control_block, 0)
290
+ self._assert_array_exprs(test_block, 0)
291
+
292
+ def test_trivial_expr(self):
293
+ """
294
+ Ensure even a non-nested expression is rewritten, as it can enable
295
+ scalar optimizations such as rewriting `x ** 2`.
296
+ """
297
+ ns = self._test_cube_function()
298
+ self._assert_total_rewrite(ns.control_pipeline.state.func_ir.blocks,
299
+ ns.test_pipeline.state.func_ir.blocks,
300
+ trivial=True)
301
+
302
+ def test_complicated_expr(self):
303
+ '''
304
+ Using the polynomial root function, ensure the full expression is
305
+ being put in the same kernel with no remnants of intermediate
306
+ array expressions.
307
+ '''
308
+ ns = self._test_root_function()
309
+ self._assert_total_rewrite(ns.control_pipeline.state.func_ir.blocks,
310
+ ns.test_pipeline.state.func_ir.blocks)
311
+
312
+ def test_common_subexpressions(self, fn=neg_root_common_subexpr):
313
+ '''
314
+ Attempt to verify that rewriting will incorporate user common
315
+ subexpressions properly.
316
+ '''
317
+ ns = self._test_root_function(fn)
318
+ ir0 = ns.control_pipeline.state.func_ir.blocks
319
+ ir1 = ns.test_pipeline.state.func_ir.blocks
320
+ self.assertEqual(len(ir0), len(ir1))
321
+ self.assertGreater(len(ir0[0].body), len(ir1[0].body))
322
+ self.assertEqual(len(list(self._get_array_exprs(ir0[0].body))), 0)
323
+ # Verify that we didn't rewrite everything into a monolithic
324
+ # array expression since we stored temporary values in
325
+ # variables that might be used later (from the optimization's
326
+ # point of view).
327
+ array_expr_instrs = list(self._get_array_exprs(ir1[0].body))
328
+ self.assertGreater(len(array_expr_instrs), 1)
329
+ # Now check that we haven't duplicated any subexpressions in
330
+ # the rewritten code.
331
+ array_sets = list(self._array_expr_to_set(instr.value.expr)[1]
332
+ for instr in array_expr_instrs)
333
+ for expr_set_0, expr_set_1 in zip(array_sets[:-1], array_sets[1:]):
334
+ intersections = expr_set_0.intersection(expr_set_1)
335
+ if intersections:
336
+ self.fail("Common subexpressions detected in array "
337
+ "expressions ({0})".format(intersections))
338
+
339
+ def test_complex_subexpression(self):
340
+ return self.test_common_subexpressions(neg_root_complex_subexpr)
341
+
342
+ def test_ufunc_and_dufunc_calls(self):
343
+ '''
344
+ Verify that ufunc and DUFunc calls are being properly included in
345
+ array expressions.
346
+ '''
347
+ A = np.random.random(10)
348
+ B = np.random.random(10)
349
+ arg_tys = [typeof(arg) for arg in (A, B)]
350
+
351
+ vaxy_descr = vaxy._dispatcher.targetdescr
352
+ control_pipeline = RewritesTester.mk_no_rw_pipeline(
353
+ arg_tys,
354
+ typing_context=vaxy_descr.typing_context,
355
+ target_context=vaxy_descr.target_context)
356
+ cres_0 = control_pipeline.compile_extra(call_stuff)
357
+ nb_call_stuff_0 = cres_0.entry_point
358
+
359
+ test_pipeline = RewritesTester.mk_pipeline(
360
+ arg_tys,
361
+ typing_context=vaxy_descr.typing_context,
362
+ target_context=vaxy_descr.target_context)
363
+ cres_1 = test_pipeline.compile_extra(call_stuff)
364
+ nb_call_stuff_1 = cres_1.entry_point
365
+
366
+ expected = call_stuff(A, B)
367
+ control = nb_call_stuff_0(A, B)
368
+ actual = nb_call_stuff_1(A, B)
369
+ np.testing.assert_array_almost_equal(expected, control)
370
+ np.testing.assert_array_almost_equal(expected, actual)
371
+
372
+ self._assert_total_rewrite(control_pipeline.state.func_ir.blocks,
373
+ test_pipeline.state.func_ir.blocks)
374
+
375
+ def test_cmp_op(self):
376
+ '''
377
+ Verify that comparison operators are supported by the rewriter.
378
+ '''
379
+ ns = self._test_root_function(are_roots_imaginary)
380
+ self._assert_total_rewrite(ns.control_pipeline.state.func_ir.blocks,
381
+ ns.test_pipeline.state.func_ir.blocks)
382
+
383
+ def test_explicit_output(self):
384
+ """
385
+ Check that ufunc calls with explicit outputs are not rewritten.
386
+ """
387
+ ns = self._test_explicit_output_function(explicit_output)
388
+ self._assert_no_rewrite(ns.control_pipeline.state.func_ir.blocks,
389
+ ns.test_pipeline.state.func_ir.blocks)
390
+
391
+
392
+ class TestRewriteIssues(MemoryLeakMixin, TestCase):
393
+
394
+ def test_issue_1184(self):
395
+ from numba import jit
396
+ import numpy as np
397
+
398
+ @jit(nopython=True)
399
+ def foo(arr):
400
+ return arr
401
+
402
+ @jit(nopython=True)
403
+ def bar(arr):
404
+ c = foo(arr)
405
+ d = foo(arr) # two calls to trigger rewrite
406
+ return c, d
407
+
408
+ arr = np.arange(10)
409
+ out_c, out_d = bar(arr)
410
+ self.assertIs(out_c, out_d)
411
+ self.assertIs(out_c, arr)
412
+
413
+ def test_issue_1264(self):
414
+ n = 100
415
+ x = np.random.uniform(size=n*3).reshape((n,3))
416
+ expected = distance_matrix(x)
417
+ actual = njit(distance_matrix)(x)
418
+ np.testing.assert_array_almost_equal(expected, actual)
419
+ # Avoid sporadic failures in MemoryLeakMixin.tearDown()
420
+ gc.collect()
421
+
422
+ def test_issue_1372(self):
423
+ """Test array expression with duplicated term"""
424
+ from numba import njit
425
+
426
+ @njit
427
+ def foo(a, b):
428
+ b = np.sin(b)
429
+ return b + b + a
430
+
431
+ a = np.random.uniform(10)
432
+ b = np.random.uniform(10)
433
+ expect = foo.py_func(a, b)
434
+ got = foo(a, b)
435
+ np.testing.assert_allclose(got, expect)
436
+
437
+ def test_unary_arrayexpr(self):
438
+ """
439
+ Typing of unary array expression (np.negate) can be incorrect.
440
+ """
441
+ @njit
442
+ def foo(a, b):
443
+ return b - a + -a
444
+
445
+ b = 1.5
446
+ a = np.arange(10, dtype=np.int32)
447
+
448
+ expect = foo.py_func(a, b)
449
+ got = foo(a, b)
450
+ self.assertPreciseEqual(got, expect)
451
+
452
+ def test_bitwise_arrayexpr(self):
453
+ """
454
+ Typing of bitwise boolean array expression can be incorrect
455
+ (issue #1813).
456
+ """
457
+ @njit
458
+ def foo(a, b):
459
+ return ~(a & (~b))
460
+
461
+ a = np.array([True, True, False, False])
462
+ b = np.array([False, True, False, True])
463
+
464
+ expect = foo.py_func(a, b)
465
+ got = foo(a, b)
466
+ self.assertPreciseEqual(got, expect)
467
+
468
+ def test_annotations(self):
469
+ """
470
+ Type annotation of array expressions with disambiguated
471
+ variable names (issue #1466).
472
+ """
473
+ cfunc = njit(variable_name_reuse)
474
+
475
+ a = np.linspace(0, 1, 10)
476
+ cfunc(a, a, a, a)
477
+
478
+ buf = StringIO()
479
+ cfunc.inspect_types(buf)
480
+ res = buf.getvalue()
481
+ self.assertIn("# u.1 = ", res)
482
+ self.assertIn("# u.2 = ", res)
483
+
484
+ def test_issue_5599_name_collision(self):
485
+ # The original error will fail in lowering of the array_expr
486
+ @njit
487
+ def f(x):
488
+ arr = np.ones(x)
489
+
490
+ for _ in range(2):
491
+ val = arr * arr
492
+ arr = arr.copy()
493
+ return arr
494
+
495
+ got = f(5)
496
+ expect = f.py_func(5)
497
+ np.testing.assert_array_equal(got, expect)
498
+
499
+
500
+ class TestSemantics(MemoryLeakMixin, unittest.TestCase):
501
+
502
+ def test_division_by_zero(self):
503
+ # Array expressions should follow the Numpy error model
504
+ # i.e. 1./0. returns +inf instead of raising ZeroDivisionError
505
+ pyfunc = div_add
506
+ cfunc = njit(pyfunc)
507
+
508
+ a = np.float64([0.0, 1.0, float('inf')])
509
+ b = np.float64([0.0, 0.0, 1.0])
510
+ c = np.ones_like(a)
511
+
512
+ expect = pyfunc(a, b, c)
513
+ got = cfunc(a, b, c)
514
+ np.testing.assert_array_equal(expect, got)
515
+
516
+
517
+ class TestOptionals(MemoryLeakMixin, unittest.TestCase):
518
+ """ Tests the arrival and correct lowering of Optional types at a arrayexpr
519
+ derived ufunc, see #3972"""
520
+
521
+ def test_optional_scalar_type(self):
522
+
523
+ @njit
524
+ def arr_expr(x, y):
525
+ return x + y
526
+
527
+ @njit
528
+ def do_call(x, y):
529
+ if y > 0:
530
+ z = None
531
+ else:
532
+ z = y
533
+ return arr_expr(x, z)
534
+
535
+ args = (np.arange(5), -1.2)
536
+
537
+ # check result
538
+ res = do_call(*args)
539
+ expected = do_call.py_func(*args)
540
+ np.testing.assert_allclose(res, expected)
541
+
542
+ # check type
543
+ s = arr_expr.signatures
544
+ oty = s[0][1]
545
+ self.assertTrue(isinstance(oty, types.Optional))
546
+ self.assertTrue(isinstance(oty.type, types.Float))
547
+
548
+ def test_optional_array_type(self):
549
+
550
+ @njit
551
+ def arr_expr(x, y):
552
+ return x + y
553
+
554
+ @njit
555
+ def do_call(x, y):
556
+ if y[0] > 0:
557
+ z = None
558
+ else:
559
+ z = y
560
+ return arr_expr(x, z)
561
+
562
+ args = (np.arange(5), np.arange(5.))
563
+
564
+ # check result
565
+ res = do_call(*args)
566
+ expected = do_call.py_func(*args)
567
+ np.testing.assert_allclose(res, expected)
568
+
569
+ # check type
570
+ s = arr_expr.signatures
571
+ oty = s[0][1]
572
+ self.assertTrue(isinstance(oty, types.Optional))
573
+ self.assertTrue(isinstance(oty.type, types.Array))
574
+ self.assertTrue(isinstance(oty.type.dtype, types.Float))
575
+
576
+
577
+ class TestOptionalsExceptions(MemoryLeakMixin, unittest.TestCase):
578
+ # same as above, but the Optional resolves to None and TypeError's
579
+
580
+ def test_optional_scalar_type_exception_on_none(self):
581
+
582
+ self.disable_leak_check()
583
+
584
+ @njit
585
+ def arr_expr(x, y):
586
+ return x + y
587
+
588
+ @njit
589
+ def do_call(x, y):
590
+ if y > 0:
591
+ z = None
592
+ else:
593
+ z = y
594
+ return arr_expr(x, z)
595
+
596
+ args = (np.arange(5), 1.0)
597
+
598
+ # check result
599
+ with self.assertRaises(TypeError) as raises:
600
+ do_call(*args)
601
+
602
+ self.assertIn("expected float64, got None", str(raises.exception))
603
+
604
+ # check type
605
+ s = arr_expr.signatures
606
+ oty = s[0][1]
607
+ self.assertTrue(isinstance(oty, types.Optional))
608
+ self.assertTrue(isinstance(oty.type, types.Float))
609
+
610
+ def test_optional_array_type_exception_on_none(self):
611
+
612
+ self.disable_leak_check()
613
+
614
+ @njit
615
+ def arr_expr(x, y):
616
+ return x + y
617
+
618
+ @njit
619
+ def do_call(x, y):
620
+ if y[0] > 0:
621
+ z = None
622
+ else:
623
+ z = y
624
+ return arr_expr(x, z)
625
+
626
+ args = (np.arange(5), np.arange(1., 5.))
627
+
628
+ # check result
629
+ with self.assertRaises(TypeError) as raises:
630
+ do_call(*args)
631
+
632
+ excstr = str(raises.exception)
633
+ self.assertIn("expected array(float64,", excstr)
634
+ self.assertIn("got None", excstr)
635
+
636
+ # check type
637
+ s = arr_expr.signatures
638
+ oty = s[0][1]
639
+ self.assertTrue(isinstance(oty, types.Optional))
640
+ self.assertTrue(isinstance(oty.type, types.Array))
641
+ self.assertTrue(isinstance(oty.type.dtype, types.Float))
642
+
643
+
644
+ class TestExternalTypes(MemoryLeakMixin, unittest.TestCase):
645
+ """ Tests RewriteArrayExprs with external (user defined) types,
646
+ see #5157"""
647
+
648
+ source_lines = textwrap.dedent("""
649
+ from numba.core import types
650
+
651
+ class FooType(types.Type):
652
+ def __init__(self):
653
+ super(FooType, self).__init__(name='Foo')
654
+ """)
655
+
656
+ def make_foo_type(self, FooType):
657
+ class Foo(object):
658
+ def __init__(self, value):
659
+ self.value = value
660
+
661
+ @register_model(FooType)
662
+ class FooModel(models.StructModel):
663
+ def __init__(self, dmm, fe_type):
664
+ members = [("value", types.intp)]
665
+ models.StructModel.__init__(self, dmm, fe_type, members)
666
+
667
+ make_attribute_wrapper(FooType, "value", "value")
668
+
669
+ @type_callable(Foo)
670
+ def type_foo(context):
671
+ def typer(value):
672
+ return FooType()
673
+
674
+ return typer
675
+
676
+ @lower_builtin(Foo, types.intp)
677
+ def impl_foo(context, builder, sig, args):
678
+ typ = sig.return_type
679
+ [value] = args
680
+ foo = cgutils.create_struct_proxy(typ)(context, builder)
681
+ foo.value = value
682
+ return foo._getvalue()
683
+
684
+ @typeof_impl.register(Foo)
685
+ def typeof_foo(val, c):
686
+ return FooType()
687
+
688
+ return Foo, FooType
689
+
690
+ def test_external_type(self):
691
+ with create_temp_module(self.source_lines) as test_module:
692
+ Foo, FooType = self.make_foo_type(test_module.FooType)
693
+
694
+ # sum of foo class instance and array return an array
695
+ # binary operation with foo class instance as one of args
696
+ @overload(operator.add)
697
+ def overload_foo_add(lhs, rhs):
698
+ if isinstance(lhs, FooType) and isinstance(rhs, types.Array):
699
+ def imp(lhs, rhs):
700
+ return np.array([lhs.value, rhs[0]])
701
+
702
+ return imp
703
+
704
+ # sum of 2 foo class instances return an array
705
+ # binary operation with 2 foo class instances as args
706
+ @overload(operator.add)
707
+ def overload_foo_add(lhs, rhs):
708
+ if isinstance(lhs, FooType) and isinstance(rhs, FooType):
709
+ def imp(lhs, rhs):
710
+ return np.array([lhs.value, rhs.value])
711
+
712
+ return imp
713
+
714
+ # neg of foo class instance return an array
715
+ # unary operation with foo class instance arg
716
+ @overload(operator.neg)
717
+ def overload_foo_neg(x):
718
+ if isinstance(x, FooType):
719
+ def imp(x):
720
+ return np.array([-x.value])
721
+
722
+ return imp
723
+
724
+ @njit
725
+ def arr_expr_sum1(x, y):
726
+ return Foo(x) + np.array([y])
727
+
728
+ @njit
729
+ def arr_expr_sum2(x, y):
730
+ return Foo(x) + Foo(y)
731
+
732
+ @njit
733
+ def arr_expr_neg(x):
734
+ return -Foo(x)
735
+
736
+ np.testing.assert_array_equal(arr_expr_sum1(0, 1), np.array([0, 1]))
737
+ np.testing.assert_array_equal(arr_expr_sum2(2, 3), np.array([2, 3]))
738
+ np.testing.assert_array_equal(arr_expr_neg(4), np.array([-4]))
739
+
740
+
741
+ if __name__ == "__main__":
742
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_array_manipulation.py ADDED
@@ -0,0 +1,1588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from itertools import permutations
3
+
4
+ import numpy as np
5
+
6
+ import unittest
7
+ from numba import jit, njit, from_dtype, typeof
8
+ from numba.core.errors import TypingError
9
+ from numba.core import types, errors
10
+ from numba.tests.support import TestCase, MemoryLeakMixin
11
+
12
+ enable_pyobj_flags = {'forceobj': True}
13
+
14
+ no_pyobj_flags = {'_nrt': True, 'nopython': True}
15
+
16
+
17
+ def from_generic(pyfuncs_to_use):
18
+ """Decorator for generic check functions.
19
+ Iterates over 'pyfuncs_to_use', calling 'func' with the iterated
20
+ item as first argument. Example:
21
+
22
+ @from_generic(numpy_array_reshape, array_reshape)
23
+ def check_only_shape(pyfunc, arr, shape, expected_shape):
24
+ # Only check Numba result to avoid Numpy bugs
25
+ self.memory_leak_setup()
26
+ got = generic_run(pyfunc, arr, shape)
27
+ self.assertEqual(got.shape, expected_shape)
28
+ self.assertEqual(got.size, arr.size)
29
+ del got
30
+ self.memory_leak_teardown()
31
+ """
32
+ def decorator(func):
33
+ def result(*args, **kwargs):
34
+ return [func(pyfunc, *args, **kwargs) for pyfunc in pyfuncs_to_use]
35
+ return result
36
+ return decorator
37
+
38
+
39
+ @njit
40
+ def array_reshape(arr, newshape):
41
+ return arr.reshape(newshape)
42
+
43
+ @njit
44
+ def numpy_array_reshape(arr, newshape):
45
+ return np.reshape(arr, newshape)
46
+
47
+
48
+ def numpy_broadcast_to(arr, shape):
49
+ return np.broadcast_to(arr, shape)
50
+
51
+
52
+ def numpy_broadcast_shapes(*args):
53
+ return np.broadcast_shapes(*args)
54
+
55
+
56
+ def numpy_broadcast_arrays(*args):
57
+ return np.broadcast_arrays(*args)
58
+
59
+
60
+ def numpy_broadcast_to_indexing(arr, shape, idx):
61
+ return np.broadcast_to(arr, shape)[idx]
62
+
63
+
64
+ def flatten_array(a):
65
+ return a.flatten()
66
+
67
+
68
+ def ravel_array(a):
69
+ return a.ravel()
70
+
71
+
72
+ def ravel_array_size(a):
73
+ return a.ravel().size
74
+
75
+
76
+ def numpy_ravel_array(a):
77
+ return np.ravel(a)
78
+
79
+
80
+ def transpose_array(a):
81
+ return a.transpose()
82
+
83
+
84
+ def numpy_transpose_array(a):
85
+ return np.transpose(a)
86
+
87
+
88
+ @njit
89
+ def numpy_transpose_array_axes_kwarg(arr, axes):
90
+ return np.transpose(arr, axes=axes)
91
+
92
+
93
+ @njit
94
+ def numpy_transpose_array_axes_kwarg_copy(arr, axes):
95
+ return np.transpose(arr, axes=axes).copy()
96
+
97
+
98
+ @njit
99
+ def array_transpose_axes(arr, axes):
100
+ return arr.transpose(axes)
101
+
102
+
103
+ @njit
104
+ def array_transpose_axes_copy(arr, axes):
105
+ return arr.transpose(axes).copy()
106
+
107
+
108
+ @njit
109
+ def transpose_issue_4708(m, n):
110
+ r1 = np.reshape(np.arange(m * n * 3), (m, 3, n))
111
+ r2 = np.reshape(np.arange(n * 3), (n, 3))
112
+ r_dif = (r1 - r2.T).T
113
+ r_dif = np.transpose(r_dif, (2, 0, 1))
114
+ z = r_dif + 1
115
+ return z
116
+
117
+
118
+ def squeeze_array(a):
119
+ return a.squeeze()
120
+
121
+
122
+ def expand_dims(a, axis):
123
+ return np.expand_dims(a, axis)
124
+
125
+
126
+ def atleast_1d(*args):
127
+ return np.atleast_1d(*args)
128
+
129
+
130
+ def atleast_2d(*args):
131
+ return np.atleast_2d(*args)
132
+
133
+
134
+ def atleast_3d(*args):
135
+ return np.atleast_3d(*args)
136
+
137
+
138
+ def as_strided1(a):
139
+ # as_strided() with implicit shape
140
+ strides = (a.strides[0] // 2,) + a.strides[1:]
141
+ return np.lib.stride_tricks.as_strided(a, strides=strides)
142
+
143
+
144
+ def as_strided2(a):
145
+ # Rolling window example as in https://github.com/numba/numba/issues/1884
146
+ window = 3
147
+ shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
148
+ strides = a.strides + (a.strides[-1],)
149
+ return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
150
+
151
+
152
+ @njit
153
+ def sliding_window_view(x, window_shape, axis=None):
154
+ return np.lib.stride_tricks.sliding_window_view(x, window_shape, axis=axis)
155
+
156
+
157
+ def bad_index(arr, arr2d):
158
+ x = arr.x,
159
+ y = arr.y
160
+ # note that `x` is a tuple, which causes a new axis to be created.
161
+ arr2d[x, y] = 1.0
162
+
163
+
164
+ def bad_float_index(arr):
165
+ # 2D index required for this function because 1D index
166
+ # fails typing
167
+ return arr[1, 2.0]
168
+
169
+
170
+ def numpy_fill_diagonal(arr, val, wrap=False):
171
+ return np.fill_diagonal(arr, val, wrap)
172
+
173
+
174
+ def numpy_shape(arr):
175
+ return np.shape(arr)
176
+
177
+ def numpy_size(arr):
178
+ return np.size(arr)
179
+
180
+
181
+ def numpy_flatnonzero(a):
182
+ return np.flatnonzero(a)
183
+
184
+
185
+ def numpy_argwhere(a):
186
+ return np.argwhere(a)
187
+
188
+ def numpy_resize(a, new_shape):
189
+ return np.resize(a, new_shape)
190
+
191
+
192
+ class TestArrayManipulation(MemoryLeakMixin, TestCase):
193
+ """
194
+ Check shape-changing operations on arrays.
195
+ """
196
+ def test_array_reshape(self):
197
+ pyfuncs_to_use = [array_reshape, numpy_array_reshape]
198
+
199
+ def generic_run(pyfunc, arr, shape):
200
+ return pyfunc(arr, shape)
201
+
202
+ @from_generic(pyfuncs_to_use)
203
+ def check(pyfunc, arr, shape):
204
+ expected = pyfunc.py_func(arr, shape)
205
+ self.memory_leak_setup()
206
+ got = generic_run(pyfunc, arr, shape)
207
+ self.assertPreciseEqual(got, expected)
208
+ del got
209
+ self.memory_leak_teardown()
210
+
211
+ @from_generic(pyfuncs_to_use)
212
+ def check_only_shape(pyfunc, arr, shape, expected_shape):
213
+ # Only check Numba result to avoid Numpy bugs
214
+ self.memory_leak_setup()
215
+ got = generic_run(pyfunc, arr, shape)
216
+ self.assertEqual(got.shape, expected_shape)
217
+ self.assertEqual(got.size, arr.size)
218
+ del got
219
+ self.memory_leak_teardown()
220
+
221
+ @from_generic(pyfuncs_to_use)
222
+ def check_err_shape(pyfunc, arr, shape):
223
+ with self.assertRaises(NotImplementedError) as raises:
224
+ generic_run(pyfunc, arr, shape)
225
+ self.assertEqual(str(raises.exception),
226
+ "incompatible shape for array")
227
+
228
+ @from_generic(pyfuncs_to_use)
229
+ def check_err_size(pyfunc, arr, shape):
230
+ with self.assertRaises(ValueError) as raises:
231
+ generic_run(pyfunc, arr, shape)
232
+ self.assertEqual(str(raises.exception),
233
+ "total size of new array must be unchanged")
234
+
235
+ @from_generic(pyfuncs_to_use)
236
+ def check_err_multiple_negative(pyfunc, arr, shape):
237
+ with self.assertRaises(ValueError) as raises:
238
+ generic_run(pyfunc, arr, shape)
239
+ self.assertEqual(str(raises.exception),
240
+ "multiple negative shape values")
241
+
242
+
243
+ # C-contiguous
244
+ arr = np.arange(24)
245
+ check(arr, (24,))
246
+ check(arr, (4, 6))
247
+ check(arr, (8, 3))
248
+ check(arr, (8, 1, 3))
249
+ check(arr, (1, 8, 1, 1, 3, 1))
250
+ arr = np.arange(24).reshape((2, 3, 4))
251
+ check(arr, (24,))
252
+ check(arr, (4, 6))
253
+ check(arr, (8, 3))
254
+ check(arr, (8, 1, 3))
255
+ check(arr, (1, 8, 1, 1, 3, 1))
256
+ check_err_size(arr, ())
257
+ check_err_size(arr, (25,))
258
+ check_err_size(arr, (8, 4))
259
+ arr = np.arange(24).reshape((1, 8, 1, 1, 3, 1))
260
+ check(arr, (24,))
261
+ check(arr, (4, 6))
262
+ check(arr, (8, 3))
263
+ check(arr, (8, 1, 3))
264
+
265
+ # F-contiguous
266
+ arr = np.arange(24).reshape((2, 3, 4)).T
267
+ check(arr, (4, 3, 2))
268
+ check(arr, (1, 4, 1, 3, 1, 2, 1))
269
+ check_err_shape(arr, (2, 3, 4))
270
+ check_err_shape(arr, (6, 4))
271
+ check_err_shape(arr, (2, 12))
272
+
273
+ # Test negative shape value
274
+ arr = np.arange(25).reshape(5,5)
275
+ check(arr, -1)
276
+ check(arr, (-1,))
277
+ check(arr, (-1, 5))
278
+ check(arr, (5, -1, 5))
279
+ check(arr, (5, 5, -1))
280
+ check_err_size(arr, (-1, 4))
281
+ check_err_multiple_negative(arr, (-1, -2, 5, 5))
282
+ check_err_multiple_negative(arr, (5, 5, -1, -1))
283
+
284
+ # 0-sized arrays
285
+ def check_empty(arr):
286
+ check(arr, 0)
287
+ check(arr, (0,))
288
+ check(arr, (1, 0, 2))
289
+ check(arr, (0, 55, 1, 0, 2))
290
+ # -1 is buggy in Numpy with 0-sized arrays
291
+ check_only_shape(arr, -1, (0,))
292
+ check_only_shape(arr, (-1,), (0,))
293
+ check_only_shape(arr, (0, -1), (0, 0))
294
+ check_only_shape(arr, (4, -1), (4, 0))
295
+ check_only_shape(arr, (-1, 0, 4), (0, 0, 4))
296
+ check_err_size(arr, ())
297
+ check_err_size(arr, 1)
298
+ check_err_size(arr, (1, 2))
299
+
300
+ arr = np.array([])
301
+ check_empty(arr)
302
+ check_empty(arr.reshape((3, 2, 0)))
303
+
304
+ # Exceptions leak references
305
+ self.disable_leak_check()
306
+
307
+ def test_array_transpose_axes(self):
308
+ pyfuncs_to_use = [numpy_transpose_array_axes_kwarg,
309
+ numpy_transpose_array_axes_kwarg_copy,
310
+ array_transpose_axes,
311
+ array_transpose_axes_copy]
312
+
313
+ @from_generic(pyfuncs_to_use)
314
+ def check(pyfunc, arr, axes):
315
+ expected = pyfunc.py_func(arr, axes)
316
+ got = pyfunc(arr, axes)
317
+ self.assertPreciseEqual(got, expected)
318
+ self.assertEqual(got.flags.f_contiguous,
319
+ expected.flags.f_contiguous)
320
+ self.assertEqual(got.flags.c_contiguous,
321
+ expected.flags.c_contiguous)
322
+
323
+ @from_generic(pyfuncs_to_use)
324
+ def check_err_axis_repeated(pyfunc, arr, axes):
325
+ with self.assertRaises(ValueError) as raises:
326
+ pyfunc(arr, axes)
327
+ self.assertEqual(str(raises.exception),
328
+ "repeated axis in transpose")
329
+
330
+ @from_generic(pyfuncs_to_use)
331
+ def check_err_axis_oob(pyfunc, arr, axes):
332
+ with self.assertRaises(ValueError) as raises:
333
+ pyfunc(arr, axes)
334
+ self.assertEqual(str(raises.exception),
335
+ "axis is out of bounds for array of given dimension")
336
+
337
+ @from_generic(pyfuncs_to_use)
338
+ def check_err_invalid_args(pyfunc, arr, axes):
339
+ with self.assertRaises((TypeError, TypingError)):
340
+ pyfunc(arr, axes)
341
+
342
+ arrs = [np.arange(24),
343
+ np.arange(24).reshape(4, 6),
344
+ np.arange(24).reshape(2, 3, 4),
345
+ np.arange(24).reshape(1, 2, 3, 4),
346
+ np.arange(64).reshape(8, 4, 2)[::3,::2,:]]
347
+
348
+ for i in range(len(arrs)):
349
+ # First check `None`, the default, which is to reverse dims
350
+ check(arrs[i], None)
351
+ # Check supplied axis permutations
352
+ for axes in permutations(tuple(range(arrs[i].ndim))):
353
+ ndim = len(axes)
354
+ neg_axes = tuple([x - ndim for x in axes])
355
+ check(arrs[i], axes)
356
+ check(arrs[i], neg_axes)
357
+
358
+ @from_generic([transpose_issue_4708])
359
+ def check_issue_4708(pyfunc, m, n):
360
+ expected = pyfunc.py_func(m, n)
361
+ got = pyfunc(m, n)
362
+ # values in arrays are equals,
363
+ # but stronger assertions not hold (layout and strides equality)
364
+ np.testing.assert_equal(got, expected)
365
+
366
+ check_issue_4708(3, 2)
367
+ check_issue_4708(2, 3)
368
+ check_issue_4708(5, 4)
369
+
370
+ # Exceptions leak references
371
+ self.disable_leak_check()
372
+
373
+ check_err_invalid_args(arrs[1], "foo")
374
+ check_err_invalid_args(arrs[1], ("foo",))
375
+ check_err_invalid_args(arrs[1], 5.3)
376
+ check_err_invalid_args(arrs[2], (1.2, 5))
377
+
378
+ check_err_axis_repeated(arrs[1], (0, 0))
379
+ check_err_axis_repeated(arrs[2], (2, 0, 0))
380
+ check_err_axis_repeated(arrs[3], (3, 2, 1, 1))
381
+
382
+ check_err_axis_oob(arrs[0], (1,))
383
+ check_err_axis_oob(arrs[0], (-2,))
384
+ check_err_axis_oob(arrs[1], (0, 2))
385
+ check_err_axis_oob(arrs[1], (-3, 2))
386
+ check_err_axis_oob(arrs[1], (0, -3))
387
+ check_err_axis_oob(arrs[2], (3, 1, 2))
388
+ check_err_axis_oob(arrs[2], (-4, 1, 2))
389
+ check_err_axis_oob(arrs[3], (3, 1, 2, 5))
390
+ check_err_axis_oob(arrs[3], (3, 1, 2, -5))
391
+
392
+ with self.assertRaises(TypingError) as e:
393
+ jit(nopython=True)(numpy_transpose_array)((np.array([0, 1]),))
394
+ self.assertIn("np.transpose does not accept tuples",
395
+ str(e.exception))
396
+
397
+ def test_numpy_resize_basic(self):
398
+ pyfunc = numpy_resize
399
+ cfunc = njit(pyfunc)
400
+ def inputs():
401
+ # Taken from https://github.com/numpy/numpy/blob/f0b2fca91a1f5f50ff696895072f6fe9e69c1466/numpy/core/tests/test_numeric.py#L24-L64 noqa: E501
402
+ yield np.array([[1, 2], [3, 4]]), (2, 4)
403
+ yield np.array([[1, 2], [3, 4]]), (4, 2)
404
+ yield np.array([[1, 2], [3, 4]]), (4, 3)
405
+ yield np.array([[1, 2], [3, 4]]), (0,)
406
+ yield np.array([[1, 2], [3, 4]]), (0, 2)
407
+ yield np.array([[1, 2], [3, 4]]), (2, 0)
408
+ yield np.zeros(0, dtype = float), (2, 1)
409
+ # other
410
+ yield np.array([[1, 2], [3, 4]]), (4,)
411
+ yield np.array([[1, 2], [3, 4]]), 4
412
+ yield np.zeros((1, 3), dtype = int), (2, 1)
413
+ yield np.array([], dtype = float), (4, 2)
414
+ yield [0, 1, 2, 3], (2, 3)
415
+ yield 4, (2, 3)
416
+
417
+ for a, new_shape in inputs():
418
+ self.assertPreciseEqual(pyfunc(a, new_shape), cfunc(a, new_shape))
419
+
420
+ def test_numpy_resize_exception(self):
421
+ # Exceptions leak references
422
+ self.disable_leak_check()
423
+
424
+ cfunc = njit(numpy_resize)
425
+
426
+ with self.assertRaises(TypingError) as raises:
427
+ cfunc("abc", (2, 3))
428
+ self.assertIn(('The argument "a" must be array-like'),
429
+ str(raises.exception))
430
+
431
+ with self.assertRaises(TypingError) as raises:
432
+ cfunc(np.array([[0,1],[2,3]]), "abc")
433
+ self.assertIn(('The argument "new_shape" must be an integer or '
434
+ 'a tuple of integers'),
435
+ str(raises.exception))
436
+
437
+ with self.assertRaises(ValueError) as raises:
438
+ cfunc(np.array([[0,1],[2,3]]), (-2, 3))
439
+ self.assertIn(('All elements of `new_shape` must be non-negative'),
440
+ str(raises.exception))
441
+
442
+ with self.assertRaises(ValueError) as raises:
443
+ cfunc(np.array([[0,1],[2,3]]), -4)
444
+ self.assertIn(('All elements of `new_shape` must be non-negative'),
445
+ str(raises.exception))
446
+
447
+ def test_expand_dims(self):
448
+ pyfunc = expand_dims
449
+ cfunc = njit(pyfunc)
450
+
451
+ def check(arr, axis):
452
+ expected = pyfunc(arr, axis)
453
+ self.memory_leak_setup()
454
+ got = cfunc(arr, axis)
455
+ self.assertPreciseEqual(got, expected)
456
+ del got
457
+ self.memory_leak_teardown()
458
+
459
+ def check_all_axes(arr):
460
+ for axis in range(-arr.ndim - 1, arr.ndim + 1):
461
+ check(arr, axis)
462
+
463
+ # 1d
464
+ arr = np.arange(5)
465
+ check_all_axes(arr)
466
+ # 3d (C, F, A)
467
+ arr = np.arange(24).reshape((2, 3, 4))
468
+ check_all_axes(arr)
469
+ check_all_axes(arr.T)
470
+ check_all_axes(arr[::-1])
471
+ # 0d
472
+ arr = np.array(42)
473
+ check_all_axes(arr)
474
+
475
+ def test_expand_dims_exceptions(self):
476
+ pyfunc = expand_dims
477
+ cfunc = jit(nopython=True)(pyfunc)
478
+ arr = np.arange(5)
479
+
480
+ with self.assertTypingError() as raises:
481
+ cfunc('hello', 3)
482
+ self.assertIn('First argument "a" must be an array', str(raises.exception))
483
+
484
+ with self.assertTypingError() as raises:
485
+ cfunc(arr, 'hello')
486
+ self.assertIn('Argument "axis" must be an integer', str(raises.exception))
487
+
488
+
489
+ def check_atleast_nd(self, pyfunc, cfunc):
490
+ def check_result(got, expected):
491
+ # We would like to check the result has the same contiguity,
492
+ # but we can't rely on the "flags" attribute when there are
493
+ # 1-sized dimensions.
494
+ self.assertStridesEqual(got, expected)
495
+ self.assertPreciseEqual(got.flatten(), expected.flatten())
496
+
497
+ def check_single(arg):
498
+ check_result(cfunc(arg), pyfunc(arg))
499
+
500
+ def check_tuple(*args):
501
+ expected_tuple = pyfunc(*args)
502
+ got_tuple = cfunc(*args)
503
+ self.assertEqual(len(got_tuple), len(expected_tuple))
504
+ for got, expected in zip(got_tuple, expected_tuple):
505
+ check_result(got, expected)
506
+
507
+ # 0d
508
+ a1 = np.array(42)
509
+ a2 = np.array(5j)
510
+ check_single(a1)
511
+ check_tuple(a1, a2)
512
+ # 1d
513
+ b1 = np.arange(5)
514
+ b2 = np.arange(6) + 1j
515
+ b3 = b1[::-1]
516
+ check_single(b1)
517
+ check_tuple(b1, b2, b3)
518
+ # 2d
519
+ c1 = np.arange(6).reshape((2, 3))
520
+ c2 = c1.T
521
+ c3 = c1[::-1]
522
+ check_single(c1)
523
+ check_tuple(c1, c2, c3)
524
+ # 3d
525
+ d1 = np.arange(24).reshape((2, 3, 4))
526
+ d2 = d1.T
527
+ d3 = d1[::-1]
528
+ check_single(d1)
529
+ check_tuple(d1, d2, d3)
530
+ # 4d
531
+ e = np.arange(16).reshape((2, 2, 2, 2))
532
+ check_single(e)
533
+ # mixed dimensions
534
+ check_tuple(a1, b2, c3, d2)
535
+
536
+ def test_atleast_1d(self):
537
+ pyfunc = atleast_1d
538
+ cfunc = jit(nopython=True)(pyfunc)
539
+ self.check_atleast_nd(pyfunc, cfunc)
540
+
541
+ def test_atleast_2d(self):
542
+ pyfunc = atleast_2d
543
+ cfunc = jit(nopython=True)(pyfunc)
544
+ self.check_atleast_nd(pyfunc, cfunc)
545
+
546
+ def test_atleast_3d(self):
547
+ pyfunc = atleast_3d
548
+ cfunc = jit(nopython=True)(pyfunc)
549
+ self.check_atleast_nd(pyfunc, cfunc)
550
+
551
+ def check_as_strided(self, pyfunc):
552
+ cfunc = njit(pyfunc)
553
+
554
+ def check(arr):
555
+ expected = pyfunc(arr)
556
+ got = cfunc(arr)
557
+ self.assertPreciseEqual(got, expected)
558
+
559
+ arr = np.arange(24)
560
+ check(arr)
561
+ check(arr.reshape((6, 4)))
562
+ check(arr.reshape((4, 1, 6)))
563
+
564
+ def test_as_strided(self):
565
+ self.check_as_strided(as_strided1)
566
+ self.check_as_strided(as_strided2)
567
+
568
+ def test_as_strided_stride_none(self):
569
+
570
+ @jit
571
+ def foo():
572
+ arr = np.arange(24).reshape((6, 4))
573
+ return np.lib.stride_tricks.as_strided(arr, strides=None)
574
+
575
+ with self.assertRaises(errors.TypingError) as raises:
576
+ foo()
577
+
578
+ msg = "strides argument cannot be None"
579
+ self.assertIn(msg, str(raises.exception))
580
+
581
+ def test_sliding_window_view(self):
582
+ def check(arr, window_shape, axis):
583
+ # Our version is always writeable (NumPy default is False).
584
+ expected = np.lib.stride_tricks.sliding_window_view(
585
+ arr, window_shape, axis, writeable=True
586
+ )
587
+ got = sliding_window_view(arr, window_shape, axis)
588
+ self.assertPreciseEqual(got, expected)
589
+
590
+ # 1d array, different ways of specifying the axis.
591
+ arr1 = np.arange(24)
592
+ for axis in [None, 0, -1, (0,)]:
593
+ with self.subTest(f"1d array, axis={axis}"):
594
+ check(arr1, 5, axis)
595
+
596
+ # 2d array, 1d window.
597
+ arr2 = np.arange(200).reshape(10, 20)
598
+ for axis in [0, -1]:
599
+ with self.subTest(f"2d array, axis={axis}"):
600
+ check(arr2, 5, axis)
601
+
602
+ # 2d array, 2d window.
603
+ for axis in [None, (0, 1), (1, 0), (1, -2)]:
604
+ with self.subTest(f"2d array, axis={axis}"):
605
+ check(arr2, (5, 8), axis)
606
+
607
+ # 4d array, 2d window.
608
+ arr4 = np.arange(200).reshape(4, 5, 5, 2)
609
+ for axis in [(1, 2), (-2, -3)]:
610
+ with self.subTest(f"4d array, axis={axis}"):
611
+ check(arr4, (3, 2), axis)
612
+
613
+ # Repeated axis.
614
+ with self.subTest("2d array, repeated axes"):
615
+ check(arr2, (5, 3, 3), (0, 1, 0))
616
+
617
+ def test_sliding_window_view_errors(self):
618
+ def _raises(msg, *args):
619
+ with self.assertRaises(ValueError) as raises:
620
+ sliding_window_view(*args)
621
+ self.assertIn(msg, str(raises.exception))
622
+
623
+ def _typing_error(msg, *args):
624
+ with self.assertRaises(errors.TypingError) as raises:
625
+ sliding_window_view(*args)
626
+ self.assertIn(msg, str(raises.exception))
627
+
628
+ # Exceptions leak references
629
+ self.disable_leak_check()
630
+
631
+ arr1 = np.arange(24)
632
+ arr2 = np.arange(200).reshape(10, 20)
633
+
634
+ # Window shape cannot be larger than dimension or negative.
635
+ with self.subTest("1d window shape too large"):
636
+ _raises("window_shape cannot be larger", arr1, 25, None)
637
+ with self.subTest("2d window shape too large"):
638
+ _raises("window_shape cannot be larger", arr2, (4, 21), None)
639
+ with self.subTest("1d window negative size"):
640
+ _raises("`window_shape` cannot contain negative", arr1, -1, None)
641
+ with self.subTest("2d window with a negative size"):
642
+ _raises("`window_shape` cannot contain negative", arr2, (4, -3), None)
643
+
644
+ # window_shape and axis parameters must be compatible.
645
+ with self.subTest("1d array, 2d window shape"):
646
+ _raises("matching length window_shape and axis", arr1, (10, 2), None)
647
+ with self.subTest("2d window shape, only one axis given"):
648
+ _raises("matching length window_shape and axis", arr2, (10, 2), 1)
649
+ with self.subTest("1d window shape, 2 axes given"):
650
+ _raises("matching length window_shape and axis", arr1, 5, (0, 0))
651
+
652
+ # Axis values out of bounds.
653
+ with self.subTest("1d array, second axis"):
654
+ _raises("Argument axis out of bounds", arr1, 4, 1)
655
+ with self.subTest("1d array, axis -2"):
656
+ _raises("Argument axis out of bounds", arr1, 4, -2)
657
+ with self.subTest("2d array, fourth axis"):
658
+ _raises("Argument axis out of bounds", arr2, (4, 4), (0, 3))
659
+ with self.subTest("2d array, axis -3"):
660
+ _raises("Argument axis out of bounds", arr2, (4, 4), (0, -3))
661
+
662
+ # Useful messages for unsupported types.
663
+ with self.subTest("window_shape=None"):
664
+ _typing_error(
665
+ "window_shape must be an integer or tuple of integer", arr1, None
666
+ )
667
+ with self.subTest("window_shape=float"):
668
+ _typing_error(
669
+ "window_shape must be an integer or tuple of integer", arr1, 3.1
670
+ )
671
+ with self.subTest("window_shape=tuple(float)"):
672
+ _typing_error(
673
+ "window_shape must be an integer or tuple of integer", arr1, (3.1,)
674
+ )
675
+ with self.subTest("axis=float"):
676
+ _typing_error(
677
+ "axis must be None, an integer or tuple of integer", arr1, 4, 3.1
678
+ )
679
+ with self.subTest("axis=tuple(float)"):
680
+ _typing_error(
681
+ "axis must be None, an integer or tuple of integer", arr1, 4, (3.1,)
682
+ )
683
+
684
+
685
+ def test_flatten_array(self, flags=enable_pyobj_flags, layout='C'):
686
+ a = np.arange(9).reshape(3, 3)
687
+ if layout == 'F':
688
+ a = a.T
689
+
690
+ pyfunc = flatten_array
691
+ arraytype1 = typeof(a)
692
+ if layout == 'A':
693
+ # Force A layout
694
+ arraytype1 = arraytype1.copy(layout='A')
695
+
696
+ self.assertEqual(arraytype1.layout, layout)
697
+ cfunc = jit((arraytype1,), **flags)(pyfunc)
698
+
699
+ expected = pyfunc(a)
700
+ got = cfunc(a)
701
+ np.testing.assert_equal(expected, got)
702
+
703
+ def test_flatten_array_npm(self):
704
+ self.test_flatten_array(flags=no_pyobj_flags)
705
+ self.test_flatten_array(flags=no_pyobj_flags, layout='F')
706
+ self.test_flatten_array(flags=no_pyobj_flags, layout='A')
707
+
708
+ def test_ravel_array(self, flags=enable_pyobj_flags):
709
+ def generic_check(pyfunc, a, assume_layout):
710
+ # compile
711
+ arraytype1 = typeof(a)
712
+ self.assertEqual(arraytype1.layout, assume_layout)
713
+ cfunc = jit((arraytype1,), **flags)(pyfunc)
714
+
715
+ expected = pyfunc(a)
716
+ got = cfunc(a)
717
+ # Check result matches
718
+ np.testing.assert_equal(expected, got)
719
+ # Check copying behavior
720
+ py_copied = (a.ctypes.data != expected.ctypes.data)
721
+ nb_copied = (a.ctypes.data != got.ctypes.data)
722
+ self.assertEqual(py_copied, assume_layout != 'C')
723
+ self.assertEqual(py_copied, nb_copied)
724
+
725
+ check_method = partial(generic_check, ravel_array)
726
+ check_function = partial(generic_check, numpy_ravel_array)
727
+
728
+ def check(*args, **kwargs):
729
+ check_method(*args, **kwargs)
730
+ check_function(*args, **kwargs)
731
+
732
+ # Check 2D
733
+ check(np.arange(9).reshape(3, 3), assume_layout='C')
734
+ check(np.arange(9).reshape(3, 3, order='F'), assume_layout='F')
735
+ check(np.arange(18).reshape(3, 3, 2)[:, :, 0], assume_layout='A')
736
+
737
+ # Check 3D
738
+ check(np.arange(18).reshape(2, 3, 3), assume_layout='C')
739
+ check(np.arange(18).reshape(2, 3, 3, order='F'), assume_layout='F')
740
+ check(np.arange(36).reshape(2, 3, 3, 2)[:, :, :, 0], assume_layout='A')
741
+
742
+ def test_ravel_array_size(self, flags=enable_pyobj_flags):
743
+ a = np.arange(9).reshape(3, 3)
744
+
745
+ pyfunc = ravel_array_size
746
+ arraytype1 = typeof(a)
747
+ cfunc = jit((arraytype1,), **flags)(pyfunc)
748
+
749
+ expected = pyfunc(a)
750
+ got = cfunc(a)
751
+ np.testing.assert_equal(expected, got)
752
+
753
+ def test_ravel_array_npm(self):
754
+ self.test_ravel_array(flags=no_pyobj_flags)
755
+
756
+ def test_ravel_array_size_npm(self):
757
+ self.test_ravel_array_size(flags=no_pyobj_flags)
758
+
759
+ def test_transpose_array(self, flags=enable_pyobj_flags):
760
+ @from_generic([transpose_array, numpy_transpose_array])
761
+ def check(pyfunc):
762
+ a = np.arange(9).reshape(3, 3)
763
+
764
+ arraytype1 = typeof(a)
765
+ cfunc = jit((arraytype1,), **flags)(pyfunc)
766
+
767
+ expected = pyfunc(a)
768
+ got = cfunc(a)
769
+ np.testing.assert_equal(expected, got)
770
+
771
+ check()
772
+
773
+ def test_transpose_array_npm(self):
774
+ self.test_transpose_array(flags=no_pyobj_flags)
775
+
776
+ def test_squeeze_array(self, flags=enable_pyobj_flags):
777
+ a = np.arange(2 * 1 * 3 * 1 * 4).reshape(2, 1, 3, 1, 4)
778
+
779
+ pyfunc = squeeze_array
780
+ arraytype1 = typeof(a)
781
+ cfunc = jit((arraytype1,), **flags)(pyfunc)
782
+
783
+ expected = pyfunc(a)
784
+ got = cfunc(a)
785
+ np.testing.assert_equal(expected, got)
786
+
787
+ def test_squeeze_array_npm(self):
788
+ with self.assertRaises(errors.TypingError) as raises:
789
+ self.test_squeeze_array(flags=no_pyobj_flags)
790
+
791
+ self.assertIn("squeeze", str(raises.exception))
792
+
793
+ def test_add_axis(self):
794
+ @njit
795
+ def np_new_axis_getitem(a, idx):
796
+ return a[idx]
797
+
798
+ @njit
799
+ def np_new_axis_setitem(a, idx, item):
800
+ a[idx] = item
801
+ return a
802
+
803
+ a = np.arange(4 * 5 * 6 * 7).reshape((4, 5, 6, 7))
804
+ idx_cases = [
805
+ (slice(None), np.newaxis),
806
+ (np.newaxis, slice(None)),
807
+ (slice(1), np.newaxis, 1),
808
+ (np.newaxis, 2, slice(None)),
809
+ (slice(1), Ellipsis, np.newaxis, 1),
810
+ (1, np.newaxis, Ellipsis),
811
+ (np.newaxis, slice(1), np.newaxis, 1),
812
+ (1, Ellipsis, None, np.newaxis),
813
+ (np.newaxis, slice(1), Ellipsis, np.newaxis, 1),
814
+ (1, np.newaxis, np.newaxis, Ellipsis),
815
+ (np.newaxis, 1, np.newaxis, Ellipsis),
816
+ (slice(3), 1, np.newaxis, None),
817
+ (np.newaxis, 1, Ellipsis, None),
818
+ ]
819
+ pyfunc_getitem = np_new_axis_getitem.py_func
820
+ cfunc_getitem = np_new_axis_getitem
821
+
822
+ pyfunc_setitem = np_new_axis_setitem.py_func
823
+ cfunc_setitem = np_new_axis_setitem
824
+
825
+ for idx in idx_cases:
826
+ expected = pyfunc_getitem(a, idx)
827
+ got = cfunc_getitem(a, idx)
828
+ np.testing.assert_equal(expected, got)
829
+
830
+ a_empty = np.zeros_like(a)
831
+ item = a[idx]
832
+
833
+ expected = pyfunc_setitem(a_empty.copy(), idx, item)
834
+ got = cfunc_setitem(a_empty.copy(), idx, item)
835
+ np.testing.assert_equal(expected, got)
836
+
837
+ def test_bad_index_npm(self):
838
+ with self.assertTypingError() as raises:
839
+ arraytype1 = from_dtype(np.dtype([('x', np.int32),
840
+ ('y', np.int32)]))
841
+ arraytype2 = types.Array(types.int32, 2, 'C')
842
+ njit((arraytype1, arraytype2))(bad_index)
843
+ self.assertIn('Unsupported array index type', str(raises.exception))
844
+
845
+ def test_bad_float_index_npm(self):
846
+ with self.assertTypingError() as raises:
847
+ njit((types.Array(types.float64, 2, 'C'),))(bad_float_index)
848
+ self.assertIn('Unsupported array index type float64',
849
+ str(raises.exception))
850
+
851
+ def test_fill_diagonal_basic(self):
852
+ pyfunc = numpy_fill_diagonal
853
+ cfunc = jit(nopython=True)(pyfunc)
854
+
855
+ def _shape_variations(n):
856
+ # square
857
+ yield (n, n)
858
+ # tall and thin
859
+ yield (2 * n, n)
860
+ # short and fat
861
+ yield (n, 2 * n)
862
+ # a bit taller than wide; odd numbers of rows and cols
863
+ yield ((2 * n + 1), (2 * n - 1))
864
+ # 4d, all dimensions same
865
+ yield (n, n, n, n)
866
+ # weird edge case
867
+ yield (1, 1, 1)
868
+
869
+ def _val_variations():
870
+ yield 1
871
+ yield 3.142
872
+ yield np.nan
873
+ yield -np.inf
874
+ yield True
875
+ yield np.arange(4)
876
+ yield (4,)
877
+ yield [8, 9]
878
+ yield np.arange(54).reshape(9, 3, 2, 1) # contiguous C
879
+ yield np.asfortranarray(np.arange(9).reshape(3, 3)) # contiguous F
880
+ yield np.arange(9).reshape(3, 3)[::-1] # non-contiguous
881
+
882
+ # contiguous arrays
883
+ def _multi_dimensional_array_variations(n):
884
+ for shape in _shape_variations(n):
885
+ yield np.zeros(shape, dtype=np.float64)
886
+ yield np.asfortranarray(np.ones(shape, dtype=np.float64))
887
+
888
+ # non-contiguous arrays
889
+ def _multi_dimensional_array_variations_strided(n):
890
+ for shape in _shape_variations(n):
891
+ tmp = np.zeros(tuple([x * 2 for x in shape]), dtype=np.float64)
892
+ slicer = tuple(slice(0, x * 2, 2) for x in shape)
893
+ yield tmp[slicer]
894
+
895
+ def _check_fill_diagonal(arr, val):
896
+ for wrap in None, True, False:
897
+ a = arr.copy()
898
+ b = arr.copy()
899
+
900
+ if wrap is None:
901
+ params = {}
902
+ else:
903
+ params = {'wrap': wrap}
904
+
905
+ pyfunc(a, val, **params)
906
+ cfunc(b, val, **params)
907
+ self.assertPreciseEqual(a, b)
908
+
909
+ for arr in _multi_dimensional_array_variations(3):
910
+ for val in _val_variations():
911
+ _check_fill_diagonal(arr, val)
912
+
913
+ for arr in _multi_dimensional_array_variations_strided(3):
914
+ for val in _val_variations():
915
+ _check_fill_diagonal(arr, val)
916
+
917
+ # non-numeric input arrays
918
+ arr = np.array([True] * 9).reshape(3, 3)
919
+ _check_fill_diagonal(arr, False)
920
+ _check_fill_diagonal(arr, [False, True, False])
921
+ _check_fill_diagonal(arr, np.array([True, False, True]))
922
+
923
+ def test_fill_diagonal_exception_cases(self):
924
+ pyfunc = numpy_fill_diagonal
925
+ cfunc = jit(nopython=True)(pyfunc)
926
+ val = 1
927
+
928
+ # Exceptions leak references
929
+ self.disable_leak_check()
930
+
931
+ # first argument unsupported number of dimensions
932
+ for a in np.array([]), np.ones(5):
933
+ with self.assertRaises(TypingError) as raises:
934
+ cfunc(a, val)
935
+ assert "The first argument must be at least 2-D" in str(raises.exception)
936
+
937
+ # multi-dimensional input where dimensions are not all equal
938
+ with self.assertRaises(ValueError) as raises:
939
+ a = np.zeros((3, 3, 4))
940
+ cfunc(a, val)
941
+ self.assertEqual("All dimensions of input must be of equal length", str(raises.exception))
942
+
943
+ # cases where val has incompatible type / value
944
+ def _assert_raises(arr, val):
945
+ with self.assertRaises(ValueError) as raises:
946
+ cfunc(arr, val)
947
+ self.assertEqual("Unable to safely conform val to a.dtype", str(raises.exception))
948
+
949
+ arr = np.zeros((3, 3), dtype=np.int32)
950
+ val = np.nan
951
+ _assert_raises(arr, val)
952
+
953
+ val = [3.3, np.inf]
954
+ _assert_raises(arr, val)
955
+
956
+ val = np.array([1, 2, 1e10], dtype=np.int64)
957
+ _assert_raises(arr, val)
958
+
959
+ arr = np.zeros((3, 3), dtype=np.float32)
960
+ val = [1.4, 2.6, -1e100]
961
+ _assert_raises(arr, val)
962
+
963
+ val = 1.1e100
964
+ _assert_raises(arr, val)
965
+
966
+ val = np.array([-1e100])
967
+ _assert_raises(arr, val)
968
+
969
+ def test_broadcast_to(self):
970
+ pyfunc = numpy_broadcast_to
971
+ cfunc = jit(nopython=True)(pyfunc)
972
+
973
+ # Tests taken from
974
+ # https://github.com/numpy/numpy/blob/75f852edf94a7293e7982ad516bee314d7187c2d/numpy/lib/tests/test_stride_tricks.py#L234-L257 # noqa: E501
975
+ data = [
976
+ [np.array(0), (0,)],
977
+ [np.array(0), (1,)],
978
+ [np.array(0), (3,)],
979
+ [np.ones(1), (1,)],
980
+ [np.ones(1), (2,)],
981
+ [np.ones(1), (1, 2, 3)],
982
+ [np.arange(3), (3,)],
983
+ [np.arange(3), (1, 3)],
984
+ [np.arange(3), (2, 3)],
985
+ # test if shape is not a tuple
986
+ [np.ones(0), 0],
987
+ [np.ones(1), 1],
988
+ [np.ones(1), 2],
989
+ # these cases with size 0 are strange, but they reproduce the behavior
990
+ # of broadcasting with ufuncs
991
+ [np.ones(1), (0,)],
992
+ [np.ones((1, 2)), (0, 2)],
993
+ [np.ones((2, 1)), (2, 0)],
994
+ # numpy accepts scalar values as first argument to np.broadcast_to
995
+ [2, (2, 2)],
996
+ # tuple input
997
+ [(1, 2), (2, 2)],
998
+ ]
999
+ for input_array, shape in data:
1000
+ expected = pyfunc(input_array, shape)
1001
+ got = cfunc(input_array, shape)
1002
+ self.assertPreciseEqual(got, expected)
1003
+
1004
+ def test_broadcast_to_0d_array(self):
1005
+ pyfunc = numpy_broadcast_to
1006
+ cfunc = jit(nopython=True)(pyfunc)
1007
+
1008
+ inputs = [
1009
+ np.array(123),
1010
+ 123,
1011
+ True,
1012
+ # can't do np.asarray() on the types below
1013
+ # 'hello',
1014
+ # np.timedelta64(10, 'Y'),
1015
+ # np.datetime64(10, 'Y'),
1016
+ ]
1017
+
1018
+ shape = ()
1019
+ for arr in inputs:
1020
+ expected = pyfunc(arr, shape)
1021
+ got = cfunc(arr, shape)
1022
+ self.assertPreciseEqual(expected, got)
1023
+ # ensure that np.broadcast_to returned a read-only array
1024
+ self.assertFalse(got.flags['WRITEABLE'])
1025
+
1026
+ def test_broadcast_to_raises(self):
1027
+ pyfunc = numpy_broadcast_to
1028
+ cfunc = jit(nopython=True)(pyfunc)
1029
+
1030
+ # Tests taken from
1031
+ # https://github.com/numpy/numpy/blob/75f852edf94a7293e7982ad516bee314d7187c2d/numpy/lib/tests/test_stride_tricks.py#L260-L276 # noqa: E501
1032
+ data = [
1033
+ [np.zeros((0,)), (), TypingError,
1034
+ 'Cannot broadcast a non-scalar to a scalar array'],
1035
+ [np.zeros((1,)), (), TypingError,
1036
+ 'Cannot broadcast a non-scalar to a scalar array'],
1037
+ [np.zeros((3,)), (), TypingError,
1038
+ 'Cannot broadcast a non-scalar to a scalar array'],
1039
+ [(), (), TypingError,
1040
+ 'Cannot broadcast a non-scalar to a scalar array'],
1041
+ [(123,), (), TypingError,
1042
+ 'Cannot broadcast a non-scalar to a scalar array'],
1043
+ [np.zeros((3,)), (1,), ValueError,
1044
+ 'operands could not be broadcast together with remapped shapes'],
1045
+ [np.zeros((3,)), (2,), ValueError,
1046
+ 'operands could not be broadcast together with remapped shapes'],
1047
+ [np.zeros((3,)), (4,), ValueError,
1048
+ 'operands could not be broadcast together with remapped shapes'],
1049
+ [np.zeros((1, 2)), (2, 1), ValueError,
1050
+ 'operands could not be broadcast together with remapped shapes'],
1051
+ [np.zeros((1, 1)), (1,), ValueError,
1052
+ 'input operand has more dimensions than allowed by the axis remapping'],
1053
+ [np.zeros((2, 2)), (3,), ValueError,
1054
+ 'input operand has more dimensions than allowed by the axis remapping'],
1055
+ [np.zeros((1,)), -1, ValueError,
1056
+ 'all elements of broadcast shape must be non-negative'],
1057
+ [np.zeros((1,)), (-1,), ValueError,
1058
+ 'all elements of broadcast shape must be non-negative'],
1059
+ [np.zeros((1, 2)), (-1, 2), ValueError,
1060
+ 'all elements of broadcast shape must be non-negative'],
1061
+ [np.zeros((1, 2)), (1.1, 2.2), TypingError,
1062
+ 'The second argument "shape" must be a tuple of integers'],
1063
+ ['hello', (3,), TypingError,
1064
+ 'The first argument "array" must be array-like'],
1065
+ [3, (2, 'a'), TypingError,
1066
+ 'object cannot be interpreted as an integer'],
1067
+ ]
1068
+ self.disable_leak_check()
1069
+ for arr, target_shape, err, msg in data:
1070
+ with self.assertRaises(err) as raises:
1071
+ cfunc(arr, target_shape)
1072
+ self.assertIn(msg, str(raises.exception))
1073
+
1074
+ def test_broadcast_to_corner_cases(self):
1075
+ @njit
1076
+ def _broadcast_to_1():
1077
+ return np.broadcast_to('a', (2, 3))
1078
+
1079
+ expected = _broadcast_to_1.py_func()
1080
+ got = _broadcast_to_1()
1081
+ self.assertPreciseEqual(expected, got)
1082
+
1083
+ def test_broadcast_to_change_view(self):
1084
+ pyfunc = numpy_broadcast_to
1085
+ cfunc = jit(nopython=True)(pyfunc)
1086
+ input_array = np.zeros(2, dtype=np.int32)
1087
+ shape = (2, 2)
1088
+ view = cfunc(input_array, shape)
1089
+ input_array[0] = 10
1090
+
1091
+ self.assertEqual(input_array.sum(), 10)
1092
+ self.assertEqual(view.sum(), 20)
1093
+
1094
+ def test_broadcast_to_indexing(self):
1095
+ pyfunc = numpy_broadcast_to_indexing
1096
+ cfunc = jit(nopython=True)(pyfunc)
1097
+ data = [
1098
+ [np.ones(2), (2, 2), (1,)],
1099
+ ]
1100
+ for input_array, shape, idx in data:
1101
+ expected = pyfunc(input_array, shape, idx)
1102
+ got = cfunc(input_array, shape, idx)
1103
+ self.assertPreciseEqual(got, expected)
1104
+
1105
+ def test_broadcast_to_array_attrs(self):
1106
+ # See issue #8534. This tests that broadcast array attributes have the
1107
+ # correct value when accessed.
1108
+ @njit
1109
+ def foo(arr):
1110
+ ret = np.broadcast_to(arr, (2, 3))
1111
+ return ret, ret.size, ret.shape, ret.strides
1112
+
1113
+ arr = np.arange(3)
1114
+
1115
+ expected = foo.py_func(arr)
1116
+ got = foo(arr)
1117
+ self.assertPreciseEqual(expected, got)
1118
+
1119
+ def test_broadcast_shapes(self):
1120
+ pyfunc = numpy_broadcast_shapes
1121
+ cfunc = jit(nopython=True)(pyfunc)
1122
+
1123
+ # Tests taken from
1124
+ # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L296-L334
1125
+ data = [
1126
+ # [[], ()], # cannot compute fingerprint of empty list
1127
+ [()],
1128
+ [(), ()],
1129
+ [(7,)],
1130
+ [(1, 2),],
1131
+ [(1, 1)],
1132
+ [(1, 1), (3, 4)],
1133
+ [(6, 7), (5, 6, 1), (7,), (5, 1, 7)],
1134
+ [(5, 6, 1)],
1135
+ [(1, 3), (3, 1)],
1136
+ [(1, 0), (0, 0)],
1137
+ [(0, 1), (0, 0)],
1138
+ [(1, 0), (0, 1)],
1139
+ [(1, 1), (0, 0)],
1140
+ [(1, 1), (1, 0)],
1141
+ [(1, 1), (0, 1)],
1142
+ [(), (0,)],
1143
+ [(0,), (0, 0)],
1144
+ [(0,), (0, 1)],
1145
+ [(1,), (0, 0)],
1146
+ [(), (0, 0)],
1147
+ [(1, 1), (0,)],
1148
+ [(1,), (0, 1)],
1149
+ [(1,), (1, 0)],
1150
+ [(), (1, 0)],
1151
+ [(), (0, 1)],
1152
+ [(1,), (3,)],
1153
+ [2, (3, 2)],
1154
+ ]
1155
+ for input_shape in data:
1156
+ expected = pyfunc(*input_shape)
1157
+ got = cfunc(*input_shape)
1158
+ self.assertIsInstance(got, tuple)
1159
+ self.assertPreciseEqual(expected, got)
1160
+
1161
+ def test_broadcast_shapes_raises(self):
1162
+ pyfunc = numpy_broadcast_shapes
1163
+ cfunc = jit(nopython=True)(pyfunc)
1164
+
1165
+ self.disable_leak_check()
1166
+
1167
+ # Tests taken from
1168
+ # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L337-L351
1169
+ data = [
1170
+ [(3,), (4,)],
1171
+ [(2, 3), (2,)],
1172
+ [(3,), (3,), (4,)],
1173
+ [(1, 3, 4), (2, 3, 3)],
1174
+ [(1, 2), (3, 1), (3, 2), (10, 5)],
1175
+ [2, (2, 3)],
1176
+ ]
1177
+ for input_shape in data:
1178
+ with self.assertRaises(ValueError) as raises:
1179
+ cfunc(*input_shape)
1180
+
1181
+ self.assertIn("shape mismatch: objects cannot be broadcast to a single shape",
1182
+ str(raises.exception))
1183
+
1184
+ def test_broadcast_shapes_negative_dimension(self):
1185
+ pyfunc = numpy_broadcast_shapes
1186
+ cfunc = jit(nopython=True)(pyfunc)
1187
+
1188
+ self.disable_leak_check()
1189
+ with self.assertRaises(ValueError) as raises:
1190
+ cfunc((1, 2), (2), (-2))
1191
+
1192
+ self.assertIn("negative dimensions are not allowed", str(raises.exception))
1193
+
1194
+ def test_broadcast_shapes_invalid_type(self):
1195
+ pyfunc = numpy_broadcast_shapes
1196
+ cfunc = jit(nopython=True)(pyfunc)
1197
+
1198
+ self.disable_leak_check()
1199
+
1200
+ inps = [
1201
+ ((1, 2), ('hello',)),
1202
+ (3.4,),
1203
+ ('string',),
1204
+ ((1.2, 'a')),
1205
+ (1, ((1.2, 'a'))),
1206
+ ]
1207
+
1208
+ for inp in inps:
1209
+ with self.assertRaises(TypingError) as raises:
1210
+ cfunc(*inp)
1211
+
1212
+ self.assertIn("must be either an int or tuple[int]", str(raises.exception))
1213
+
1214
+ def test_shape(self):
1215
+ pyfunc = numpy_shape
1216
+ cfunc = jit(nopython=True)(pyfunc)
1217
+
1218
+ def check(x):
1219
+ expected = pyfunc(x)
1220
+ got = cfunc(x)
1221
+ self.assertPreciseEqual(got, expected)
1222
+
1223
+ # check arrays
1224
+ for t in [(), (1,), (2, 3,), (4, 5, 6)]:
1225
+ arr = np.empty(t)
1226
+ check(arr)
1227
+
1228
+ # check some types that go via asarray
1229
+ for t in [1, False, [1,], [[1, 2,],[3, 4]], (1,), (1, 2, 3)]:
1230
+ check(arr)
1231
+
1232
+ with self.assertRaises(TypingError) as raises:
1233
+ cfunc('a')
1234
+
1235
+ self.assertIn("The argument to np.shape must be array-like",
1236
+ str(raises.exception))
1237
+
1238
+ def test_size(self):
1239
+ pyfunc = numpy_size
1240
+ cfunc = jit(nopython=True)(pyfunc)
1241
+
1242
+ def check(x):
1243
+ expected = pyfunc(x)
1244
+ got = cfunc(x)
1245
+ self.assertPreciseEqual(got, expected)
1246
+
1247
+ # check arrays
1248
+ for t in [(), (1,), (2, 3,), (4, 5, 6)]:
1249
+ arr = np.empty(t)
1250
+ check(arr)
1251
+
1252
+ # check scalar values
1253
+ for t in [1, False, 3.14, np.int8(4), np.float32(2.718)]:
1254
+ check(t)
1255
+
1256
+ with self.assertRaises(TypingError) as raises:
1257
+ cfunc('a')
1258
+
1259
+ self.assertIn("The argument to np.size must be array-like",
1260
+ str(raises.exception))
1261
+
1262
+ def test_flatnonzero_basic(self):
1263
+ pyfunc = numpy_flatnonzero
1264
+ cfunc = jit(nopython=True)(pyfunc)
1265
+
1266
+ def a_variations():
1267
+ yield np.arange(-5, 5)
1268
+ yield np.full(5, fill_value=0)
1269
+ yield np.array([])
1270
+ a = self.random.randn(100)
1271
+ a[np.abs(a) > 0.2] = 0.0
1272
+ yield a
1273
+ yield a.reshape(5, 5, 4)
1274
+ yield a.reshape(50, 2, order='F')
1275
+ yield a.reshape(25, 4)[1::2]
1276
+ yield a * 1j
1277
+
1278
+ for a in a_variations():
1279
+ expected = pyfunc(a)
1280
+ got = cfunc(a)
1281
+ self.assertPreciseEqual(expected, got)
1282
+
1283
+ def test_argwhere_basic(self):
1284
+ pyfunc = numpy_argwhere
1285
+ cfunc = jit(nopython=True)(pyfunc)
1286
+
1287
+ def a_variations():
1288
+ yield np.arange(-5, 5) > 2
1289
+ yield np.full(5, fill_value=0)
1290
+ yield np.full(5, fill_value=1)
1291
+ yield np.array([])
1292
+ yield np.array([-1.0, 0.0, 1.0])
1293
+ a = self.random.randn(100)
1294
+ yield a > 0.2
1295
+ yield a.reshape(5, 5, 4) > 0.5
1296
+ yield a.reshape(50, 2, order='F') > 0.5
1297
+ yield a.reshape(25, 4)[1::2] > 0.5
1298
+ yield a == a - 1
1299
+ yield a > -a
1300
+
1301
+ for a in a_variations():
1302
+ expected = pyfunc(a)
1303
+ got = cfunc(a)
1304
+ self.assertPreciseEqual(expected, got)
1305
+
1306
+ @staticmethod
1307
+ def array_like_variations():
1308
+ yield ((1.1, 2.2), (3.3, 4.4), (5.5, 6.6))
1309
+ yield (0.0, 1.0, 0.0, -6.0)
1310
+ yield ([0, 1], [2, 3])
1311
+ yield ()
1312
+ yield np.nan
1313
+ yield 0
1314
+ yield 1
1315
+ yield False
1316
+ yield True
1317
+ yield (True, False, True)
1318
+ yield 2 + 1j
1319
+ # the following are not array-like, but NumPy does not raise
1320
+ yield None
1321
+ yield 'a_string'
1322
+ yield ''
1323
+
1324
+
1325
+ def test_flatnonzero_array_like(self):
1326
+ pyfunc = numpy_flatnonzero
1327
+ cfunc = jit(nopython=True)(pyfunc)
1328
+
1329
+ for a in self.array_like_variations():
1330
+ expected = pyfunc(a)
1331
+ got = cfunc(a)
1332
+ self.assertPreciseEqual(expected, got)
1333
+
1334
+ def test_argwhere_array_like(self):
1335
+ pyfunc = numpy_argwhere
1336
+ cfunc = jit(nopython=True)(pyfunc)
1337
+ for a in self.array_like_variations():
1338
+ expected = pyfunc(a)
1339
+ got = cfunc(a)
1340
+ self.assertPreciseEqual(expected, got)
1341
+
1342
+ def broadcast_arrays_assert_correct_shape(self, input_shapes, expected_shape):
1343
+ # Broadcast a list of arrays with the given input shapes and check the
1344
+ # common output shape.
1345
+ pyfunc = numpy_broadcast_arrays
1346
+ cfunc = jit(nopython=True)(pyfunc)
1347
+
1348
+ inarrays = [np.zeros(s) for s in input_shapes]
1349
+ outarrays = cfunc(*inarrays)
1350
+ expected = [expected_shape] * len(inarrays)
1351
+ got = [a.shape for a in outarrays]
1352
+ self.assertPreciseEqual(expected, got)
1353
+
1354
+ def test_broadcast_arrays_same_input_shapes(self):
1355
+ # Tests taken from
1356
+ # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L83-L107 # noqa: E501
1357
+ # Check that the final shape is just the input shape.
1358
+ pyfunc = numpy_broadcast_arrays
1359
+ cfunc = jit(nopython=True)(pyfunc)
1360
+
1361
+ data = [
1362
+ # (),
1363
+ (1,),
1364
+ (3,),
1365
+ (0, 1),
1366
+ (0, 3),
1367
+ (1, 0),
1368
+ (3, 0),
1369
+ (1, 3),
1370
+ (3, 1),
1371
+ (3, 3),
1372
+ ]
1373
+ for shape in data:
1374
+ input_shapes = [shape]
1375
+ # Single input.
1376
+ self.broadcast_arrays_assert_correct_shape(input_shapes, shape)
1377
+ # Double input.
1378
+ input_shapes2 = [shape, shape]
1379
+ self.broadcast_arrays_assert_correct_shape(input_shapes2, shape)
1380
+ # Triple input.
1381
+ input_shapes3 = [shape, shape, shape]
1382
+ self.broadcast_arrays_assert_correct_shape(input_shapes3, shape)
1383
+
1384
+ def test_broadcast_arrays_two_compatible_by_ones_input_shapes(self):
1385
+ # Tests taken from
1386
+ # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L110-L132
1387
+ # Check that two different input shapes of the same length, but some have
1388
+ # ones, broadcast to the correct shape.
1389
+
1390
+ data = [
1391
+ [[(1,), (3,)], (3,)],
1392
+ [[(1, 3), (3, 3)], (3, 3)],
1393
+ [[(3, 1), (3, 3)], (3, 3)],
1394
+ [[(1, 3), (3, 1)], (3, 3)],
1395
+ [[(1, 1), (3, 3)], (3, 3)],
1396
+ [[(1, 1), (1, 3)], (1, 3)],
1397
+ [[(1, 1), (3, 1)], (3, 1)],
1398
+ [[(1, 0), (0, 0)], (0, 0)],
1399
+ [[(0, 1), (0, 0)], (0, 0)],
1400
+ [[(1, 0), (0, 1)], (0, 0)],
1401
+ [[(1, 1), (0, 0)], (0, 0)],
1402
+ [[(1, 1), (1, 0)], (1, 0)],
1403
+ [[(1, 1), (0, 1)], (0, 1)],
1404
+ ]
1405
+ for input_shapes, expected_shape in data:
1406
+ self.broadcast_arrays_assert_correct_shape(input_shapes, expected_shape)
1407
+ # Reverse the input shapes since broadcasting should be symmetric.
1408
+ self.broadcast_arrays_assert_correct_shape(input_shapes[::-1], expected_shape)
1409
+
1410
+ def test_broadcast_arrays_two_compatible_by_prepending_ones_input_shapes(self):
1411
+ # Tests taken from
1412
+ # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L135-L164
1413
+ # Check that two different input shapes (of different lengths) broadcast
1414
+ # to the correct shape.
1415
+
1416
+ data = [
1417
+ [[(), (3,)], (3,)],
1418
+ [[(3,), (3, 3)], (3, 3)],
1419
+ [[(3,), (3, 1)], (3, 3)],
1420
+ [[(1,), (3, 3)], (3, 3)],
1421
+ [[(), (3, 3)], (3, 3)],
1422
+ [[(1, 1), (3,)], (1, 3)],
1423
+ [[(1,), (3, 1)], (3, 1)],
1424
+ [[(1,), (1, 3)], (1, 3)],
1425
+ [[(), (1, 3)], (1, 3)],
1426
+ [[(), (3, 1)], (3, 1)],
1427
+ [[(), (0,)], (0,)],
1428
+ [[(0,), (0, 0)], (0, 0)],
1429
+ [[(0,), (0, 1)], (0, 0)],
1430
+ [[(1,), (0, 0)], (0, 0)],
1431
+ [[(), (0, 0)], (0, 0)],
1432
+ [[(1, 1), (0,)], (1, 0)],
1433
+ [[(1,), (0, 1)], (0, 1)],
1434
+ [[(1,), (1, 0)], (1, 0)],
1435
+ [[(), (1, 0)], (1, 0)],
1436
+ [[(), (0, 1)], (0, 1)],
1437
+ ]
1438
+ for input_shapes, expected_shape in data:
1439
+ self.broadcast_arrays_assert_correct_shape(input_shapes, expected_shape)
1440
+ # Reverse the input shapes since broadcasting should be symmetric.
1441
+ self.broadcast_arrays_assert_correct_shape(input_shapes[::-1], expected_shape)
1442
+
1443
+ def test_broadcast_arrays_scalar_input(self):
1444
+ pyfunc = numpy_broadcast_arrays
1445
+ cfunc = jit(nopython=True)(pyfunc)
1446
+ data = [
1447
+ [[True, False], (1,)],
1448
+ [[1, 2], (1,)],
1449
+ [[(1, 2), 2], (2,)],
1450
+ ]
1451
+ for inarrays, expected_shape in data:
1452
+ outarrays = cfunc(*inarrays)
1453
+ got = [a.shape for a in outarrays]
1454
+ expected = [expected_shape] * len(inarrays)
1455
+ self.assertPreciseEqual(expected, got)
1456
+
1457
+ def test_broadcast_arrays_tuple_input(self):
1458
+ pyfunc = numpy_broadcast_arrays
1459
+ cfunc = jit(nopython=True)(pyfunc)
1460
+ outarrays = cfunc((123, 456), (789,))
1461
+ expected = [(2,), (2,)]
1462
+ got = [a.shape for a in outarrays]
1463
+ self.assertPreciseEqual(expected, got)
1464
+
1465
+ def test_broadcast_arrays_non_array_input(self):
1466
+ pyfunc = numpy_broadcast_arrays
1467
+ cfunc = jit(nopython=True)(pyfunc)
1468
+ outarrays = cfunc(np.intp(2), np.zeros((1, 3), dtype=np.intp))
1469
+ expected = [(1, 3), (1, 3)]
1470
+ got = [a.shape for a in outarrays]
1471
+ self.assertPreciseEqual(expected, got)
1472
+
1473
+ def test_broadcast_arrays_invalid_mixed_input_types(self):
1474
+ pyfunc = numpy_broadcast_arrays
1475
+ cfunc = jit(nopython=True)(pyfunc)
1476
+
1477
+ self.disable_leak_check()
1478
+
1479
+ with self.assertRaises(TypingError) as raises:
1480
+ arr = np.arange(6).reshape((2, 3))
1481
+ b = True
1482
+ cfunc(arr, b)
1483
+ self.assertIn('Mismatch of argument types', str(raises.exception))
1484
+
1485
+ def test_broadcast_arrays_invalid_input(self):
1486
+ pyfunc = numpy_broadcast_arrays
1487
+ cfunc = jit(nopython=True)(pyfunc)
1488
+
1489
+ self.disable_leak_check()
1490
+
1491
+ with self.assertRaises(TypingError) as raises:
1492
+ arr = np.zeros(3, dtype=np.int64)
1493
+ s = 'hello world'
1494
+ cfunc(arr, s)
1495
+ self.assertIn('Argument "1" must be array-like', str(raises.exception))
1496
+
1497
+ def test_broadcast_arrays_incompatible_shapes_raise_valueerror(self):
1498
+ # Check that a ValueError is raised for incompatible shapes.
1499
+ pyfunc = numpy_broadcast_arrays
1500
+ cfunc = jit(nopython=True)(pyfunc)
1501
+
1502
+ self.disable_leak_check()
1503
+
1504
+ data = [
1505
+ [(3,), (4,)],
1506
+ [(2, 3), (2,)],
1507
+ [(3,), (3,), (4,)],
1508
+ [(1, 3, 4), (2, 3, 3)],
1509
+ ]
1510
+ for input_shapes in data:
1511
+ for shape in [input_shapes, input_shapes[::-1]]:
1512
+ # Reverse the input shapes since broadcasting should be symmetric.
1513
+ with self.assertRaises(ValueError) as raises:
1514
+ inarrays = [np.zeros(s) for s in shape]
1515
+ cfunc(*inarrays)
1516
+ self.assertIn("shape mismatch: objects cannot be broadcast to a single shape",
1517
+ str(raises.exception))
1518
+
1519
+ def test_readonly_after_flatten(self):
1520
+ # Reproduces Issue #8370
1521
+ def unfold_flatten(x, y):
1522
+ r, c = x.shape
1523
+ a = np.broadcast_to(x, (y, r, c))
1524
+ b = np.swapaxes(a, 0, 1)
1525
+ cc = b.flatten()
1526
+ d = np.reshape(cc, (-1, c))
1527
+ d[y - 1:, :] = d[: 1 - y]
1528
+ return d
1529
+
1530
+ pyfunc = unfold_flatten
1531
+ cfunc = jit(nopython=True)(pyfunc)
1532
+
1533
+ # If issue #8370 is not fixed: This will fail.
1534
+ res_nb = cfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2)
1535
+ res_py = pyfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2)
1536
+
1537
+ np.testing.assert_array_equal(res_py, res_nb)
1538
+
1539
+ def test_readonly_after_ravel(self):
1540
+ # Reproduces another suggested problem in Issue #8370
1541
+ def unfold_ravel(x, y):
1542
+ r, c = x.shape
1543
+ a = np.broadcast_to(x, (y, r, c))
1544
+ b = np.swapaxes(a, 0, 1)
1545
+ cc = b.ravel()
1546
+ d = np.reshape(cc, (-1, c))
1547
+ d[y - 1:, :] = d[: 1 - y]
1548
+ return d
1549
+
1550
+ pyfunc = unfold_ravel
1551
+ cfunc = jit(nopython=True)(pyfunc)
1552
+
1553
+ # If issue #8370 is not fixed: This will fail.
1554
+ res_nb = cfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2)
1555
+ res_py = pyfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2)
1556
+
1557
+ np.testing.assert_array_equal(res_py, res_nb)
1558
+
1559
+ def test_mutability_after_ravel(self):
1560
+ # Reproduces another suggested problem in Issue #8370
1561
+ # Namely that ravel should only return a writable array
1562
+ # if a copy took place... otherwise leave it as it is.
1563
+ self.disable_leak_check()
1564
+ a_c = np.arange(9).reshape((3, 3)).copy()
1565
+ a_f = a_c.copy(order='F')
1566
+ a_c.flags.writeable = False
1567
+ a_f.flags.writeable = False
1568
+
1569
+ def try_ravel_w_copy(a):
1570
+ result = a.ravel()
1571
+ return result
1572
+
1573
+ pyfunc = try_ravel_w_copy
1574
+ cfunc = jit(nopython=True)(pyfunc)
1575
+
1576
+ ret_c = cfunc(a_c)
1577
+ ret_f = cfunc(a_f)
1578
+
1579
+ msg = 'No copy was performed, so the ' \
1580
+ 'resulting array must not be writeable'
1581
+ self.assertTrue(not ret_c.flags.writeable, msg)
1582
+
1583
+ msg = 'A copy was performed, yet the resulting array is not modifiable'
1584
+ self.assertTrue(ret_f.flags.writeable, msg)
1585
+
1586
+
1587
+ if __name__ == '__main__':
1588
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_asnumbatype.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the as_numba_type() machinery.
3
+ """
4
+ import typing as py_typing
5
+
6
+
7
+ import unittest
8
+
9
+ from numba.core import types
10
+ from numba.core.errors import TypingError
11
+ from numba.core.typing.typeof import typeof
12
+ from numba.core.typing.asnumbatype import as_numba_type, AsNumbaTypeRegistry
13
+ from numba.experimental.jitclass import jitclass
14
+ from numba.tests.support import TestCase
15
+
16
+
17
+ class TestAsNumbaType(TestCase):
18
+
19
+ int_nb_type = typeof(0)
20
+ float_nb_type = typeof(0.0)
21
+ complex_nb_type = typeof(complex(0))
22
+ str_nb_type = typeof("numba")
23
+ bool_nb_type = typeof(True)
24
+ none_nb_type = typeof(None)
25
+
26
+ def test_simple_types(self):
27
+ self.assertEqual(as_numba_type(int), self.int_nb_type)
28
+ self.assertEqual(as_numba_type(float), self.float_nb_type)
29
+ self.assertEqual(as_numba_type(complex), self.complex_nb_type)
30
+ self.assertEqual(as_numba_type(str), self.str_nb_type)
31
+ self.assertEqual(as_numba_type(bool), self.bool_nb_type)
32
+ self.assertEqual(as_numba_type(type(None)), self.none_nb_type)
33
+
34
+ def test_numba_types(self):
35
+ numba_types = [
36
+ types.intp,
37
+ types.boolean,
38
+ types.ListType(types.float64),
39
+ types.DictType(
40
+ types.intp, types.Tuple([types.float32, types.float32])
41
+ ),
42
+ ]
43
+
44
+ for ty in numba_types:
45
+ self.assertEqual(as_numba_type(ty), ty)
46
+
47
+ def test_single_containers(self):
48
+ self.assertEqual(
49
+ as_numba_type(py_typing.List[float]),
50
+ types.ListType(self.float_nb_type),
51
+ )
52
+ self.assertEqual(
53
+ as_numba_type(py_typing.Dict[float, str]),
54
+ types.DictType(self.float_nb_type, self.str_nb_type),
55
+ )
56
+ self.assertEqual(
57
+ as_numba_type(py_typing.Set[complex]),
58
+ types.Set(self.complex_nb_type),
59
+ )
60
+ self.assertEqual(
61
+ as_numba_type(py_typing.Tuple[float, float]),
62
+ types.Tuple([self.float_nb_type, self.float_nb_type]),
63
+ )
64
+ self.assertEqual(
65
+ as_numba_type(py_typing.Tuple[float, complex]),
66
+ types.Tuple([self.float_nb_type, self.complex_nb_type]),
67
+ )
68
+
69
+ def test_optional(self):
70
+ self.assertEqual(
71
+ as_numba_type(py_typing.Optional[float]),
72
+ types.Optional(self.float_nb_type),
73
+ )
74
+ self.assertEqual(
75
+ as_numba_type(py_typing.Union[str, None]),
76
+ types.Optional(self.str_nb_type),
77
+ )
78
+ self.assertEqual(
79
+ as_numba_type(py_typing.Union[None, bool]),
80
+ types.Optional(self.bool_nb_type),
81
+ )
82
+
83
+ # Optional[x] is a special case of Union[x, None]. We raise a
84
+ # TypingError if the right type is not NoneType.
85
+ with self.assertRaises(TypingError) as raises:
86
+ as_numba_type(py_typing.Union[int, float])
87
+ self.assertIn("Cannot type Union that is not an Optional",
88
+ str(raises.exception))
89
+
90
+ def test_nested_containers(self):
91
+ IntList = py_typing.List[int]
92
+ self.assertEqual(
93
+ as_numba_type(py_typing.List[IntList]),
94
+ types.ListType(types.ListType(self.int_nb_type)),
95
+ )
96
+ self.assertEqual(
97
+ as_numba_type(py_typing.List[py_typing.Dict[float, bool]]),
98
+ types.ListType(
99
+ types.DictType(self.float_nb_type, self.bool_nb_type)
100
+ ),
101
+ )
102
+ self.assertEqual(
103
+ as_numba_type(
104
+ py_typing.Set[py_typing.Tuple[py_typing.Optional[int], float]]),
105
+ types.Set(types.Tuple(
106
+ [types.Optional(self.int_nb_type), self.float_nb_type])),
107
+ )
108
+
109
+ def test_jitclass_registers(self):
110
+
111
+ @jitclass
112
+ class MyInt:
113
+ x: int
114
+
115
+ def __init__(self, value):
116
+ self.x = value
117
+
118
+ self.assertEqual(as_numba_type(MyInt), MyInt.class_type.instance_type)
119
+
120
+ def test_type_alias(self):
121
+ Pair = py_typing.Tuple[int, int]
122
+ ListOfPairs = py_typing.List[Pair]
123
+
124
+ pair_nb_type = types.Tuple((self.int_nb_type, self.int_nb_type))
125
+ self.assertEqual(as_numba_type(Pair), pair_nb_type)
126
+ self.assertEqual(
127
+ as_numba_type(ListOfPairs), types.ListType(pair_nb_type)
128
+ )
129
+
130
+ def test_overwrite_type(self):
131
+ as_numba_type = AsNumbaTypeRegistry()
132
+ self.assertEqual(as_numba_type(float), self.float_nb_type)
133
+ as_numba_type.register(float, types.float32)
134
+ self.assertEqual(as_numba_type(float), types.float32)
135
+ self.assertNotEqual(as_numba_type(float), self.float_nb_type)
136
+
137
+ def test_any_throws(self):
138
+ Any = py_typing.Any
139
+
140
+ any_types = [
141
+ py_typing.Optional[Any],
142
+ py_typing.List[Any],
143
+ py_typing.Set[Any],
144
+ py_typing.Dict[float, Any],
145
+ py_typing.Dict[Any, float],
146
+ py_typing.Tuple[int, Any],
147
+ ]
148
+
149
+ for bad_py_type in any_types:
150
+ with self.assertRaises(TypingError) as raises:
151
+ as_numba_type(bad_py_type)
152
+ self.assertIn(
153
+ "Cannot infer numba type of python type",
154
+ str(raises.exception),
155
+ )
156
+
157
+ def test_bad_union_throws(self):
158
+ bad_unions = [
159
+ py_typing.Union[str, int],
160
+ py_typing.Union[int, type(None), py_typing.Tuple[bool, bool]],
161
+ ]
162
+
163
+ for bad_py_type in bad_unions:
164
+ with self.assertRaises(TypingError) as raises:
165
+ as_numba_type(bad_py_type)
166
+ self.assertIn("Cannot type Union", str(raises.exception))
167
+
168
+
169
+ if __name__ == '__main__':
170
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_auto_constants.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+
4
+ import numpy as np
5
+
6
+ from numba import njit
7
+ import numba.tests.usecases as uc
8
+ import unittest
9
+
10
+
11
+ class TestAutoConstants(unittest.TestCase):
12
+ def test_numpy_nan(self):
13
+
14
+ @njit
15
+ def f():
16
+ return np.nan
17
+
18
+ self.assertTrue(math.isnan(f()))
19
+ self.assertTrue(math.isnan(f.py_func()))
20
+
21
+ def test_sys_constant(self):
22
+
23
+ @njit
24
+ def f():
25
+ return sys.hexversion
26
+
27
+ self.assertEqual(f(), f.py_func())
28
+
29
+ def test_module_string_constant(self):
30
+
31
+ @njit
32
+ def f():
33
+ return uc._GLOBAL_STR
34
+ self.assertEqual(f(), f.py_func())
35
+
36
+
37
+ if __name__ == '__main__':
38
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_boundscheck.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from numba.cuda.testing import SerialMixin
4
+ from numba import typeof, cuda, njit
5
+ from numba.core.types import float64
6
+ from numba.tests.support import TestCase, MemoryLeakMixin
7
+ from numba.core import config
8
+ import unittest
9
+
10
+
11
+ def basic_array_access(a):
12
+ return a[10]
13
+
14
+
15
+ def slice_array_access(a):
16
+ # The first index (slice) is not bounds checked
17
+ return a[10:, 10]
18
+
19
+
20
+ def fancy_array_access(x):
21
+ a = np.array([1, 2, 3])
22
+ return x[a]
23
+
24
+
25
+ def fancy_array_modify(x):
26
+ a = np.array([1, 2, 3])
27
+ x[a] = 0
28
+ return x
29
+
30
+
31
+ class TestBoundsCheckNoError(MemoryLeakMixin, TestCase):
32
+
33
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
34
+ def test_basic_array_boundscheck(self):
35
+ self.assertIsNone(config.BOUNDSCHECK)
36
+
37
+ a = np.arange(5)
38
+ # Check the numpy behavior to make sure the test is correct
39
+ with self.assertRaises(IndexError):
40
+ # TODO: When we raise the same error message as numpy, test that
41
+ # they are the same
42
+ basic_array_access(a)
43
+
44
+ at = typeof(a)
45
+ noboundscheck = njit((at,))(basic_array_access)
46
+ # Check that the default flag doesn't raise
47
+ noboundscheck(a)
48
+ # boundscheck(a) is tested in TestBoundsCheckError below
49
+
50
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
51
+ def test_slice_array_boundscheck(self):
52
+ self.assertIsNone(config.BOUNDSCHECK)
53
+
54
+ a = np.ones((5, 5))
55
+ b = np.ones((5, 20))
56
+ with self.assertRaises(IndexError):
57
+ # TODO: When we raise the same error message as numpy, test that
58
+ # they are the same
59
+ slice_array_access(a)
60
+ # Out of bounds on a slice doesn't raise
61
+ slice_array_access(b)
62
+
63
+ at = typeof(a)
64
+ rt = float64[:]
65
+ noboundscheck = njit(rt(at))(slice_array_access)
66
+ boundscheck = njit(rt(at), boundscheck=True)(slice_array_access)
67
+ # Check that the default flag doesn't raise
68
+ noboundscheck(a)
69
+ noboundscheck(b)
70
+ # boundscheck(a) is tested in TestBoundsCheckError below
71
+
72
+ # Doesn't raise
73
+ boundscheck(b)
74
+
75
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
76
+ def test_fancy_indexing_boundscheck(self):
77
+ self.assertIsNone(config.BOUNDSCHECK)
78
+
79
+ a = np.arange(3)
80
+ b = np.arange(4)
81
+
82
+ # Check the numpy behavior to ensure the test is correct.
83
+ with self.assertRaises(IndexError):
84
+ # TODO: When we raise the same error message as numpy, test that
85
+ # they are the same
86
+ fancy_array_access(a)
87
+ fancy_array_access(b)
88
+
89
+ at = typeof(a)
90
+ rt = at.dtype[:]
91
+ noboundscheck = njit(rt(at))(fancy_array_access)
92
+ boundscheck = njit(rt(at), boundscheck=True)(fancy_array_access)
93
+ # Check that the default flag doesn't raise
94
+ noboundscheck(a)
95
+ noboundscheck(b)
96
+ # boundscheck(a) is tested in TestBoundsCheckError below
97
+
98
+ # Doesn't raise
99
+ boundscheck(b)
100
+
101
+
102
+ class TestNoCudaBoundsCheck(SerialMixin, TestCase):
103
+ @unittest.skipIf(not cuda.is_available(), "NO CUDA")
104
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '1'})
105
+ def test_no_cuda_boundscheck(self):
106
+ self.assertTrue(config.BOUNDSCHECK)
107
+ with self.assertRaises(NotImplementedError):
108
+ @cuda.jit(boundscheck=True)
109
+ def func():
110
+ pass
111
+
112
+ # Make sure we aren't raising "not supported" error if we aren't
113
+ # requesting bounds checking anyway. Related pull request: #5257
114
+ @cuda.jit(boundscheck=False)
115
+ def func3():
116
+ pass
117
+
118
+ @cuda.jit
119
+ def func2(x, a):
120
+ a[1] = x[1]
121
+
122
+ a = np.ones((1,))
123
+ x = np.zeros((1,))
124
+ # Out of bounds but doesn't raise (it does raise in the simulator,
125
+ # so skip there)
126
+ if not config.ENABLE_CUDASIM:
127
+ func2[1, 1](x, a)
128
+
129
+
130
+ # This is a separate test because the jitted functions that raise exceptions
131
+ # have memory leaks.
132
+ class TestBoundsCheckError(TestCase):
133
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
134
+ def test_basic_array_boundscheck(self):
135
+ self.assertIsNone(config.BOUNDSCHECK)
136
+
137
+ a = np.arange(5)
138
+ # Check the numpy behavior to make sure the test is correct
139
+ with self.assertRaises(IndexError):
140
+ # TODO: When we raise the same error message as numpy, test that
141
+ # they are the same
142
+ basic_array_access(a)
143
+
144
+ at = typeof(a)
145
+ boundscheck = njit((at,), boundscheck=True)(basic_array_access)
146
+
147
+ with self.assertRaises(IndexError):
148
+ boundscheck(a)
149
+
150
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
151
+ def test_slice_array_boundscheck(self):
152
+ self.assertIsNone(config.BOUNDSCHECK)
153
+
154
+ a = np.ones((5, 5))
155
+ b = np.ones((5, 20))
156
+ with self.assertRaises(IndexError):
157
+ # TODO: When we raise the same error message as numpy, test that
158
+ # they are the same
159
+ slice_array_access(a)
160
+ # Out of bounds on a slice doesn't raise
161
+ slice_array_access(b)
162
+
163
+ at = typeof(a)
164
+ rt = float64[:]
165
+ boundscheck = njit(rt(at), boundscheck=True)(slice_array_access)
166
+
167
+ with self.assertRaises(IndexError):
168
+ boundscheck(a)
169
+
170
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
171
+ def test_fancy_indexing_boundscheck(self):
172
+ self.assertIsNone(config.BOUNDSCHECK)
173
+
174
+ a = np.arange(3)
175
+ b = np.arange(4)
176
+
177
+ # Check the numpy behavior to ensure the test is correct.
178
+ with self.assertRaises(IndexError):
179
+ # TODO: When we raise the same error message as numpy, test that
180
+ # they are the same
181
+ fancy_array_access(a)
182
+ fancy_array_access(b)
183
+
184
+ at = typeof(a)
185
+ rt = at.dtype[:]
186
+ boundscheck = njit(rt(at), boundscheck=True)(fancy_array_access)
187
+
188
+ with self.assertRaises(IndexError):
189
+ boundscheck(a)
190
+
191
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
192
+ def test_fancy_indexing_with_modification_boundscheck(self):
193
+ self.assertIsNone(config.BOUNDSCHECK)
194
+
195
+ a = np.arange(3)
196
+ b = np.arange(4)
197
+
198
+ # Check the numpy behavior to ensure the test is correct.
199
+ with self.assertRaises(IndexError):
200
+ # TODO: When we raise the same error message as numpy, test that
201
+ # they are the same
202
+ fancy_array_modify(a)
203
+ fancy_array_modify(b)
204
+
205
+ at = typeof(a)
206
+ rt = at.dtype[:]
207
+ boundscheck = njit(rt(at), boundscheck=True)(fancy_array_modify)
208
+
209
+ with self.assertRaises(IndexError):
210
+ boundscheck(a)
211
+
212
+
213
+ class TestBoundsEnvironmentVariable(TestCase):
214
+ def setUp(self):
215
+ @njit
216
+ def default(x):
217
+ return x[1]
218
+
219
+ @njit(boundscheck=False)
220
+ def off(x):
221
+ return x[1]
222
+
223
+ @njit(boundscheck=True)
224
+ def on(x):
225
+ return x[1]
226
+
227
+ self.default = default
228
+ self.off = off
229
+ self.on = on
230
+
231
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
232
+ def test_boundscheck_unset(self):
233
+ self.assertIsNone(config.BOUNDSCHECK)
234
+
235
+ a = np.array([1])
236
+
237
+ # Doesn't raise
238
+ self.default(a)
239
+ self.off(a)
240
+
241
+ with self.assertRaises(IndexError):
242
+ self.on(a)
243
+
244
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '1'})
245
+ def test_boundscheck_enabled(self):
246
+ self.assertTrue(config.BOUNDSCHECK)
247
+
248
+ a = np.array([1])
249
+
250
+ with self.assertRaises(IndexError):
251
+ self.default(a)
252
+ self.off(a)
253
+ self.on(a)
254
+
255
+ @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'})
256
+ def test_boundscheck_disabled(self):
257
+ self.assertFalse(config.BOUNDSCHECK)
258
+
259
+ a = np.array([1])
260
+
261
+ # Doesn't raise
262
+ self.default(a)
263
+ self.off(a)
264
+ self.on(a)
265
+
266
+
267
+ if __name__ == '__main__':
268
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_byteflow.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test byteflow.py specific issues
3
+ """
4
+ import unittest
5
+
6
+ from numba.tests.support import TestCase
7
+ from numba.core.compiler import run_frontend
8
+
9
+
10
+ class TestByteFlowIssues(TestCase):
11
+ def test_issue_5087(self):
12
+ # This is an odd issue. The exact number of print below is
13
+ # necessary to trigger it. Too many or too few will alter the behavior.
14
+ # Also note that the function below will not be executed. The problem
15
+ # occurs at compilation. The definition below is invalid for execution.
16
+ # The problem occurs in the bytecode analysis.
17
+ def udt():
18
+ print
19
+ print
20
+ print
21
+
22
+ for i in range:
23
+ print
24
+ print
25
+ print
26
+ print
27
+ print
28
+ print
29
+ print
30
+ print
31
+ print
32
+ print
33
+ print
34
+ print
35
+ print
36
+ print
37
+ print
38
+ print
39
+ print
40
+ print
41
+
42
+ for j in range:
43
+ print
44
+ print
45
+ print
46
+ print
47
+ print
48
+ print
49
+ print
50
+ for k in range:
51
+ for l in range:
52
+ print
53
+
54
+ print
55
+ print
56
+ print
57
+ print
58
+ print
59
+ print
60
+ print
61
+ print
62
+ print
63
+ if print:
64
+ for n in range:
65
+ print
66
+ else:
67
+ print
68
+
69
+ run_frontend(udt)
70
+
71
+ def test_issue_5097(self):
72
+ # Inspired by https://github.com/numba/numba/issues/5097
73
+ def udt():
74
+ for i in range(0):
75
+ if i > 0:
76
+ pass
77
+ a = None # noqa: F841
78
+
79
+ run_frontend(udt)
80
+
81
+ def test_issue_5680(self):
82
+ # From https://github.com/numba/numba/issues/5680#issuecomment-625351336
83
+ def udt():
84
+ for k in range(0):
85
+ if 1 == 1:
86
+ ...
87
+ if 'a' == 'a':
88
+ ...
89
+
90
+ run_frontend(udt)
91
+
92
+
93
+ if __name__ == '__main__':
94
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_cfunc.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for @cfunc and friends.
3
+ """
4
+
5
+
6
+ import ctypes
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ from collections import namedtuple
11
+
12
+ import numpy as np
13
+
14
+ from numba import cfunc, carray, farray, njit
15
+ from numba.core import types, typing, utils
16
+ import numba.core.typing.cffi_utils as cffi_support
17
+ from numba.tests.support import (TestCase, skip_unless_cffi, tag,
18
+ captured_stderr)
19
+ import unittest
20
+ from numba.np import numpy_support
21
+
22
+
23
+ def add_usecase(a, b):
24
+ return a + b
25
+
26
+ def div_usecase(a, b):
27
+ c = a / b
28
+ return c
29
+
30
+ def square_usecase(a):
31
+ return a ** 2
32
+
33
+ add_sig = "float64(float64, float64)"
34
+
35
+ div_sig = "float64(int64, int64)"
36
+
37
+ square_sig = "float64(float64)"
38
+
39
+ def objmode_usecase(a, b):
40
+ object()
41
+ return a + b
42
+
43
+ # Test functions for carray() and farray()
44
+
45
+ CARRAY_USECASE_OUT_LEN = 8
46
+
47
+ def make_cfarray_usecase(func):
48
+
49
+ def cfarray_usecase(in_ptr, out_ptr, m, n):
50
+ # Tuple shape
51
+ in_ = func(in_ptr, (m, n))
52
+ # Integer shape
53
+ out = func(out_ptr, CARRAY_USECASE_OUT_LEN)
54
+ out[0] = in_.ndim
55
+ out[1:3] = in_.shape
56
+ out[3:5] = in_.strides
57
+ out[5] = in_.flags.c_contiguous
58
+ out[6] = in_.flags.f_contiguous
59
+ s = 0
60
+ for i, j in np.ndindex(m, n):
61
+ s += in_[i, j] * (i - j)
62
+ out[7] = s
63
+
64
+ return cfarray_usecase
65
+
66
+ carray_usecase = make_cfarray_usecase(carray)
67
+ farray_usecase = make_cfarray_usecase(farray)
68
+
69
+
70
+ def make_cfarray_dtype_usecase(func):
71
+ # Same as make_cfarray_usecase(), but with explicit dtype.
72
+
73
+ def cfarray_usecase(in_ptr, out_ptr, m, n):
74
+ # Tuple shape
75
+ in_ = func(in_ptr, (m, n), dtype=np.float32)
76
+ # Integer shape
77
+ out = func(out_ptr, CARRAY_USECASE_OUT_LEN, np.float32)
78
+ out[0] = in_.ndim
79
+ out[1:3] = in_.shape
80
+ out[3:5] = in_.strides
81
+ out[5] = in_.flags.c_contiguous
82
+ out[6] = in_.flags.f_contiguous
83
+ s = 0
84
+ for i, j in np.ndindex(m, n):
85
+ s += in_[i, j] * (i - j)
86
+ out[7] = s
87
+
88
+ return cfarray_usecase
89
+
90
+ carray_dtype_usecase = make_cfarray_dtype_usecase(carray)
91
+ farray_dtype_usecase = make_cfarray_dtype_usecase(farray)
92
+
93
+ carray_float32_usecase_sig = types.void(types.CPointer(types.float32),
94
+ types.CPointer(types.float32),
95
+ types.intp, types.intp)
96
+
97
+ carray_float64_usecase_sig = types.void(types.CPointer(types.float64),
98
+ types.CPointer(types.float64),
99
+ types.intp, types.intp)
100
+
101
+ carray_voidptr_usecase_sig = types.void(types.voidptr, types.voidptr,
102
+ types.intp, types.intp)
103
+
104
+
105
+ class TestCFunc(TestCase):
106
+
107
+ def test_basic(self):
108
+ """
109
+ Basic usage and properties of a cfunc.
110
+ """
111
+ f = cfunc(add_sig)(add_usecase)
112
+
113
+ self.assertEqual(f.__name__, "add_usecase")
114
+ self.assertEqual(f.__qualname__, "add_usecase")
115
+ self.assertIs(f.__wrapped__, add_usecase)
116
+
117
+ symbol = f.native_name
118
+ self.assertIsInstance(symbol, str)
119
+ self.assertIn("add_usecase", symbol)
120
+
121
+ addr = f.address
122
+ self.assertIsInstance(addr, int)
123
+
124
+ ct = f.ctypes
125
+ self.assertEqual(ctypes.cast(ct, ctypes.c_void_p).value, addr)
126
+
127
+ self.assertPreciseEqual(ct(2.0, 3.5), 5.5)
128
+
129
+ @skip_unless_cffi
130
+ def test_cffi(self):
131
+ from numba.tests import cffi_usecases
132
+ ffi, lib = cffi_usecases.load_inline_module()
133
+
134
+ f = cfunc(square_sig)(square_usecase)
135
+
136
+ res = lib._numba_test_funcptr(f.cffi)
137
+ self.assertPreciseEqual(res, 2.25) # 1.5 ** 2
138
+
139
+ def test_locals(self):
140
+ # By forcing the intermediate result into an integer, we
141
+ # truncate the ultimate function result
142
+ f = cfunc(div_sig, locals={'c': types.int64})(div_usecase)
143
+ self.assertPreciseEqual(f.ctypes(8, 3), 2.0)
144
+
145
+ def test_errors(self):
146
+ f = cfunc(div_sig)(div_usecase)
147
+
148
+ with captured_stderr() as err:
149
+ self.assertPreciseEqual(f.ctypes(5, 2), 2.5)
150
+ self.assertEqual(err.getvalue(), "")
151
+
152
+ with captured_stderr() as err:
153
+ res = f.ctypes(5, 0)
154
+ # This is just a side effect of Numba zero-initializing
155
+ # stack variables, and could change in the future.
156
+ self.assertPreciseEqual(res, 0.0)
157
+ err = err.getvalue()
158
+ self.assertIn("ZeroDivisionError:", err)
159
+ self.assertIn("Exception ignored", err)
160
+
161
+ def test_llvm_ir(self):
162
+ f = cfunc(add_sig)(add_usecase)
163
+ ir = f.inspect_llvm()
164
+ self.assertIn(f.native_name, ir)
165
+ self.assertIn("fadd double", ir)
166
+
167
+ def test_object_mode(self):
168
+ """
169
+ Object mode is currently unsupported.
170
+ """
171
+ with self.assertRaises(NotImplementedError):
172
+ cfunc(add_sig, forceobj=True)(add_usecase)
173
+ with self.assertTypingError() as raises:
174
+ cfunc(add_sig)(objmode_usecase)
175
+ self.assertIn("Untyped global name 'object'", str(raises.exception))
176
+
177
+
178
+ class TestCArray(TestCase):
179
+ """
180
+ Tests for carray() and farray().
181
+ """
182
+
183
+ def run_carray_usecase(self, pointer_factory, func):
184
+ a = np.arange(10, 16).reshape((2, 3)).astype(np.float32)
185
+ out = np.empty(CARRAY_USECASE_OUT_LEN, dtype=np.float32)
186
+ func(pointer_factory(a), pointer_factory(out), *a.shape)
187
+ return out
188
+
189
+ def check_carray_usecase(self, pointer_factory, pyfunc, cfunc):
190
+ expected = self.run_carray_usecase(pointer_factory, pyfunc)
191
+ got = self.run_carray_usecase(pointer_factory, cfunc)
192
+ self.assertPreciseEqual(expected, got)
193
+
194
+ def make_voidptr(self, arr):
195
+ return arr.ctypes.data_as(ctypes.c_void_p)
196
+
197
+ def make_float32_pointer(self, arr):
198
+ return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
199
+
200
+ def make_float64_pointer(self, arr):
201
+ return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
202
+
203
+ def check_carray_farray(self, func, order):
204
+ def eq(got, expected):
205
+ # Same layout, dtype, shape, etc.
206
+ self.assertPreciseEqual(got, expected)
207
+ # Same underlying data
208
+ self.assertEqual(got.ctypes.data, expected.ctypes.data)
209
+
210
+ base = np.arange(6).reshape((2, 3)).astype(np.float32).copy(order=order)
211
+
212
+ # With typed pointer and implied dtype
213
+ a = func(self.make_float32_pointer(base), base.shape)
214
+ eq(a, base)
215
+ # Integer shape
216
+ a = func(self.make_float32_pointer(base), base.size)
217
+ eq(a, base.ravel('K'))
218
+
219
+ # With typed pointer and explicit dtype
220
+ a = func(self.make_float32_pointer(base), base.shape, base.dtype)
221
+ eq(a, base)
222
+ a = func(self.make_float32_pointer(base), base.shape, np.float32)
223
+ eq(a, base)
224
+
225
+ # With voidptr and explicit dtype
226
+ a = func(self.make_voidptr(base), base.shape, base.dtype)
227
+ eq(a, base)
228
+ a = func(self.make_voidptr(base), base.shape, np.int32)
229
+ eq(a, base.view(np.int32))
230
+
231
+ # voidptr without dtype
232
+ with self.assertRaises(TypeError):
233
+ func(self.make_voidptr(base), base.shape)
234
+ # Invalid pointer type
235
+ with self.assertRaises(TypeError):
236
+ func(base.ctypes.data, base.shape)
237
+ # Mismatching dtype
238
+ with self.assertRaises(TypeError) as raises:
239
+ func(self.make_float32_pointer(base), base.shape, np.int32)
240
+ self.assertIn("mismatching dtype 'int32' for pointer",
241
+ str(raises.exception))
242
+
243
+ def test_carray(self):
244
+ """
245
+ Test pure Python carray().
246
+ """
247
+ self.check_carray_farray(carray, 'C')
248
+
249
+ def test_farray(self):
250
+ """
251
+ Test pure Python farray().
252
+ """
253
+ self.check_carray_farray(farray, 'F')
254
+
255
+ def make_carray_sigs(self, formal_sig):
256
+ """
257
+ Generate a bunch of concrete signatures by varying the width
258
+ and signedness of size arguments (see issue #1923).
259
+ """
260
+ for actual_size in (types.intp, types.int32, types.intc,
261
+ types.uintp, types.uint32, types.uintc):
262
+ args = tuple(actual_size if a == types.intp else a
263
+ for a in formal_sig.args)
264
+ yield formal_sig.return_type(*args)
265
+
266
+ def check_numba_carray_farray(self, usecase, dtype_usecase):
267
+ # With typed pointers and implicit dtype
268
+ pyfunc = usecase
269
+ for sig in self.make_carray_sigs(carray_float32_usecase_sig):
270
+ f = cfunc(sig)(pyfunc)
271
+ self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes)
272
+
273
+ # With typed pointers and explicit (matching) dtype
274
+ pyfunc = dtype_usecase
275
+ for sig in self.make_carray_sigs(carray_float32_usecase_sig):
276
+ f = cfunc(sig)(pyfunc)
277
+ self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes)
278
+ # With typed pointers and mismatching dtype
279
+ with self.assertTypingError() as raises:
280
+ f = cfunc(carray_float64_usecase_sig)(pyfunc)
281
+ self.assertIn("mismatching dtype 'float32' for pointer type 'float64*'",
282
+ str(raises.exception))
283
+
284
+ # With voidptr
285
+ pyfunc = dtype_usecase
286
+ for sig in self.make_carray_sigs(carray_voidptr_usecase_sig):
287
+ f = cfunc(sig)(pyfunc)
288
+ self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes)
289
+
290
+ def test_numba_carray(self):
291
+ """
292
+ Test Numba-compiled carray() against pure Python carray()
293
+ """
294
+ self.check_numba_carray_farray(carray_usecase, carray_dtype_usecase)
295
+
296
+ def test_numba_farray(self):
297
+ """
298
+ Test Numba-compiled farray() against pure Python farray()
299
+ """
300
+ self.check_numba_carray_farray(farray_usecase, farray_dtype_usecase)
301
+
302
+
303
+ @skip_unless_cffi
304
+ class TestCffiStruct(TestCase):
305
+ c_source = """
306
+ typedef struct _big_struct {
307
+ int i1;
308
+ float f2;
309
+ double d3;
310
+ float af4[9];
311
+ } big_struct;
312
+
313
+ typedef struct _error {
314
+ int bits:4;
315
+ } error;
316
+
317
+ typedef double (*myfunc)(big_struct*, size_t);
318
+ """
319
+
320
+ def get_ffi(self, src=c_source):
321
+ from cffi import FFI
322
+
323
+ ffi = FFI()
324
+ ffi.cdef(src)
325
+ return ffi
326
+
327
+ def test_type_parsing(self):
328
+ ffi = self.get_ffi()
329
+ # Check struct typedef
330
+ big_struct = ffi.typeof('big_struct')
331
+ nbtype = cffi_support.map_type(big_struct, use_record_dtype=True)
332
+ self.assertIsInstance(nbtype, types.Record)
333
+ self.assertEqual(len(nbtype), 4)
334
+ self.assertEqual(nbtype.typeof('i1'), types.int32)
335
+ self.assertEqual(nbtype.typeof('f2'), types.float32)
336
+ self.assertEqual(nbtype.typeof('d3'), types.float64)
337
+ self.assertEqual(
338
+ nbtype.typeof('af4'),
339
+ types.NestedArray(dtype=types.float32, shape=(9,)),
340
+ )
341
+
342
+ # Check function typedef
343
+ myfunc = ffi.typeof('myfunc')
344
+ sig = cffi_support.map_type(myfunc, use_record_dtype=True)
345
+ self.assertIsInstance(sig, typing.Signature)
346
+ self.assertEqual(sig.args[0], types.CPointer(nbtype))
347
+ self.assertEqual(sig.args[1], types.uintp)
348
+ self.assertEqual(sig.return_type, types.float64)
349
+
350
+ def test_cfunc_callback(self):
351
+ ffi = self.get_ffi()
352
+ big_struct = ffi.typeof('big_struct')
353
+ nb_big_struct = cffi_support.map_type(big_struct, use_record_dtype=True)
354
+ sig = cffi_support.map_type(ffi.typeof('myfunc'), use_record_dtype=True)
355
+
356
+ @njit
357
+ def calc(base):
358
+ tmp = 0
359
+ for i in range(base.size):
360
+ elem = base[i]
361
+ tmp += elem.i1 * elem.f2 / elem.d3
362
+ tmp += base[i].af4.sum()
363
+ return tmp
364
+
365
+ @cfunc(sig)
366
+ def foo(ptr, n):
367
+ base = carray(ptr, n)
368
+ return calc(base)
369
+
370
+ # Make data
371
+ mydata = ffi.new('big_struct[3]')
372
+ ptr = ffi.cast('big_struct*', mydata)
373
+ for i in range(3):
374
+ ptr[i].i1 = i * 123
375
+ ptr[i].f2 = i * 213
376
+ ptr[i].d3 = (1 + i) * 213
377
+ for j in range(9):
378
+ ptr[i].af4[j] = i * 10 + j
379
+
380
+ # Address of my data
381
+ addr = int(ffi.cast('size_t', ptr))
382
+ got = foo.ctypes(addr, 3)
383
+
384
+ # Make numpy array from the cffi buffer
385
+ array = np.ndarray(
386
+ buffer=ffi.buffer(mydata),
387
+ dtype=numpy_support.as_dtype(nb_big_struct),
388
+ shape=3,
389
+ )
390
+ expect = calc(array)
391
+ self.assertEqual(got, expect)
392
+
393
+ def test_unsupport_bitsize(self):
394
+ ffi = self.get_ffi()
395
+ with self.assertRaises(ValueError) as raises:
396
+ cffi_support.map_type(
397
+ ffi.typeof('error'),
398
+ use_record_dtype=True,
399
+ )
400
+ # When bitsize is provided, bitshift defaults to 0.
401
+ self.assertEqual(
402
+ "field 'bits' has bitshift, this is not supported",
403
+ str(raises.exception)
404
+ )
405
+
406
+
407
+ if __name__ == "__main__":
408
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_codegen.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for numba.core.codegen.
3
+ """
4
+
5
+
6
+ import warnings
7
+ import base64
8
+ import ctypes
9
+ import pickle
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ import weakref
14
+
15
+ import llvmlite.binding as ll
16
+
17
+ import unittest
18
+ from numba import njit
19
+ from numba.core.codegen import JITCPUCodegen
20
+ from numba.core.compiler_lock import global_compiler_lock
21
+ from numba.tests.support import TestCase
22
+
23
+
24
+ asm_sum = r"""
25
+ define i32 @sum(i32 %.1, i32 %.2) {
26
+ %.3 = add i32 %.1, %.2
27
+ ret i32 %.3
28
+ }
29
+ """
30
+
31
+ # Note we're using a rather mangled function name to check that it
32
+ # is compatible with object serialization.
33
+
34
+ asm_sum_inner = """
35
+ define i32 @"__main__.ising_element_update$1.array(int8,_2d,_C).int64.int64"(i32 %.1, i32 %.2) {
36
+ %.3 = add i32 %.1, %.2
37
+ ret i32 %.3
38
+ }
39
+ """ # noqa: E501
40
+
41
+ asm_sum_outer = """
42
+ declare i32 @"__main__.ising_element_update$1.array(int8,_2d,_C).int64.int64"(i32 %.1, i32 %.2)
43
+
44
+ define i32 @sum(i32 %.1, i32 %.2) {
45
+ %.3 = call i32 @"__main__.ising_element_update$1.array(int8,_2d,_C).int64.int64"(i32 %.1, i32 %.2)
46
+ ret i32 %.3
47
+ }
48
+ """ # noqa: E501
49
+
50
+
51
+ ctypes_sum_ty = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
52
+
53
+
54
+ class JITCPUCodegenTestCase(TestCase):
55
+ """
56
+ Test the JIT code generation.
57
+ """
58
+
59
+ def setUp(self):
60
+ global_compiler_lock.acquire()
61
+ self.codegen = JITCPUCodegen('test_codegen')
62
+
63
+ def tearDown(self):
64
+ del self.codegen
65
+ global_compiler_lock.release()
66
+
67
+ def compile_module(self, asm, linking_asm=None):
68
+ library = self.codegen.create_library('compiled_module')
69
+ ll_module = ll.parse_assembly(asm)
70
+ ll_module.verify()
71
+ library.add_llvm_module(ll_module)
72
+ if linking_asm:
73
+ linking_library = self.codegen.create_library('linking_module')
74
+ ll_module = ll.parse_assembly(linking_asm)
75
+ ll_module.verify()
76
+ linking_library.add_llvm_module(ll_module)
77
+ library.add_linking_library(linking_library)
78
+ return library
79
+
80
+ @classmethod
81
+ def _check_unserialize_sum(cls, state):
82
+ codegen = JITCPUCodegen('other_codegen')
83
+ library = codegen.unserialize_library(state)
84
+ ptr = library.get_pointer_to_function("sum")
85
+ assert ptr, ptr
86
+ cfunc = ctypes_sum_ty(ptr)
87
+ res = cfunc(2, 3)
88
+ assert res == 5, res
89
+
90
+ def test_get_pointer_to_function(self):
91
+ library = self.compile_module(asm_sum)
92
+ ptr = library.get_pointer_to_function("sum")
93
+ self.assertIsInstance(ptr, int)
94
+ cfunc = ctypes_sum_ty(ptr)
95
+ self.assertEqual(cfunc(2, 3), 5)
96
+ # Note: With llvm3.9.1, deleting `library` will cause memory error in
97
+ # the following code during running of optimization passes in
98
+ # LLVM. The reason of the error is unclear. The error is known to
99
+ # replicate on osx64 and linux64.
100
+
101
+ # Same, but with dependency on another library
102
+ library2 = self.compile_module(asm_sum_outer, asm_sum_inner)
103
+ ptr = library2.get_pointer_to_function("sum")
104
+ self.assertIsInstance(ptr, int)
105
+ cfunc = ctypes_sum_ty(ptr)
106
+ self.assertEqual(cfunc(2, 3), 5)
107
+
108
+ def test_magic_tuple(self):
109
+ tup = self.codegen.magic_tuple()
110
+ pickle.dumps(tup)
111
+ cg2 = JITCPUCodegen('xxx')
112
+ self.assertEqual(cg2.magic_tuple(), tup)
113
+
114
+ # Serialization tests.
115
+
116
+ def _check_serialize_unserialize(self, state):
117
+ self._check_unserialize_sum(state)
118
+
119
+ def _check_unserialize_other_process(self, state):
120
+ arg = base64.b64encode(pickle.dumps(state, -1))
121
+ code = """if 1:
122
+ import base64
123
+ import pickle
124
+ import sys
125
+ from numba.tests.test_codegen import %(test_class)s
126
+
127
+ state = pickle.loads(base64.b64decode(sys.argv[1]))
128
+ %(test_class)s._check_unserialize_sum(state)
129
+ """ % dict(test_class=self.__class__.__name__)
130
+ subprocess.check_call([sys.executable, '-c', code, arg.decode()])
131
+
132
+ def test_serialize_unserialize_bitcode(self):
133
+ library = self.compile_module(asm_sum_outer, asm_sum_inner)
134
+ state = library.serialize_using_bitcode()
135
+ self._check_serialize_unserialize(state)
136
+
137
+ def test_unserialize_other_process_bitcode(self):
138
+ library = self.compile_module(asm_sum_outer, asm_sum_inner)
139
+ state = library.serialize_using_bitcode()
140
+ self._check_unserialize_other_process(state)
141
+
142
+ def test_serialize_unserialize_object_code(self):
143
+ library = self.compile_module(asm_sum_outer, asm_sum_inner)
144
+ library.enable_object_caching()
145
+ state = library.serialize_using_object_code()
146
+ self._check_serialize_unserialize(state)
147
+
148
+ def test_unserialize_other_process_object_code(self):
149
+ library = self.compile_module(asm_sum_outer, asm_sum_inner)
150
+ library.enable_object_caching()
151
+ state = library.serialize_using_object_code()
152
+ self._check_unserialize_other_process(state)
153
+
154
+ def test_cache_disabled_inspection(self):
155
+ """
156
+ """
157
+ library = self.compile_module(asm_sum_outer, asm_sum_inner)
158
+ library.enable_object_caching()
159
+ state = library.serialize_using_object_code()
160
+
161
+ # exercise the valid behavior
162
+ with warnings.catch_warnings(record=True) as w:
163
+ old_llvm = library.get_llvm_str()
164
+ old_asm = library.get_asm_str()
165
+ library.get_function_cfg('sum')
166
+ self.assertEqual(len(w), 0)
167
+
168
+ # unserialize
169
+ codegen = JITCPUCodegen('other_codegen')
170
+ library = codegen.unserialize_library(state)
171
+
172
+ # the inspection methods would warn and give incorrect result
173
+ with warnings.catch_warnings(record=True) as w:
174
+ warnings.simplefilter("always")
175
+ self.assertNotEqual(old_llvm, library.get_llvm_str())
176
+ self.assertEqual(len(w), 1)
177
+ self.assertIn("Inspection disabled", str(w[0].message))
178
+
179
+ with warnings.catch_warnings(record=True) as w:
180
+ warnings.simplefilter("always")
181
+ self.assertNotEqual(library.get_asm_str(), old_asm)
182
+ self.assertEqual(len(w), 1)
183
+ self.assertIn("Inspection disabled", str(w[0].message))
184
+
185
+ with warnings.catch_warnings(record=True) as w:
186
+ warnings.simplefilter("always")
187
+ with self.assertRaises(NameError) as raises:
188
+ library.get_function_cfg('sum')
189
+ self.assertEqual(len(w), 1)
190
+ self.assertIn("Inspection disabled", str(w[0].message))
191
+ self.assertIn("sum", str(raises.exception))
192
+
193
+ # Lifetime tests
194
+
195
+ @unittest.expectedFailure # MCJIT removeModule leaks and it is disabled
196
+ def test_library_lifetime(self):
197
+ library = self.compile_module(asm_sum_outer, asm_sum_inner)
198
+ # Exercise code generation
199
+ library.enable_object_caching()
200
+ library.serialize_using_bitcode()
201
+ library.serialize_using_object_code()
202
+ u = weakref.ref(library)
203
+ v = weakref.ref(library._final_module)
204
+ del library
205
+ # Both the library and its backing LLVM module are collected
206
+ self.assertIs(u(), None)
207
+ self.assertIs(v(), None)
208
+
209
+
210
+ class TestWrappers(TestCase):
211
+
212
+ def test_noinline_on_main_call(self):
213
+ # Checks that the cpython and cfunc wrapper produces a call with the
214
+ # "noinline" attr present for the decorated function.
215
+
216
+ # Creating a refcounted object induces a side-effect that prevents IPO
217
+ # from eliding the call to the function with LLVM 15. See Issue #9658:
218
+ # https://github.com/numba/numba/issues/9658
219
+ @njit
220
+ def foo():
221
+ return list([1])
222
+
223
+ foo()
224
+ sig = foo.signatures[0]
225
+
226
+ ol = foo.overloads[sig]
227
+ name = ol.fndesc.mangled_name.replace("$", r"\$")
228
+ p1 = r".*call.*{}".format(name)
229
+ p2 = r".*(#[0-9]+).*"
230
+ call_site = re.compile(p1 + p2)
231
+
232
+ lines = foo.inspect_llvm(sig).splitlines()
233
+ meta_data_idx = []
234
+ for l in lines:
235
+ matched = call_site.match(l)
236
+ if matched:
237
+ meta_data_idx.append(matched.groups()[0])
238
+
239
+ # should be 2 calls, one from cpython wrapper one from cfunc wrapper
240
+ self.assertEqual(len(meta_data_idx), 2)
241
+ # both calls should refer to the same metadata item
242
+ self.assertEqual(meta_data_idx[0], meta_data_idx[1])
243
+
244
+ p1 = r"^attributes\s+{}".format(meta_data_idx[0])
245
+ p2 = r"\s+=\s+{(.*)}.*$"
246
+ attr_site = re.compile(p1 + p2)
247
+
248
+ for l in reversed(lines):
249
+ matched = attr_site.match(l)
250
+ if matched:
251
+ meta_data = matched.groups()[0]
252
+ lmeta = meta_data.strip().split(' ')
253
+ for x in lmeta:
254
+ if 'noinline' in x:
255
+ break
256
+ else:
257
+ continue
258
+ break
259
+ else:
260
+ return self.fail("Metadata did not match 'noinline'")
261
+
262
+
263
+ if __name__ == '__main__':
264
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_ctypes.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ctypes import *
2
+ import sys
3
+ import threading
4
+
5
+ import numpy as np
6
+
7
+
8
+ from numba import jit, njit
9
+ from numba.core import types, errors
10
+ from numba.core.typing import ctypes_utils
11
+ from numba.tests.support import MemoryLeakMixin, tag, TestCase
12
+ from numba.tests.ctypes_usecases import *
13
+ import unittest
14
+
15
+
16
+ class TestCTypesTypes(TestCase):
17
+
18
+ def _conversion_tests(self, check):
19
+ check(c_double, types.float64)
20
+ check(c_int, types.intc)
21
+ check(c_uint16, types.uint16)
22
+ check(c_size_t, types.size_t)
23
+ check(c_ssize_t, types.ssize_t)
24
+
25
+ check(c_void_p, types.voidptr)
26
+ check(POINTER(c_float), types.CPointer(types.float32))
27
+ check(POINTER(POINTER(c_float)),
28
+ types.CPointer(types.CPointer(types.float32)))
29
+
30
+ check(None, types.void)
31
+
32
+ def test_from_ctypes(self):
33
+ """
34
+ Test converting a ctypes type to a Numba type.
35
+ """
36
+ def check(cty, ty):
37
+ got = ctypes_utils.from_ctypes(cty)
38
+ self.assertEqual(got, ty)
39
+
40
+ self._conversion_tests(check)
41
+
42
+ # An unsupported type
43
+ with self.assertRaises(TypeError) as raises:
44
+ ctypes_utils.from_ctypes(c_wchar_p)
45
+ self.assertIn("Unsupported ctypes type", str(raises.exception))
46
+
47
+ def test_to_ctypes(self):
48
+ """
49
+ Test converting a Numba type to a ctypes type.
50
+ """
51
+ def check(cty, ty):
52
+ got = ctypes_utils.to_ctypes(ty)
53
+ self.assertEqual(got, cty)
54
+
55
+ self._conversion_tests(check)
56
+
57
+ # An unsupported type
58
+ with self.assertRaises(TypeError) as raises:
59
+ ctypes_utils.to_ctypes(types.ellipsis)
60
+ self.assertIn("Cannot convert Numba type '...' to ctypes type",
61
+ str(raises.exception))
62
+
63
+
64
+ class TestCTypesUseCases(MemoryLeakMixin, TestCase):
65
+
66
+ def test_c_sin(self):
67
+ pyfunc = use_c_sin
68
+ cfunc = njit((types.double,))(pyfunc)
69
+ x = 3.14
70
+ self.assertEqual(pyfunc(x), cfunc(x))
71
+
72
+ def test_two_funcs(self):
73
+ # Check that two constant functions don't get mixed up.
74
+ pyfunc = use_two_funcs
75
+ cfunc = njit((types.double,))(pyfunc)
76
+ x = 3.14
77
+ self.assertEqual(pyfunc(x), cfunc(x))
78
+
79
+ @unittest.skipUnless(is_windows, "Windows-specific test")
80
+ def test_stdcall(self):
81
+ # Just check that it doesn't crash
82
+ cfunc = njit((types.uintc,))(use_c_sleep)
83
+
84
+ cfunc(1)
85
+
86
+ def test_ctype_wrapping(self):
87
+ pyfunc = use_ctype_wrapping
88
+ cfunc = njit((types.double,))(pyfunc)
89
+ x = 3.14
90
+ self.assertEqual(pyfunc(x), cfunc(x))
91
+
92
+ def test_ctype_voidptr(self):
93
+ pyfunc = use_c_pointer
94
+ # pyfunc will segfault if called
95
+ cfunc = njit((types.int32,))(pyfunc)
96
+ x = 123
97
+ self.assertEqual(cfunc(x), x + 1)
98
+
99
+ def test_function_pointer(self):
100
+ pyfunc = use_func_pointer
101
+ cfunc = jit(nopython=True)(pyfunc)
102
+ for (fa, fb, x) in [
103
+ (c_sin, c_cos, 1.0),
104
+ (c_sin, c_cos, -1.0),
105
+ (c_cos, c_sin, 1.0),
106
+ (c_cos, c_sin, -1.0)]:
107
+ expected = pyfunc(fa, fb, x)
108
+ got = cfunc(fa, fb, x)
109
+ self.assertEqual(got, expected)
110
+ # A single specialization was compiled for all calls
111
+ self.assertEqual(len(cfunc.overloads), 1, cfunc.overloads)
112
+
113
+ def test_untyped_function(self):
114
+ with self.assertRaises(TypeError) as raises:
115
+ njit((types.double,))(use_c_untyped)
116
+ self.assertIn("ctypes function '_numba_test_exp' doesn't define its argument types",
117
+ str(raises.exception))
118
+
119
+ def test_python_call_back(self):
120
+ mydct = {'what': 1232121}
121
+
122
+ def call_me_maybe(arr):
123
+ return mydct[arr[0].decode('ascii')]
124
+
125
+ # Create a callback into the python interpreter
126
+ py_call_back = CFUNCTYPE(c_int, py_object)(call_me_maybe)
127
+
128
+ def pyfunc(a):
129
+ what = py_call_back(a)
130
+ return what
131
+
132
+ cfunc = jit(nopython=True, nogil=True)(pyfunc)
133
+ arr = np.array(["what"], dtype='S10')
134
+ self.assertEqual(pyfunc(arr), cfunc(arr))
135
+
136
+ def test_python_call_back_threaded(self):
137
+ def pyfunc(a, repeat):
138
+ out = 0
139
+ for _ in range(repeat):
140
+ out += py_call_back(a)
141
+ return out
142
+
143
+ cfunc = jit(nopython=True, nogil=True)(pyfunc)
144
+
145
+ arr = np.array(["what"], dtype='S10')
146
+ repeat = 1000
147
+
148
+ expected = pyfunc(arr, repeat)
149
+ outputs = []
150
+
151
+ # Warm up
152
+ cfunc(arr, repeat)
153
+
154
+ # Test the function in multiple threads to exercise the
155
+ # GIL ensure/release code
156
+
157
+ def run(func, arr, repeat):
158
+ outputs.append(func(arr, repeat))
159
+
160
+ threads = [threading.Thread(target=run, args=(cfunc, arr, repeat))
161
+ for _ in range(10)]
162
+
163
+ # Start threads
164
+ for th in threads:
165
+ th.start()
166
+
167
+ # End threads
168
+ for th in threads:
169
+ th.join()
170
+
171
+ # Check results
172
+ for got in outputs:
173
+ self.assertEqual(expected, got)
174
+
175
+ def test_passing_array_ctypes_data(self):
176
+ """
177
+ Test the ".ctypes.data" attribute of an array can be passed
178
+ as a "void *" parameter.
179
+ """
180
+ def pyfunc(arr):
181
+ return c_take_array_ptr(arr.ctypes.data)
182
+
183
+ cfunc = jit(nopython=True, nogil=True)(pyfunc)
184
+
185
+ arr = np.arange(5)
186
+
187
+ expected = pyfunc(arr)
188
+ got = cfunc(arr)
189
+
190
+ self.assertEqual(expected, got)
191
+
192
+ def check_array_ctypes(self, pyfunc):
193
+ cfunc = jit(nopython=True)(pyfunc)
194
+
195
+ arr = np.linspace(0, 10, 5)
196
+ expected = arr ** 2.0
197
+ got = cfunc(arr)
198
+ self.assertPreciseEqual(expected, got)
199
+ return cfunc
200
+
201
+ def test_passing_array_ctypes_voidptr(self):
202
+ """
203
+ Test the ".ctypes" attribute of an array can be passed
204
+ as a "void *" parameter.
205
+ """
206
+ self.check_array_ctypes(use_c_vsquare)
207
+
208
+ def test_passing_array_ctypes_voidptr_pass_ptr(self):
209
+ """
210
+ Test the ".ctypes" attribute of an array can be passed
211
+ as a pointer parameter of the right type.
212
+ """
213
+ cfunc = self.check_array_ctypes(use_c_vcube)
214
+
215
+ # Non-compatible pointers are not accepted (here float32* vs. float64*)
216
+ with self.assertRaises(errors.TypingError) as raises:
217
+ cfunc(np.float32([0.0]))
218
+
219
+ self.assertIn("No implementation of function ExternalFunctionPointer",
220
+ str(raises.exception))
221
+
222
+ def test_storing_voidptr_to_int_array(self):
223
+ # Make C callback that returns a void*
224
+ cproto = CFUNCTYPE(c_void_p)
225
+
226
+ @cproto
227
+ def get_voidstar():
228
+ return 0xdeadbeef
229
+
230
+ # Make python functions that use the C callback
231
+ def pyfunc(a):
232
+ ptr = get_voidstar()
233
+ a[0] = ptr
234
+ return ptr
235
+
236
+ # Compile it
237
+ cfunc = njit((types.uintp[::1],))(pyfunc)
238
+
239
+ # Setup inputs
240
+ arr_got = np.zeros(1, dtype=np.uintp)
241
+ arr_expect = arr_got.copy()
242
+
243
+ # Run functions
244
+ ret_got = cfunc(arr_got)
245
+ ret_expect = pyfunc(arr_expect)
246
+
247
+ # Check
248
+ self.assertEqual(ret_expect, 0xdeadbeef)
249
+ self.assertPreciseEqual(ret_got, ret_expect)
250
+ self.assertPreciseEqual(arr_got, arr_expect)
251
+
252
+
253
+ if __name__ == '__main__':
254
+ unittest.main()
255
+
lib/python3.10/site-packages/numba/tests/test_deprecations.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import unittest
3
+ from contextlib import contextmanager
4
+
5
+ from numba import jit, vectorize, guvectorize
6
+ from numba.core.errors import (NumbaDeprecationWarning,
7
+ NumbaPendingDeprecationWarning, NumbaWarning)
8
+ from numba.tests.support import TestCase, needs_setuptools
9
+
10
+
11
+ @contextmanager
12
+ def _catch_numba_deprecation_warnings():
13
+ with warnings.catch_warnings(record=True) as w:
14
+ warnings.simplefilter("ignore", category=NumbaWarning)
15
+ warnings.simplefilter("always", category=NumbaDeprecationWarning)
16
+ yield w
17
+
18
+
19
+ class TestDeprecation(TestCase):
20
+
21
+ def check_warning(self, warnings, expected_str, category, check_rtd=True):
22
+ self.assertEqual(len(warnings), 1)
23
+ self.assertEqual(warnings[0].category, category)
24
+ self.assertIn(expected_str, str(warnings[0].message))
25
+ if check_rtd:
26
+ self.assertIn("https://numba.readthedocs.io",
27
+ str(warnings[0].message))
28
+
29
+ @TestCase.run_test_in_subprocess
30
+ def test_explicit_false_nopython_kwarg(self):
31
+ # tests that explicitly setting `nopython=False` in @jit raises a
32
+ # warning about it doing nothing.
33
+ with _catch_numba_deprecation_warnings() as w:
34
+
35
+ @jit(nopython=False)
36
+ def foo():
37
+ pass
38
+
39
+ foo()
40
+
41
+ msg = "The keyword argument 'nopython=False' was supplied"
42
+ self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False)
43
+
44
+ @TestCase.run_test_in_subprocess
45
+ def test_vectorize_missing_nopython_kwarg_not_reported(self):
46
+ # Checks that use of @vectorize without a nopython kwarg doesn't raise
47
+ # a warning about lack of said kwarg.
48
+
49
+ with _catch_numba_deprecation_warnings() as w:
50
+ # This compiles via nopython mode directly
51
+ @vectorize('float64(float64)')
52
+ def foo(a):
53
+ return a + 1
54
+
55
+ self.assertFalse(w)
56
+
57
+ @TestCase.run_test_in_subprocess
58
+ def test_vectorize_nopython_false_is_reported(self):
59
+ # Checks that use of @vectorize with nopython=False raises a warning
60
+ # about supplying it.
61
+
62
+ with _catch_numba_deprecation_warnings() as w:
63
+ # This compiles via nopython mode directly
64
+ @vectorize('float64(float64)', nopython=False)
65
+ def foo(a):
66
+ return a + 1
67
+
68
+ msg = "The keyword argument 'nopython=False' was supplied"
69
+ self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False)
70
+
71
+ @TestCase.run_test_in_subprocess
72
+ def test_vectorize_objmode_direct_compilation_no_warnings(self):
73
+ # Checks that use of @vectorize with forceobj=True raises no warnings.
74
+
75
+ with _catch_numba_deprecation_warnings() as w:
76
+ # Compiles via objmode directly with no warnings raised
77
+ @vectorize('float64(float64)', forceobj=True)
78
+ def foo(a):
79
+ object()
80
+ return a + 1
81
+
82
+ self.assertFalse(w)
83
+
84
+ @TestCase.run_test_in_subprocess
85
+ def test_vectorize_objmode_compilation_nopython_false_warns(self):
86
+ # Checks that use of @vectorize with forceobj set and nopython set as
87
+ # False raises no warnings.
88
+
89
+ with _catch_numba_deprecation_warnings() as w:
90
+ # Compiles via objmode directly with no warnings raised
91
+ @vectorize('float64(float64)', forceobj=True, nopython=False)
92
+ def foo(a):
93
+ object()
94
+ return a + 1
95
+
96
+ msg = "The keyword argument 'nopython=False' was supplied"
97
+ self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False)
98
+
99
+ @TestCase.run_test_in_subprocess
100
+ def test_vectorize_parallel_true_no_warnings(self):
101
+ # Checks that use of @vectorize with the parallel target doesn't
102
+ # raise warnings about nopython kwarg, the parallel target doesn't
103
+ # support objmode so nopython=True is implicit.
104
+ with _catch_numba_deprecation_warnings() as w:
105
+ @vectorize('float64(float64)', target='parallel')
106
+ def foo(x):
107
+ return x + 1
108
+
109
+ self.assertFalse(w)
110
+
111
+ @TestCase.run_test_in_subprocess
112
+ def test_vectorize_parallel_true_nopython_true_no_warnings(self):
113
+ # Checks that use of @vectorize with the parallel target and
114
+ # nopython=True doesn't raise warnings about nopython kwarg.
115
+ with _catch_numba_deprecation_warnings() as w:
116
+ @vectorize('float64(float64)', target='parallel', nopython=True)
117
+ def foo(x):
118
+ return x + 1
119
+
120
+ self.assertFalse(w)
121
+
122
+ @TestCase.run_test_in_subprocess
123
+ def test_vectorize_parallel_true_nopython_false_warns(self):
124
+ # Checks that use of @vectorize with the parallel target and
125
+ # nopython=False raises a warning about the nopython kwarg being False.
126
+ with _catch_numba_deprecation_warnings() as w:
127
+ @vectorize('float64(float64)', target='parallel', nopython=False)
128
+ def foo(x):
129
+ return x + 1
130
+
131
+ msg = "The keyword argument 'nopython=False' was supplied"
132
+ self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False)
133
+
134
+ @TestCase.run_test_in_subprocess
135
+ def test_vectorize_calling_jit_with_nopython_false_warns_from_jit(self):
136
+ # Checks the scope of the suppression of deprecation warnings that are
137
+ # present in e.g. vectorize. The function `bar` should raise a
138
+ # deprecation warning, the `@vectorize`d `foo` function should not,
139
+ # even though both don't have a nopython kwarg.
140
+
141
+ # First check that the @vectorize call doesn't raise anything
142
+ with _catch_numba_deprecation_warnings() as w:
143
+ @vectorize('float64(float64)', forceobj=True)
144
+ def foo(x):
145
+ return bar(x + 1)
146
+
147
+ def bar(*args):
148
+ pass
149
+
150
+ self.assertFalse(w)
151
+
152
+ @TestCase.run_test_in_subprocess
153
+ def test_guvectorize_implicit_nopython_no_warnings(self):
154
+ # Checks that use of @guvectorize with implicit nopython compilation
155
+ # does not warn on compilation.
156
+ with _catch_numba_deprecation_warnings() as w:
157
+
158
+ @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)')
159
+ def bar(a, b):
160
+ a += 1
161
+
162
+ self.assertFalse(w)
163
+
164
+ @TestCase.run_test_in_subprocess
165
+ def test_guvectorize_forceobj_no_warnings(self):
166
+ # Checks that use of @guvectorize with direct objmode compilation does
167
+ # not warn.
168
+ with _catch_numba_deprecation_warnings() as w:
169
+
170
+ @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)',
171
+ forceobj=True)
172
+ def bar(a, b):
173
+ object()
174
+ a += 1
175
+
176
+ self.assertFalse(w)
177
+
178
+ @TestCase.run_test_in_subprocess
179
+ def test_guvectorize_parallel_implicit_nopython_no_warnings(self):
180
+ # Checks that use of @guvectorize with parallel target and implicit
181
+ # nopython mode compilation does not warn.
182
+ with _catch_numba_deprecation_warnings() as w:
183
+
184
+ @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)',
185
+ target='parallel')
186
+ def bar(a, b):
187
+ a += 1
188
+
189
+ self.assertFalse(w)
190
+
191
+ @TestCase.run_test_in_subprocess
192
+ def test_guvectorize_parallel_forceobj_no_warnings(self):
193
+ # Checks that use of @guvectorize with parallel target and direct
194
+ # objmode compilation does not warn.
195
+ with _catch_numba_deprecation_warnings() as w:
196
+
197
+ # This compiles somewhat surprisingly for the parallel target using
198
+ # object mode?!
199
+ @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)',
200
+ target='parallel', forceobj=True)
201
+ def bar(a, b):
202
+ object()
203
+ a += 1
204
+
205
+ self.assertFalse(w)
206
+
207
+ @TestCase.run_test_in_subprocess
208
+ def test_reflection_of_mutable_container(self):
209
+ # tests that reflection in list/set warns
210
+ def foo_list(a):
211
+ return a.append(1)
212
+
213
+ def foo_set(a):
214
+ return a.add(1)
215
+
216
+ for f in [foo_list, foo_set]:
217
+ container = f.__name__.strip('foo_')
218
+ inp = eval(container)([10, ])
219
+ with warnings.catch_warnings(record=True) as w:
220
+ warnings.simplefilter("ignore", category=NumbaWarning)
221
+ warnings.simplefilter("always",
222
+ category=NumbaPendingDeprecationWarning)
223
+ jit(nopython=True)(f)(inp)
224
+ self.assertEqual(len(w), 1)
225
+ self.assertEqual(w[0].category, NumbaPendingDeprecationWarning)
226
+ warn_msg = str(w[0].message)
227
+ msg = ("Encountered the use of a type that is scheduled for "
228
+ "deprecation")
229
+ self.assertIn(msg, warn_msg)
230
+ msg = ("\'reflected %s\' found for argument" % container)
231
+ self.assertIn(msg, warn_msg)
232
+ self.assertIn("https://numba.readthedocs.io", warn_msg)
233
+
234
+ @needs_setuptools
235
+ @TestCase.run_test_in_subprocess
236
+ def test_pycc_module(self):
237
+ # checks import of module warns
238
+
239
+ with warnings.catch_warnings(record=True) as w:
240
+ warnings.simplefilter("always",
241
+ category=NumbaPendingDeprecationWarning)
242
+ import numba.pycc # noqa: F401
243
+
244
+ expected_str = ("The 'pycc' module is pending deprecation.")
245
+ self.check_warning(w, expected_str, NumbaPendingDeprecationWarning)
246
+
247
+ @needs_setuptools
248
+ @TestCase.run_test_in_subprocess
249
+ def test_pycc_CC(self):
250
+ # check the most commonly used functionality (CC) warns
251
+
252
+ with warnings.catch_warnings(record=True) as w:
253
+ warnings.simplefilter("always",
254
+ category=NumbaPendingDeprecationWarning)
255
+ from numba.pycc import CC # noqa: F401
256
+
257
+ expected_str = ("The 'pycc' module is pending deprecation.")
258
+ self.check_warning(w, expected_str, NumbaPendingDeprecationWarning)
259
+
260
+
261
+ if __name__ == '__main__':
262
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_dispatcher.py ADDED
@@ -0,0 +1,1193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import multiprocessing
2
+ import platform
3
+ import threading
4
+ import pickle
5
+ import weakref
6
+ from itertools import chain
7
+ from io import StringIO
8
+
9
+ import numpy as np
10
+
11
+ from numba import njit, jit, typeof, vectorize
12
+ from numba.core import types, errors
13
+ from numba import _dispatcher
14
+ from numba.tests.support import TestCase, captured_stdout
15
+ from numba.np.numpy_support import as_dtype
16
+ from numba.core.dispatcher import Dispatcher
17
+ from numba.extending import overload
18
+ from numba.tests.support import needs_lapack, SerialMixin
19
+ from numba.testing.main import _TIMEOUT as _RUNNER_TIMEOUT
20
+ import unittest
21
+
22
+
23
+ _TEST_TIMEOUT = _RUNNER_TIMEOUT - 60.
24
+
25
+
26
+ try:
27
+ import jinja2
28
+ except ImportError:
29
+ jinja2 = None
30
+
31
+ try:
32
+ import pygments
33
+ except ImportError:
34
+ pygments = None
35
+
36
+ _is_armv7l = platform.machine() == 'armv7l'
37
+
38
+
39
+ def dummy(x):
40
+ return x
41
+
42
+
43
+ def add(x, y):
44
+ return x + y
45
+
46
+
47
+ def addsub(x, y, z):
48
+ return x - y + z
49
+
50
+
51
+ def addsub_defaults(x, y=2, z=3):
52
+ return x - y + z
53
+
54
+
55
+ def star_defaults(x, y=2, *z):
56
+ return x, y, z
57
+
58
+
59
+ def generated_usecase(x, y=5):
60
+ if isinstance(x, types.Complex):
61
+ def impl(x, y):
62
+ return x + y
63
+ else:
64
+ def impl(x, y):
65
+ return x - y
66
+ return impl
67
+
68
+
69
+ def bad_generated_usecase(x, y=5):
70
+ if isinstance(x, types.Complex):
71
+ def impl(x):
72
+ return x
73
+ else:
74
+ def impl(x, y=6):
75
+ return x - y
76
+ return impl
77
+
78
+
79
+ def dtype_generated_usecase(a, b, dtype=None):
80
+ if isinstance(dtype, (types.misc.NoneType, types.misc.Omitted)):
81
+ out_dtype = np.result_type(*(np.dtype(ary.dtype.name)
82
+ for ary in (a, b)))
83
+ elif isinstance(dtype, (types.DType, types.NumberClass)):
84
+ out_dtype = as_dtype(dtype)
85
+ else:
86
+ raise TypeError("Unhandled Type %s" % type(dtype))
87
+
88
+ def _fn(a, b, dtype=None):
89
+ return np.ones(a.shape, dtype=out_dtype)
90
+
91
+ return _fn
92
+
93
+
94
+ class BaseTest(TestCase):
95
+
96
+ jit_args = dict(nopython=True)
97
+
98
+ def compile_func(self, pyfunc):
99
+ def check(*args, **kwargs):
100
+ expected = pyfunc(*args, **kwargs)
101
+ result = f(*args, **kwargs)
102
+ self.assertPreciseEqual(result, expected)
103
+ f = jit(**self.jit_args)(pyfunc)
104
+ return f, check
105
+
106
+
107
+ class TestDispatcher(BaseTest):
108
+
109
+ def test_equality(self):
110
+ @jit
111
+ def foo(x):
112
+ return x
113
+
114
+ @jit
115
+ def bar(x):
116
+ return x
117
+
118
+ # Written this way to verify `==` returns a bool (gh-5838). Using
119
+ # `assertTrue(foo == foo)` or `assertEqual(foo, foo)` would defeat the
120
+ # purpose of this test.
121
+ self.assertEqual(foo == foo, True)
122
+ self.assertEqual(foo == bar, False)
123
+ self.assertEqual(foo == None, False) # noqa: E711
124
+
125
+ def test_dyn_pyfunc(self):
126
+ @jit
127
+ def foo(x):
128
+ return x
129
+
130
+ foo(1)
131
+ [cr] = foo.overloads.values()
132
+ # __module__ must be match that of foo
133
+ self.assertEqual(cr.entry_point.__module__, foo.py_func.__module__)
134
+
135
+ def test_no_argument(self):
136
+ @jit
137
+ def foo():
138
+ return 1
139
+
140
+ # Just make sure this doesn't crash
141
+ foo()
142
+
143
+ def test_coerce_input_types(self):
144
+ # Issue #486: do not allow unsafe conversions if we can still
145
+ # compile other specializations.
146
+ c_add = jit(nopython=True)(add)
147
+ self.assertPreciseEqual(c_add(123, 456), add(123, 456))
148
+ self.assertPreciseEqual(c_add(12.3, 45.6), add(12.3, 45.6))
149
+ self.assertPreciseEqual(c_add(12.3, 45.6j), add(12.3, 45.6j))
150
+ self.assertPreciseEqual(c_add(12300000000, 456), add(12300000000, 456))
151
+
152
+ # Now force compilation of only a single specialization
153
+ c_add = jit('(i4, i4)', nopython=True)(add)
154
+ self.assertPreciseEqual(c_add(123, 456), add(123, 456))
155
+ # Implicit (unsafe) conversion of float to int
156
+ self.assertPreciseEqual(c_add(12.3, 45.6), add(12, 45))
157
+ with self.assertRaises(TypeError):
158
+ # Implicit conversion of complex to int disallowed
159
+ c_add(12.3, 45.6j)
160
+
161
+ def test_ambiguous_new_version(self):
162
+ """Test compiling new version in an ambiguous case
163
+ """
164
+ @jit
165
+ def foo(a, b):
166
+ return a + b
167
+
168
+ INT = 1
169
+ FLT = 1.5
170
+ self.assertAlmostEqual(foo(INT, FLT), INT + FLT)
171
+ self.assertEqual(len(foo.overloads), 1)
172
+ self.assertAlmostEqual(foo(FLT, INT), FLT + INT)
173
+ self.assertEqual(len(foo.overloads), 2)
174
+ self.assertAlmostEqual(foo(FLT, FLT), FLT + FLT)
175
+ self.assertEqual(len(foo.overloads), 3)
176
+ # The following call is ambiguous because (int, int) can resolve
177
+ # to (float, int) or (int, float) with equal weight.
178
+ self.assertAlmostEqual(foo(1, 1), INT + INT)
179
+ self.assertEqual(len(foo.overloads), 4, "didn't compile a new "
180
+ "version")
181
+
182
+ def test_lock(self):
183
+ """
184
+ Test that (lazy) compiling from several threads at once doesn't
185
+ produce errors (see issue #908).
186
+ """
187
+ errors = []
188
+
189
+ @jit
190
+ def foo(x):
191
+ return x + 1
192
+
193
+ def wrapper():
194
+ try:
195
+ self.assertEqual(foo(1), 2)
196
+ except Exception as e:
197
+ errors.append(e)
198
+
199
+ threads = [threading.Thread(target=wrapper) for i in range(16)]
200
+ for t in threads:
201
+ t.start()
202
+ for t in threads:
203
+ t.join()
204
+ self.assertFalse(errors)
205
+
206
+ def test_explicit_signatures(self):
207
+ f = jit("(int64,int64)")(add)
208
+ # Approximate match (unsafe conversion)
209
+ self.assertPreciseEqual(f(1.5, 2.5), 3)
210
+ self.assertEqual(len(f.overloads), 1, f.overloads)
211
+ f = jit(["(int64,int64)", "(float64,float64)"])(add)
212
+ # Exact signature matches
213
+ self.assertPreciseEqual(f(1, 2), 3)
214
+ self.assertPreciseEqual(f(1.5, 2.5), 4.0)
215
+ # Approximate match (int32 -> float64 is a safe conversion)
216
+ self.assertPreciseEqual(f(np.int32(1), 2.5), 3.5)
217
+ # No conversion
218
+ with self.assertRaises(TypeError) as cm:
219
+ f(1j, 1j)
220
+ self.assertIn("No matching definition", str(cm.exception))
221
+ self.assertEqual(len(f.overloads), 2, f.overloads)
222
+ # A more interesting one...
223
+ f = jit(["(float32,float32)", "(float64,float64)"])(add)
224
+ self.assertPreciseEqual(f(np.float32(1), np.float32(2**-25)), 1.0)
225
+ self.assertPreciseEqual(f(1, 2**-25), 1.0000000298023224)
226
+ # Fail to resolve ambiguity between the two best overloads
227
+ f = jit(["(float32,float64)",
228
+ "(float64,float32)",
229
+ "(int64,int64)"])(add)
230
+ with self.assertRaises(TypeError) as cm:
231
+ f(1.0, 2.0)
232
+ # The two best matches are output in the error message, as well
233
+ # as the actual argument types.
234
+ self.assertRegex(
235
+ str(cm.exception),
236
+ r"Ambiguous overloading for <function add [^>]*> "
237
+ r"\(float64, float64\):\n"
238
+ r"\(float32, float64\) -> float64\n"
239
+ r"\(float64, float32\) -> float64"
240
+ )
241
+ # The integer signature is not part of the best matches
242
+ self.assertNotIn("int64", str(cm.exception))
243
+
244
+ def test_signature_mismatch(self):
245
+ tmpl = ("Signature mismatch: %d argument types given, but function "
246
+ "takes 2 arguments")
247
+ with self.assertRaises(TypeError) as cm:
248
+ jit("()")(add)
249
+ self.assertIn(tmpl % 0, str(cm.exception))
250
+ with self.assertRaises(TypeError) as cm:
251
+ jit("(intc,)")(add)
252
+ self.assertIn(tmpl % 1, str(cm.exception))
253
+ with self.assertRaises(TypeError) as cm:
254
+ jit("(intc,intc,intc)")(add)
255
+ self.assertIn(tmpl % 3, str(cm.exception))
256
+ # With forceobj=True, an empty tuple is accepted
257
+ jit("()", forceobj=True)(add)
258
+ with self.assertRaises(TypeError) as cm:
259
+ jit("(intc,)", forceobj=True)(add)
260
+ self.assertIn(tmpl % 1, str(cm.exception))
261
+
262
+ def test_matching_error_message(self):
263
+ f = jit("(intc,intc)")(add)
264
+ with self.assertRaises(TypeError) as cm:
265
+ f(1j, 1j)
266
+ self.assertEqual(str(cm.exception),
267
+ "No matching definition for argument type(s) "
268
+ "complex128, complex128")
269
+
270
+ def test_disabled_compilation(self):
271
+ @jit
272
+ def foo(a):
273
+ return a
274
+
275
+ foo.compile("(float32,)")
276
+ foo.disable_compile()
277
+ with self.assertRaises(RuntimeError) as raises:
278
+ foo.compile("(int32,)")
279
+ self.assertEqual(str(raises.exception), "compilation disabled")
280
+ self.assertEqual(len(foo.signatures), 1)
281
+
282
+ def test_disabled_compilation_through_list(self):
283
+ @jit(["(float32,)", "(int32,)"])
284
+ def foo(a):
285
+ return a
286
+
287
+ with self.assertRaises(RuntimeError) as raises:
288
+ foo.compile("(complex64,)")
289
+ self.assertEqual(str(raises.exception), "compilation disabled")
290
+ self.assertEqual(len(foo.signatures), 2)
291
+
292
+ def test_disabled_compilation_nested_call(self):
293
+ @jit(["(intp,)"])
294
+ def foo(a):
295
+ return a
296
+
297
+ @jit
298
+ def bar():
299
+ foo(1)
300
+ foo(np.ones(1)) # no matching definition
301
+
302
+ with self.assertRaises(errors.TypingError) as raises:
303
+ bar()
304
+
305
+ m = r".*Invalid use of.*with parameters \(array\(float64, 1d, C\)\).*"
306
+ self.assertRegex(str(raises.exception), m)
307
+
308
+ def test_fingerprint_failure(self):
309
+ """
310
+ Failure in computing the fingerprint cannot affect a nopython=False
311
+ function. On the other hand, with nopython=True, a ValueError should
312
+ be raised to report the failure with fingerprint.
313
+ """
314
+ def foo(x):
315
+ return x
316
+
317
+ # Empty list will trigger failure in compile_fingerprint
318
+ errmsg = 'cannot compute fingerprint of empty list'
319
+ with self.assertRaises(ValueError) as raises:
320
+ _dispatcher.compute_fingerprint([])
321
+ self.assertIn(errmsg, str(raises.exception))
322
+ # It should work in objmode
323
+ objmode_foo = jit(forceobj=True)(foo)
324
+ self.assertEqual(objmode_foo([]), [])
325
+ # But, not in nopython=True
326
+ strict_foo = jit(nopython=True)(foo)
327
+ with self.assertRaises(ValueError) as raises:
328
+ strict_foo([])
329
+ self.assertIn(errmsg, str(raises.exception))
330
+
331
+ # Test in loop lifting context
332
+ @jit(forceobj=True)
333
+ def bar():
334
+ object() # force looplifting
335
+ x = []
336
+ for i in range(10):
337
+ x = objmode_foo(x)
338
+ return x
339
+
340
+ self.assertEqual(bar(), [])
341
+ # Make sure it was looplifted
342
+ [cr] = bar.overloads.values()
343
+ self.assertEqual(len(cr.lifted), 1)
344
+
345
+ def test_serialization(self):
346
+ """
347
+ Test serialization of Dispatcher objects
348
+ """
349
+ @jit(nopython=True)
350
+ def foo(x):
351
+ return x + 1
352
+
353
+ self.assertEqual(foo(1), 2)
354
+
355
+ # get serialization memo
356
+ memo = Dispatcher._memo
357
+ Dispatcher._recent.clear()
358
+ memo_size = len(memo)
359
+
360
+ # pickle foo and check memo size
361
+ serialized_foo = pickle.dumps(foo)
362
+ # increases the memo size
363
+ self.assertEqual(memo_size + 1, len(memo))
364
+
365
+ # unpickle
366
+ foo_rebuilt = pickle.loads(serialized_foo)
367
+ self.assertEqual(memo_size + 1, len(memo))
368
+
369
+ self.assertIs(foo, foo_rebuilt)
370
+
371
+ # do we get the same object even if we delete all the explicit
372
+ # references?
373
+ id_orig = id(foo_rebuilt)
374
+ del foo
375
+ del foo_rebuilt
376
+ self.assertEqual(memo_size + 1, len(memo))
377
+ new_foo = pickle.loads(serialized_foo)
378
+ self.assertEqual(id_orig, id(new_foo))
379
+
380
+ # now clear the recent cache
381
+ ref = weakref.ref(new_foo)
382
+ del new_foo
383
+ Dispatcher._recent.clear()
384
+ self.assertEqual(memo_size, len(memo))
385
+
386
+ # show that deserializing creates a new object
387
+ pickle.loads(serialized_foo)
388
+ self.assertIs(ref(), None)
389
+
390
+ @needs_lapack
391
+ @unittest.skipIf(_is_armv7l, "Unaligned loads unsupported")
392
+ def test_misaligned_array_dispatch(self):
393
+ # for context see issue #2937
394
+ def foo(a):
395
+ return np.linalg.matrix_power(a, 1)
396
+
397
+ jitfoo = jit(nopython=True)(foo)
398
+
399
+ n = 64
400
+ r = int(np.sqrt(n))
401
+ dt = np.int8
402
+ count = np.complex128().itemsize // dt().itemsize
403
+
404
+ tmp = np.arange(n * count + 1, dtype=dt)
405
+
406
+ # create some arrays as Cartesian production of:
407
+ # [F/C] x [aligned/misaligned]
408
+ C_contig_aligned = tmp[:-1].view(np.complex128).reshape(r, r)
409
+ C_contig_misaligned = tmp[1:].view(np.complex128).reshape(r, r)
410
+ F_contig_aligned = C_contig_aligned.T
411
+ F_contig_misaligned = C_contig_misaligned.T
412
+
413
+ # checking routine
414
+ def check(name, a):
415
+ a[:, :] = np.arange(n, dtype=np.complex128).reshape(r, r)
416
+ expected = foo(a)
417
+ got = jitfoo(a)
418
+ np.testing.assert_allclose(expected, got)
419
+
420
+ # The checks must be run in this order to create the dispatch key
421
+ # sequence that causes invalid dispatch noted in #2937.
422
+ # The first two should hit the cache as they are aligned, supported
423
+ # order and under 5 dimensions. The second two should end up in the
424
+ # fallback path as they are misaligned.
425
+ check("C_contig_aligned", C_contig_aligned)
426
+ check("F_contig_aligned", F_contig_aligned)
427
+ check("C_contig_misaligned", C_contig_misaligned)
428
+ check("F_contig_misaligned", F_contig_misaligned)
429
+
430
+ @unittest.skipIf(_is_armv7l, "Unaligned loads unsupported")
431
+ def test_immutability_in_array_dispatch(self):
432
+
433
+ # RO operation in function
434
+ def foo(a):
435
+ return np.sum(a)
436
+
437
+ jitfoo = jit(nopython=True)(foo)
438
+
439
+ n = 64
440
+ r = int(np.sqrt(n))
441
+ dt = np.int8
442
+ count = np.complex128().itemsize // dt().itemsize
443
+
444
+ tmp = np.arange(n * count + 1, dtype=dt)
445
+
446
+ # create some arrays as Cartesian production of:
447
+ # [F/C] x [aligned/misaligned]
448
+ C_contig_aligned = tmp[:-1].view(np.complex128).reshape(r, r)
449
+ C_contig_misaligned = tmp[1:].view(np.complex128).reshape(r, r)
450
+ F_contig_aligned = C_contig_aligned.T
451
+ F_contig_misaligned = C_contig_misaligned.T
452
+
453
+ # checking routine
454
+ def check(name, a, disable_write_bit=False):
455
+ a[:, :] = np.arange(n, dtype=np.complex128).reshape(r, r)
456
+ if disable_write_bit:
457
+ a.flags.writeable = False
458
+ expected = foo(a)
459
+ got = jitfoo(a)
460
+ np.testing.assert_allclose(expected, got)
461
+
462
+ # all of these should end up in the fallback path as they have no write
463
+ # bit set
464
+ check("C_contig_aligned", C_contig_aligned, disable_write_bit=True)
465
+ check("F_contig_aligned", F_contig_aligned, disable_write_bit=True)
466
+ check("C_contig_misaligned", C_contig_misaligned,
467
+ disable_write_bit=True)
468
+ check("F_contig_misaligned", F_contig_misaligned,
469
+ disable_write_bit=True)
470
+
471
+ @needs_lapack
472
+ @unittest.skipIf(_is_armv7l, "Unaligned loads unsupported")
473
+ def test_misaligned_high_dimension_array_dispatch(self):
474
+
475
+ def foo(a):
476
+ return np.linalg.matrix_power(a[0, 0, 0, 0, :, :], 1)
477
+
478
+ jitfoo = jit(nopython=True)(foo)
479
+
480
+ def check_properties(arr, layout, aligned):
481
+ self.assertEqual(arr.flags.aligned, aligned)
482
+ if layout == "C":
483
+ self.assertEqual(arr.flags.c_contiguous, True)
484
+ if layout == "F":
485
+ self.assertEqual(arr.flags.f_contiguous, True)
486
+
487
+ n = 729
488
+ r = 3
489
+ dt = np.int8
490
+ count = np.complex128().itemsize // dt().itemsize
491
+
492
+ tmp = np.arange(n * count + 1, dtype=dt)
493
+
494
+ # create some arrays as Cartesian production of:
495
+ # [F/C] x [aligned/misaligned]
496
+ C_contig_aligned = tmp[:-1].view(np.complex128).\
497
+ reshape(r, r, r, r, r, r)
498
+ check_properties(C_contig_aligned, 'C', True)
499
+ C_contig_misaligned = tmp[1:].view(np.complex128).\
500
+ reshape(r, r, r, r, r, r)
501
+ check_properties(C_contig_misaligned, 'C', False)
502
+ F_contig_aligned = C_contig_aligned.T
503
+ check_properties(F_contig_aligned, 'F', True)
504
+ F_contig_misaligned = C_contig_misaligned.T
505
+ check_properties(F_contig_misaligned, 'F', False)
506
+
507
+ # checking routine
508
+ def check(name, a):
509
+ a[:, :] = np.arange(n, dtype=np.complex128).\
510
+ reshape(r, r, r, r, r, r)
511
+ expected = foo(a)
512
+ got = jitfoo(a)
513
+ np.testing.assert_allclose(expected, got)
514
+
515
+ # these should all hit the fallback path as the cache is only for up to
516
+ # 5 dimensions
517
+ check("F_contig_misaligned", F_contig_misaligned)
518
+ check("C_contig_aligned", C_contig_aligned)
519
+ check("F_contig_aligned", F_contig_aligned)
520
+ check("C_contig_misaligned", C_contig_misaligned)
521
+
522
+ def test_dispatch_recompiles_for_scalars(self):
523
+ # for context #3612, essentially, compiling a lambda x:x for a
524
+ # numerically wide type (everything can be converted to a complex128)
525
+ # and then calling again with e.g. an int32 would lead to the int32
526
+ # being converted to a complex128 whereas it ought to compile an int32
527
+ # specialization.
528
+ def foo(x):
529
+ return x
530
+
531
+ # jit and compile on dispatch for 3 scalar types, expect 3 signatures
532
+ jitfoo = jit(nopython=True)(foo)
533
+ jitfoo(np.complex128(1 + 2j))
534
+ jitfoo(np.int32(10))
535
+ jitfoo(np.bool_(False))
536
+ self.assertEqual(len(jitfoo.signatures), 3)
537
+ expected_sigs = [(types.complex128,), (types.int32,), (types.bool_,)]
538
+ self.assertEqual(jitfoo.signatures, expected_sigs)
539
+
540
+ # now jit with signatures so recompilation is forbidden
541
+ # expect 1 signature and type conversion
542
+ jitfoo = jit([(types.complex128,)], nopython=True)(foo)
543
+ jitfoo(np.complex128(1 + 2j))
544
+ jitfoo(np.int32(10))
545
+ jitfoo(np.bool_(False))
546
+ self.assertEqual(len(jitfoo.signatures), 1)
547
+ expected_sigs = [(types.complex128,)]
548
+ self.assertEqual(jitfoo.signatures, expected_sigs)
549
+
550
+ def test_dispatcher_raises_for_invalid_decoration(self):
551
+ # For context see https://github.com/numba/numba/issues/4750.
552
+
553
+ @jit(nopython=True)
554
+ def foo(x):
555
+ return x
556
+
557
+ with self.assertRaises(TypeError) as raises:
558
+ jit(foo)
559
+ err_msg = str(raises.exception)
560
+ self.assertIn(
561
+ "A jit decorator was called on an already jitted function", err_msg)
562
+ self.assertIn("foo", err_msg)
563
+ self.assertIn(".py_func", err_msg)
564
+
565
+ with self.assertRaises(TypeError) as raises:
566
+ jit(BaseTest)
567
+ err_msg = str(raises.exception)
568
+ self.assertIn("The decorated object is not a function", err_msg)
569
+ self.assertIn(f"{type(BaseTest)}", err_msg)
570
+
571
+
572
+ class TestSignatureHandling(BaseTest):
573
+ """
574
+ Test support for various parameter passing styles.
575
+ """
576
+
577
+ def test_named_args(self):
578
+ """
579
+ Test passing named arguments to a dispatcher.
580
+ """
581
+ f, check = self.compile_func(addsub)
582
+ check(3, z=10, y=4)
583
+ check(3, 4, 10)
584
+ check(x=3, y=4, z=10)
585
+ # All calls above fall under the same specialization
586
+ self.assertEqual(len(f.overloads), 1)
587
+ # Errors
588
+ with self.assertRaises(TypeError) as cm:
589
+ f(3, 4, y=6, z=7)
590
+ self.assertIn("too many arguments: expected 3, got 4",
591
+ str(cm.exception))
592
+ with self.assertRaises(TypeError) as cm:
593
+ f()
594
+ self.assertIn("not enough arguments: expected 3, got 0",
595
+ str(cm.exception))
596
+ with self.assertRaises(TypeError) as cm:
597
+ f(3, 4, y=6)
598
+ self.assertIn("missing argument 'z'", str(cm.exception))
599
+
600
+ def test_default_args(self):
601
+ """
602
+ Test omitting arguments with a default value.
603
+ """
604
+ f, check = self.compile_func(addsub_defaults)
605
+ check(3, z=10, y=4)
606
+ check(3, 4, 10)
607
+ check(x=3, y=4, z=10)
608
+ # Now omitting some values
609
+ check(3, z=10)
610
+ check(3, 4)
611
+ check(x=3, y=4)
612
+ check(3)
613
+ check(x=3)
614
+ # Errors
615
+ with self.assertRaises(TypeError) as cm:
616
+ f(3, 4, y=6, z=7)
617
+ self.assertIn("too many arguments: expected 3, got 4",
618
+ str(cm.exception))
619
+ with self.assertRaises(TypeError) as cm:
620
+ f()
621
+ self.assertIn("not enough arguments: expected at least 1, got 0",
622
+ str(cm.exception))
623
+ with self.assertRaises(TypeError) as cm:
624
+ f(y=6, z=7)
625
+ self.assertIn("missing argument 'x'", str(cm.exception))
626
+
627
+ def test_star_args(self):
628
+ """
629
+ Test a compiled function with starargs in the signature.
630
+ """
631
+ f, check = self.compile_func(star_defaults)
632
+ check(4)
633
+ check(4, 5)
634
+ check(4, 5, 6)
635
+ check(4, 5, 6, 7)
636
+ check(4, 5, 6, 7, 8)
637
+ check(x=4)
638
+ check(x=4, y=5)
639
+ check(4, y=5)
640
+ with self.assertRaises(TypeError) as cm:
641
+ f(4, 5, y=6)
642
+ self.assertIn("some keyword arguments unexpected", str(cm.exception))
643
+ with self.assertRaises(TypeError) as cm:
644
+ f(4, 5, z=6)
645
+ self.assertIn("some keyword arguments unexpected", str(cm.exception))
646
+ with self.assertRaises(TypeError) as cm:
647
+ f(4, x=6)
648
+ self.assertIn("some keyword arguments unexpected", str(cm.exception))
649
+
650
+
651
+ class TestSignatureHandlingObjectMode(TestSignatureHandling):
652
+ """
653
+ Sams as TestSignatureHandling, but in object mode.
654
+ """
655
+
656
+ jit_args = dict(forceobj=True)
657
+
658
+
659
+ class TestDispatcherMethods(TestCase):
660
+
661
+ def test_recompile(self):
662
+ closure = 1
663
+
664
+ @jit
665
+ def foo(x):
666
+ return x + closure
667
+ self.assertPreciseEqual(foo(1), 2)
668
+ self.assertPreciseEqual(foo(1.5), 2.5)
669
+ self.assertEqual(len(foo.signatures), 2)
670
+ closure = 2
671
+ self.assertPreciseEqual(foo(1), 2)
672
+ # Recompiling takes the new closure into account.
673
+ foo.recompile()
674
+ # Everything was recompiled
675
+ self.assertEqual(len(foo.signatures), 2)
676
+ self.assertPreciseEqual(foo(1), 3)
677
+ self.assertPreciseEqual(foo(1.5), 3.5)
678
+
679
+ def test_recompile_signatures(self):
680
+ # Same as above, but with an explicit signature on @jit.
681
+ closure = 1
682
+
683
+ @jit("int32(int32)")
684
+ def foo(x):
685
+ return x + closure
686
+ self.assertPreciseEqual(foo(1), 2)
687
+ self.assertPreciseEqual(foo(1.5), 2)
688
+ closure = 2
689
+ self.assertPreciseEqual(foo(1), 2)
690
+ # Recompiling takes the new closure into account.
691
+ foo.recompile()
692
+ self.assertPreciseEqual(foo(1), 3)
693
+ self.assertPreciseEqual(foo(1.5), 3)
694
+
695
+ def test_inspect_llvm(self):
696
+ # Create a jited function
697
+ @jit
698
+ def foo(explicit_arg1, explicit_arg2):
699
+ return explicit_arg1 + explicit_arg2
700
+
701
+ # Call it in a way to create 3 signatures
702
+ foo(1, 1)
703
+ foo(1.0, 1)
704
+ foo(1.0, 1.0)
705
+
706
+ # base call to get all llvm in a dict
707
+ llvms = foo.inspect_llvm()
708
+ self.assertEqual(len(llvms), 3)
709
+
710
+ # make sure the function name shows up in the llvm
711
+ for llvm_bc in llvms.values():
712
+ # Look for the function name
713
+ self.assertIn("foo", llvm_bc)
714
+
715
+ # Look for the argument names
716
+ self.assertIn("explicit_arg1", llvm_bc)
717
+ self.assertIn("explicit_arg2", llvm_bc)
718
+
719
+ def test_inspect_asm(self):
720
+ # Create a jited function
721
+ @jit
722
+ def foo(explicit_arg1, explicit_arg2):
723
+ return explicit_arg1 + explicit_arg2
724
+
725
+ # Call it in a way to create 3 signatures
726
+ foo(1, 1)
727
+ foo(1.0, 1)
728
+ foo(1.0, 1.0)
729
+
730
+ # base call to get all llvm in a dict
731
+ asms = foo.inspect_asm()
732
+ self.assertEqual(len(asms), 3)
733
+
734
+ # make sure the function name shows up in the llvm
735
+ for asm in asms.values():
736
+ # Look for the function name
737
+ self.assertTrue("foo" in asm)
738
+
739
+ def _check_cfg_display(self, cfg, wrapper=''):
740
+ # simple stringify test
741
+ if wrapper:
742
+ wrapper = "{}{}".format(len(wrapper), wrapper)
743
+ module_name = __name__.split('.', 1)[0]
744
+ module_len = len(module_name)
745
+ prefix = r'^digraph "CFG for \'_ZN{}{}{}'.format(wrapper,
746
+ module_len,
747
+ module_name)
748
+ self.assertRegex(str(cfg), prefix)
749
+ # .display() requires an optional dependency on `graphviz`.
750
+ # just test for the attribute without running it.
751
+ self.assertTrue(callable(cfg.display))
752
+
753
+ def test_inspect_cfg(self):
754
+ # Exercise the .inspect_cfg(). These are minimal tests and do not fully
755
+ # check the correctness of the function.
756
+ @jit
757
+ def foo(the_array):
758
+ return the_array.sum()
759
+
760
+ # Generate 3 overloads
761
+ a1 = np.ones(1)
762
+ a2 = np.ones((1, 1))
763
+ a3 = np.ones((1, 1, 1))
764
+ foo(a1)
765
+ foo(a2)
766
+ foo(a3)
767
+
768
+ # Call inspect_cfg() without arguments
769
+ cfgs = foo.inspect_cfg()
770
+
771
+ # Correct count of overloads
772
+ self.assertEqual(len(cfgs), 3)
773
+
774
+ # Makes sure all the signatures are correct
775
+ [s1, s2, s3] = cfgs.keys()
776
+ self.assertEqual(set([s1, s2, s3]),
777
+ set(map(lambda x: (typeof(x),), [a1, a2, a3])))
778
+
779
+ for cfg in cfgs.values():
780
+ self._check_cfg_display(cfg)
781
+ self.assertEqual(len(list(cfgs.values())), 3)
782
+
783
+ # Call inspect_cfg(signature)
784
+ cfg = foo.inspect_cfg(signature=foo.signatures[0])
785
+ self._check_cfg_display(cfg)
786
+
787
+ def test_inspect_cfg_with_python_wrapper(self):
788
+ # Exercise the .inspect_cfg() including the python wrapper.
789
+ # These are minimal tests and do not fully check the correctness of
790
+ # the function.
791
+ @jit
792
+ def foo(the_array):
793
+ return the_array.sum()
794
+
795
+ # Generate 3 overloads
796
+ a1 = np.ones(1)
797
+ a2 = np.ones((1, 1))
798
+ a3 = np.ones((1, 1, 1))
799
+ foo(a1)
800
+ foo(a2)
801
+ foo(a3)
802
+
803
+ # Call inspect_cfg(signature, show_wrapper="python")
804
+ cfg = foo.inspect_cfg(signature=foo.signatures[0],
805
+ show_wrapper="python")
806
+ self._check_cfg_display(cfg, wrapper='cpython')
807
+
808
+ def test_inspect_types(self):
809
+ @jit
810
+ def foo(a, b):
811
+ return a + b
812
+
813
+ foo(1, 2)
814
+ # Exercise the method
815
+ foo.inspect_types(StringIO())
816
+
817
+ # Test output
818
+ expected = str(foo.overloads[foo.signatures[0]].type_annotation)
819
+ with captured_stdout() as out:
820
+ foo.inspect_types()
821
+ assert expected in out.getvalue()
822
+
823
+ def test_inspect_types_with_signature(self):
824
+ @jit
825
+ def foo(a):
826
+ return a + 1
827
+
828
+ foo(1)
829
+ foo(1.0)
830
+ # Inspect all signatures
831
+ with captured_stdout() as total:
832
+ foo.inspect_types()
833
+ # Inspect first signature
834
+ with captured_stdout() as first:
835
+ foo.inspect_types(signature=foo.signatures[0])
836
+ # Inspect second signature
837
+ with captured_stdout() as second:
838
+ foo.inspect_types(signature=foo.signatures[1])
839
+
840
+ self.assertEqual(total.getvalue(), first.getvalue() + second.getvalue())
841
+
842
+ @unittest.skipIf(jinja2 is None, "please install the 'jinja2' package")
843
+ @unittest.skipIf(pygments is None, "please install the 'pygments' package")
844
+ def test_inspect_types_pretty(self):
845
+ @jit
846
+ def foo(a, b):
847
+ return a + b
848
+
849
+ foo(1, 2)
850
+
851
+ # Exercise the method, dump the output
852
+ with captured_stdout():
853
+ ann = foo.inspect_types(pretty=True)
854
+
855
+ # ensure HTML <span> is found in the annotation output
856
+ for k, v in ann.ann.items():
857
+ span_found = False
858
+ for line in v['pygments_lines']:
859
+ if 'span' in line[2]:
860
+ span_found = True
861
+ self.assertTrue(span_found)
862
+
863
+ # check that file+pretty kwarg combo raises
864
+ with self.assertRaises(ValueError) as raises:
865
+ foo.inspect_types(file=StringIO(), pretty=True)
866
+
867
+ self.assertIn("`file` must be None if `pretty=True`",
868
+ str(raises.exception))
869
+
870
+ def test_get_annotation_info(self):
871
+ @jit
872
+ def foo(a):
873
+ return a + 1
874
+
875
+ foo(1)
876
+ foo(1.3)
877
+
878
+ expected = dict(chain.from_iterable(foo.get_annotation_info(i).items()
879
+ for i in foo.signatures))
880
+ result = foo.get_annotation_info()
881
+ self.assertEqual(expected, result)
882
+
883
+ def test_issue_with_array_layout_conflict(self):
884
+ """
885
+ This test an issue with the dispatcher when an array that is both
886
+ C and F contiguous is supplied as the first signature.
887
+ The dispatcher checks for F contiguous first but the compiler checks
888
+ for C contiguous first. This results in an C contiguous code inserted
889
+ as F contiguous function.
890
+ """
891
+ def pyfunc(A, i, j):
892
+ return A[i, j]
893
+
894
+ cfunc = jit(pyfunc)
895
+
896
+ ary_c_and_f = np.array([[1.]])
897
+ ary_c = np.array([[0., 1.], [2., 3.]], order='C')
898
+ ary_f = np.array([[0., 1.], [2., 3.]], order='F')
899
+
900
+ exp_c = pyfunc(ary_c, 1, 0)
901
+ exp_f = pyfunc(ary_f, 1, 0)
902
+
903
+ self.assertEqual(1., cfunc(ary_c_and_f, 0, 0))
904
+ got_c = cfunc(ary_c, 1, 0)
905
+ got_f = cfunc(ary_f, 1, 0)
906
+
907
+ self.assertEqual(exp_c, got_c)
908
+ self.assertEqual(exp_f, got_f)
909
+
910
+
911
+ class TestDispatcherFunctionBoundaries(TestCase):
912
+ def test_pass_dispatcher_as_arg(self):
913
+ # Test that a Dispatcher object can be pass as argument
914
+ @jit(nopython=True)
915
+ def add1(x):
916
+ return x + 1
917
+
918
+ @jit(nopython=True)
919
+ def bar(fn, x):
920
+ return fn(x)
921
+
922
+ @jit(nopython=True)
923
+ def foo(x):
924
+ return bar(add1, x)
925
+
926
+ # Check dispatcher as argument inside NPM
927
+ inputs = [1, 11.1, np.arange(10)]
928
+ expected_results = [x + 1 for x in inputs]
929
+
930
+ for arg, expect in zip(inputs, expected_results):
931
+ self.assertPreciseEqual(foo(arg), expect)
932
+
933
+ # Check dispatcher as argument from python
934
+ for arg, expect in zip(inputs, expected_results):
935
+ self.assertPreciseEqual(bar(add1, arg), expect)
936
+
937
+ def test_dispatcher_as_arg_usecase(self):
938
+ @jit(nopython=True)
939
+ def maximum(seq, cmpfn):
940
+ tmp = seq[0]
941
+ for each in seq[1:]:
942
+ cmpval = cmpfn(tmp, each)
943
+ if cmpval < 0:
944
+ tmp = each
945
+ return tmp
946
+
947
+ got = maximum([1, 2, 3, 4], cmpfn=jit(lambda x, y: x - y))
948
+ self.assertEqual(got, 4)
949
+ got = maximum(list(zip(range(5), range(5)[::-1])),
950
+ cmpfn=jit(lambda x, y: x[0] - y[0]))
951
+ self.assertEqual(got, (4, 0))
952
+ got = maximum(list(zip(range(5), range(5)[::-1])),
953
+ cmpfn=jit(lambda x, y: x[1] - y[1]))
954
+ self.assertEqual(got, (0, 4))
955
+
956
+ def test_dispatcher_can_return_to_python(self):
957
+ @jit(nopython=True)
958
+ def foo(fn):
959
+ return fn
960
+
961
+ fn = jit(lambda x: x)
962
+
963
+ self.assertEqual(foo(fn), fn)
964
+
965
+ def test_dispatcher_in_sequence_arg(self):
966
+ @jit(nopython=True)
967
+ def one(x):
968
+ return x + 1
969
+
970
+ @jit(nopython=True)
971
+ def two(x):
972
+ return one(one(x))
973
+
974
+ @jit(nopython=True)
975
+ def three(x):
976
+ return one(one(one(x)))
977
+
978
+ @jit(nopython=True)
979
+ def choose(fns, x):
980
+ return fns[0](x), fns[1](x), fns[2](x)
981
+
982
+ # Tuple case
983
+ self.assertEqual(choose((one, two, three), 1), (2, 3, 4))
984
+ # List case
985
+ self.assertEqual(choose([one, one, one], 1), (2, 2, 2))
986
+
987
+
988
+ class TestBoxingDefaultError(unittest.TestCase):
989
+ # Testing default error at boxing/unboxing
990
+ def test_unbox_runtime_error(self):
991
+ # Dummy type has no unbox support
992
+ def foo(x):
993
+ pass
994
+ argtys = (types.Dummy("dummy_type"),)
995
+ # This needs `compile_isolated`-like behaviour so as to bypass
996
+ # dispatcher type checking logic
997
+ cres = njit(argtys)(foo).overloads[argtys]
998
+ with self.assertRaises(TypeError) as raises:
999
+ # Can pass in whatever and the unbox logic will always raise
1000
+ # without checking the input value.
1001
+ cres.entry_point(None)
1002
+ self.assertEqual(str(raises.exception), "can't unbox dummy_type type")
1003
+
1004
+ def test_box_runtime_error(self):
1005
+ @njit
1006
+ def foo():
1007
+ return unittest # Module type has no boxing logic
1008
+ with self.assertRaises(TypeError) as raises:
1009
+ foo()
1010
+ pat = "cannot convert native Module.* to Python object"
1011
+ self.assertRegex(str(raises.exception), pat)
1012
+
1013
+
1014
+ class TestNoRetryFailedSignature(unittest.TestCase):
1015
+ """Test that failed-to-compile signatures are not recompiled.
1016
+ """
1017
+
1018
+ def run_test(self, func):
1019
+ fcom = func._compiler
1020
+ self.assertEqual(len(fcom._failed_cache), 0)
1021
+ # expected failure because `int` has no `__getitem__`
1022
+ with self.assertRaises(errors.TypingError):
1023
+ func(1)
1024
+ self.assertEqual(len(fcom._failed_cache), 1)
1025
+ # retry
1026
+ with self.assertRaises(errors.TypingError):
1027
+ func(1)
1028
+ self.assertEqual(len(fcom._failed_cache), 1)
1029
+ # retry with double
1030
+ with self.assertRaises(errors.TypingError):
1031
+ func(1.0)
1032
+ self.assertEqual(len(fcom._failed_cache), 2)
1033
+
1034
+ def test_direct_call(self):
1035
+ @jit(nopython=True)
1036
+ def foo(x):
1037
+ return x[0]
1038
+
1039
+ self.run_test(foo)
1040
+
1041
+ def test_nested_call(self):
1042
+ @jit(nopython=True)
1043
+ def bar(x):
1044
+ return x[0]
1045
+
1046
+ @jit(nopython=True)
1047
+ def foobar(x):
1048
+ bar(x)
1049
+
1050
+ @jit(nopython=True)
1051
+ def foo(x):
1052
+ return bar(x) + foobar(x)
1053
+
1054
+ self.run_test(foo)
1055
+
1056
+ @unittest.expectedFailure
1057
+ # NOTE: @overload does not have an error cache. See PR #9259 for this
1058
+ # feature and remove the xfail once this is merged.
1059
+ def test_error_count(self):
1060
+ def check(field, would_fail):
1061
+ # Slightly modified from the reproducer in issue #4117.
1062
+ # Before the patch, the compilation time of the failing case is
1063
+ # much longer than of the successful case. This can be detected
1064
+ # by the number of times `trigger()` is visited.
1065
+ k = 10
1066
+ counter = {'c': 0}
1067
+
1068
+ def trigger(x):
1069
+ assert 0, "unreachable"
1070
+
1071
+ @overload(trigger)
1072
+ def ol_trigger(x):
1073
+ # Keep track of every visit
1074
+ counter['c'] += 1
1075
+ if would_fail:
1076
+ raise errors.TypingError("invoke_failed")
1077
+ return lambda x: x
1078
+
1079
+ @jit(nopython=True)
1080
+ def ident(out, x):
1081
+ pass
1082
+
1083
+ def chain_assign(fs, inner=ident):
1084
+ tab_head, tab_tail = fs[-1], fs[:-1]
1085
+
1086
+ @jit(nopython=True)
1087
+ def assign(out, x):
1088
+ inner(out, x)
1089
+ out[0] += tab_head(x)
1090
+
1091
+ if tab_tail:
1092
+ return chain_assign(tab_tail, assign)
1093
+ else:
1094
+ return assign
1095
+
1096
+ chain = chain_assign((trigger,) * k)
1097
+ out = np.ones(2)
1098
+ if would_fail:
1099
+ with self.assertRaises(errors.TypingError) as raises:
1100
+ chain(out, 1)
1101
+ self.assertIn('invoke_failed', str(raises.exception))
1102
+ else:
1103
+ chain(out, 1)
1104
+
1105
+ # Returns the visit counts
1106
+ return counter['c']
1107
+
1108
+ ct_ok = check('a', False)
1109
+ ct_bad = check('c', True)
1110
+ # `trigger()` is visited exactly once for both successful and failed
1111
+ # compilation.
1112
+ self.assertEqual(ct_ok, 1)
1113
+ self.assertEqual(ct_bad, 1)
1114
+
1115
+
1116
+ @njit
1117
+ def add_y1(x, y=1):
1118
+ return x + y
1119
+
1120
+
1121
+ @njit
1122
+ def add_ynone(x, y=None):
1123
+ return x + (1 if y else 2)
1124
+
1125
+
1126
+ @njit
1127
+ def mult(x, y):
1128
+ return x * y
1129
+
1130
+
1131
+ @njit
1132
+ def add_func(x, func=mult):
1133
+ return x + func(x, x)
1134
+
1135
+
1136
+ def _checker(f1, arg):
1137
+ assert f1(arg) == f1.py_func(arg)
1138
+
1139
+
1140
+ class TestMultiprocessingDefaultParameters(SerialMixin, unittest.TestCase):
1141
+ def run_fc_multiproc(self, fc):
1142
+ try:
1143
+ ctx = multiprocessing.get_context('spawn')
1144
+ except AttributeError:
1145
+ ctx = multiprocessing
1146
+
1147
+ # RE: issue #5973, this doesn't use multiprocessing.Pool.map as doing so
1148
+ # causes the TBB library to segfault under certain conditions. It's not
1149
+ # clear whether the cause is something in the complexity of the Pool
1150
+ # itself, e.g. watcher threads etc, or if it's a problem synonymous with
1151
+ # a "timing attack".
1152
+ for a in [1, 2, 3]:
1153
+ p = ctx.Process(target=_checker, args=(fc, a,))
1154
+ p.start()
1155
+ p.join(_TEST_TIMEOUT)
1156
+ self.assertEqual(p.exitcode, 0)
1157
+
1158
+ def test_int_def_param(self):
1159
+ """ Tests issue #4888"""
1160
+
1161
+ self.run_fc_multiproc(add_y1)
1162
+
1163
+ def test_none_def_param(self):
1164
+ """ Tests None as a default parameter"""
1165
+
1166
+ self.run_fc_multiproc(add_func)
1167
+
1168
+ def test_function_def_param(self):
1169
+ """ Tests a function as a default parameter"""
1170
+
1171
+ self.run_fc_multiproc(add_func)
1172
+
1173
+
1174
+ class TestVectorizeDifferentTargets(unittest.TestCase):
1175
+ """Test that vectorize can be reapplied if the target is different
1176
+ """
1177
+
1178
+ def test_cpu_vs_parallel(self):
1179
+ @jit
1180
+ def add(x, y):
1181
+ return x + y
1182
+
1183
+ custom_vectorize = vectorize([], identity=None, target='cpu')
1184
+
1185
+ custom_vectorize(add)
1186
+
1187
+ custom_vectorize_2 = vectorize([], identity=None, target='parallel')
1188
+
1189
+ custom_vectorize_2(add)
1190
+
1191
+
1192
+ if __name__ == '__main__':
1193
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_exceptions.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import sys
3
+ import traceback
4
+
5
+ from numba import jit, njit
6
+ from numba.core import types, errors, utils
7
+ from numba.tests.support import (TestCase, expected_failure_py311,
8
+ expected_failure_py312,
9
+ expected_failure_py313,
10
+ )
11
+ import unittest
12
+
13
+
14
+ force_pyobj_flags = {'nopython': False, 'forceobj': True}
15
+ no_pyobj_flags = {'nopython': True, '_nrt': False}
16
+ no_pyobj_flags_w_nrt = {'nopython': True, '_nrt': True}
17
+ no_gil_flags = {'nopython': True, 'nogil': True, '_nrt': True}
18
+
19
+
20
+ class MyError(Exception):
21
+ pass
22
+
23
+
24
+ class OtherError(Exception):
25
+ pass
26
+
27
+
28
+ class UDEArgsToSuper(Exception):
29
+ def __init__(self, arg, value0):
30
+ super(UDEArgsToSuper, self).__init__(arg)
31
+ self.value0 = value0
32
+
33
+ def __eq__(self, other):
34
+ if not isinstance(other, self.__class__):
35
+ return False
36
+ same = True
37
+ same |= self.args == other.args
38
+ same |= self.value0 == other.value0
39
+ return same
40
+
41
+ def __hash__(self):
42
+ return hash((super(UDEArgsToSuper).__hash__(), self.value0))
43
+
44
+
45
+ class UDENoArgSuper(Exception):
46
+ def __init__(self, arg, value0):
47
+ super(UDENoArgSuper, self).__init__()
48
+ self.deferarg = arg
49
+ self.value0 = value0
50
+
51
+ def __eq__(self, other):
52
+ if not isinstance(other, self.__class__):
53
+ return False
54
+ same = True
55
+ same |= self.args == other.args
56
+ same |= self.deferarg == other.deferarg
57
+ same |= self.value0 == other.value0
58
+ return same
59
+
60
+ def __hash__(self):
61
+ return hash((super(UDENoArgSuper).__hash__(), self.deferarg,
62
+ self.value0))
63
+
64
+
65
+ def raise_class(exc):
66
+ def raiser(i):
67
+ if i == 1:
68
+ raise exc
69
+ elif i == 2:
70
+ raise ValueError
71
+ elif i == 3:
72
+ # The exception type is looked up on a module (issue #1624)
73
+ raise np.linalg.LinAlgError
74
+ return i
75
+ return raiser
76
+
77
+
78
+ def raise_instance(exc, arg):
79
+ def raiser(i):
80
+ if i == 1:
81
+ raise exc(arg, 1)
82
+ elif i == 2:
83
+ raise ValueError(arg, 2)
84
+ elif i == 3:
85
+ raise np.linalg.LinAlgError(arg, 3)
86
+ return i
87
+ return raiser
88
+
89
+
90
+ def raise_instance_runtime_args(exc):
91
+ def raiser(i, arg):
92
+ if i == 1:
93
+ raise exc(arg, 1)
94
+ elif i == 2:
95
+ raise ValueError(arg, 2)
96
+ elif i == 3:
97
+ raise np.linalg.LinAlgError(arg, 3)
98
+ return i
99
+ return raiser
100
+
101
+
102
+ def reraise():
103
+ raise
104
+
105
+
106
+ def outer_function(inner):
107
+ def outer(i):
108
+ if i == 3:
109
+ raise OtherError("bar", 3)
110
+ return inner(i)
111
+ return outer
112
+
113
+
114
+ def assert_usecase(i):
115
+ assert i == 1, "bar"
116
+
117
+
118
+ def ude_bug_usecase():
119
+ raise UDEArgsToSuper() # oops user forgot args to exception ctor
120
+
121
+
122
+ def raise_runtime_value(arg):
123
+ raise ValueError(arg)
124
+
125
+
126
+ class TestRaising(TestCase):
127
+
128
+ def test_unituple_index_error(self):
129
+ def pyfunc(a, i):
130
+ return a.shape[i]
131
+
132
+ cfunc = njit((types.Array(types.int32, 1, 'A'), types.int32),)(pyfunc)
133
+
134
+ a = np.empty(2, dtype=np.int32)
135
+
136
+ self.assertEqual(cfunc(a, 0), pyfunc(a, 0))
137
+
138
+ with self.assertRaises(IndexError) as cm:
139
+ cfunc(a, 2)
140
+ self.assertEqual(str(cm.exception), "tuple index out of range")
141
+
142
+ def check_against_python(self, exec_mode, pyfunc, cfunc,
143
+ expected_error_class, *args):
144
+
145
+ assert exec_mode in (force_pyobj_flags, no_pyobj_flags,
146
+ no_pyobj_flags_w_nrt, no_gil_flags)
147
+
148
+ # invariant of mode, check the error class and args are the same
149
+ with self.assertRaises(expected_error_class) as pyerr:
150
+ pyfunc(*args)
151
+ with self.assertRaises(expected_error_class) as jiterr:
152
+ cfunc(*args)
153
+ self.assertEqual(pyerr.exception.args, jiterr.exception.args)
154
+
155
+ # special equality check for UDEs
156
+ if isinstance(pyerr.exception, (UDEArgsToSuper, UDENoArgSuper)):
157
+ self.assertTrue(pyerr.exception == jiterr.exception)
158
+
159
+ # in npm check bottom of traceback matches as frame injection with
160
+ # location info should ensure this
161
+ if exec_mode is no_pyobj_flags:
162
+
163
+ # we only care about the bottom two frames, the error and the
164
+ # location it was raised.
165
+ try:
166
+ pyfunc(*args)
167
+ except Exception:
168
+ py_frames = traceback.format_exception(*sys.exc_info())
169
+ expected_frames = py_frames[-2:]
170
+
171
+ try:
172
+ cfunc(*args)
173
+ except Exception:
174
+ c_frames = traceback.format_exception(*sys.exc_info())
175
+ got_frames = c_frames[-2:]
176
+
177
+ # check exception and the injected frame are the same
178
+ for expf, gotf in zip(expected_frames, got_frames):
179
+ # Note use of assertIn not assertEqual, Py 3.11 has markers (^)
180
+ # that point to the variable causing the problem, Numba doesn't
181
+ # do this so only the start of the string will match.
182
+ self.assertIn(gotf, expf)
183
+
184
+ def check_raise_class(self, flags):
185
+ pyfunc = raise_class(MyError)
186
+ cfunc = jit((types.int32,), **flags)(pyfunc)
187
+ self.assertEqual(cfunc(0), 0)
188
+ self.check_against_python(flags, pyfunc, cfunc, MyError, 1)
189
+ self.check_against_python(flags, pyfunc, cfunc, ValueError, 2)
190
+ self.check_against_python(flags, pyfunc, cfunc,
191
+ np.linalg.linalg.LinAlgError, 3)
192
+
193
+ def test_raise_class_nopython(self):
194
+ self.check_raise_class(flags=no_pyobj_flags)
195
+
196
+ def test_raise_class_objmode(self):
197
+ self.check_raise_class(flags=force_pyobj_flags)
198
+
199
+ def check_raise_instance(self, flags):
200
+ for clazz in [MyError, UDEArgsToSuper,
201
+ UDENoArgSuper]:
202
+ pyfunc = raise_instance(clazz, "some message")
203
+ cfunc = jit((types.int32,), **flags)(pyfunc)
204
+
205
+ self.assertEqual(cfunc(0), 0)
206
+ self.check_against_python(flags, pyfunc, cfunc, clazz, 1)
207
+ self.check_against_python(flags, pyfunc, cfunc, ValueError, 2)
208
+ self.check_against_python(flags, pyfunc, cfunc,
209
+ np.linalg.linalg.LinAlgError, 3)
210
+
211
+ def test_raise_instance_objmode(self):
212
+ self.check_raise_instance(flags=force_pyobj_flags)
213
+
214
+ def test_raise_instance_nopython(self):
215
+ self.check_raise_instance(flags=no_pyobj_flags)
216
+
217
+ def check_raise_nested(self, flags, **jit_args):
218
+ """
219
+ Check exception propagation from nested functions.
220
+ """
221
+ for clazz in [MyError, UDEArgsToSuper,
222
+ UDENoArgSuper]:
223
+ inner_pyfunc = raise_instance(clazz, "some message")
224
+ pyfunc = outer_function(inner_pyfunc)
225
+ inner_cfunc = jit(**jit_args)(inner_pyfunc)
226
+ cfunc = jit(**jit_args)(outer_function(inner_cfunc))
227
+
228
+ self.check_against_python(flags, pyfunc, cfunc, clazz, 1)
229
+ self.check_against_python(flags, pyfunc, cfunc, ValueError, 2)
230
+ self.check_against_python(flags, pyfunc, cfunc, OtherError, 3)
231
+
232
+ def test_raise_nested_objmode(self):
233
+ self.check_raise_nested(force_pyobj_flags, forceobj=True)
234
+
235
+ def test_raise_nested_nopython(self):
236
+ self.check_raise_nested(no_pyobj_flags, nopython=True)
237
+
238
+ def check_reraise(self, flags):
239
+ def raise_exc(exc):
240
+ raise exc
241
+ pyfunc = reraise
242
+ cfunc = jit((), **flags)(pyfunc)
243
+ for op, err in [(lambda : raise_exc(ZeroDivisionError),
244
+ ZeroDivisionError),
245
+ (lambda : raise_exc(UDEArgsToSuper("msg", 1)),
246
+ UDEArgsToSuper),
247
+ (lambda : raise_exc(UDENoArgSuper("msg", 1)),
248
+ UDENoArgSuper)]:
249
+ def gen_impl(fn):
250
+ def impl():
251
+ try:
252
+ op()
253
+ except err:
254
+ fn()
255
+ return impl
256
+ pybased = gen_impl(pyfunc)
257
+ cbased = gen_impl(cfunc)
258
+ self.check_against_python(flags, pybased, cbased, err,)
259
+
260
+ def test_reraise_objmode(self):
261
+ self.check_reraise(flags=force_pyobj_flags)
262
+
263
+ def test_reraise_nopython(self):
264
+ self.check_reraise(flags=no_pyobj_flags)
265
+
266
+ def check_raise_invalid_class(self, cls, flags):
267
+ pyfunc = raise_class(cls)
268
+ cfunc = jit((types.int32,), **flags)(pyfunc)
269
+ with self.assertRaises(TypeError) as cm:
270
+ cfunc(1)
271
+ self.assertEqual(str(cm.exception),
272
+ "exceptions must derive from BaseException")
273
+
274
+ def test_raise_invalid_class_objmode(self):
275
+ self.check_raise_invalid_class(int, flags=force_pyobj_flags)
276
+ self.check_raise_invalid_class(1, flags=force_pyobj_flags)
277
+
278
+ def test_raise_invalid_class_nopython(self):
279
+ msg = "Encountered unsupported constant type used for exception"
280
+ with self.assertRaises(errors.UnsupportedError) as raises:
281
+ self.check_raise_invalid_class(int, flags=no_pyobj_flags)
282
+ self.assertIn(msg, str(raises.exception))
283
+ with self.assertRaises(errors.UnsupportedError) as raises:
284
+ self.check_raise_invalid_class(1, flags=no_pyobj_flags)
285
+ self.assertIn(msg, str(raises.exception))
286
+
287
+ def test_raise_bare_string_nopython(self):
288
+ @njit
289
+ def foo():
290
+ raise "illegal"
291
+ msg = ("Directly raising a string constant as an exception is not "
292
+ "supported")
293
+ with self.assertRaises(errors.UnsupportedError) as raises:
294
+ foo()
295
+ self.assertIn(msg, str(raises.exception))
296
+
297
+ def check_assert_statement(self, flags):
298
+ pyfunc = assert_usecase
299
+ cfunc = jit((types.int32,), **flags)(pyfunc)
300
+ cfunc(1)
301
+ self.check_against_python(flags, pyfunc, cfunc, AssertionError, 2)
302
+
303
+ def test_assert_statement_objmode(self):
304
+ self.check_assert_statement(flags=force_pyobj_flags)
305
+
306
+ def test_assert_statement_nopython(self):
307
+ self.check_assert_statement(flags=no_pyobj_flags)
308
+
309
+ def check_raise_from_exec_string(self, flags):
310
+ # issue #3428
311
+ simple_raise = "def f(a):\n raise exc('msg', 10)"
312
+ assert_raise = "def f(a):\n assert a != 1"
313
+ py312_pep695_raise = "def f[T: int](a: T) -> T:\n assert a != 1"
314
+ py312_pep695_raise_2 = "def f[T: int\n](a: T) -> T:\n assert a != 1"
315
+ test_cases = [
316
+ (assert_raise, AssertionError),
317
+ (simple_raise, UDEArgsToSuper),
318
+ (simple_raise, UDENoArgSuper),
319
+ ]
320
+ if utils.PYVERSION >= (3, 12):
321
+ # Added for https://github.com/numba/numba/issues/9443
322
+ test_cases.append((py312_pep695_raise, AssertionError))
323
+ test_cases.append((py312_pep695_raise_2, AssertionError))
324
+ for f_text, exc in test_cases:
325
+ loc = {}
326
+ exec(f_text, {'exc': exc}, loc)
327
+ pyfunc = loc['f']
328
+ cfunc = jit((types.int32,), **flags)(pyfunc)
329
+ self.check_against_python(flags, pyfunc, cfunc, exc, 1)
330
+
331
+ def test_assert_from_exec_string_objmode(self):
332
+ self.check_raise_from_exec_string(flags=force_pyobj_flags)
333
+
334
+ def test_assert_from_exec_string_nopython(self):
335
+ self.check_raise_from_exec_string(flags=no_pyobj_flags)
336
+
337
+ def check_user_code_error_traceback(self, flags):
338
+ # this test checks that if a user tries to compile code that contains
339
+ # a bug in exception initialisation (e.g. missing arg) then this also
340
+ # has a frame injected with the location information.
341
+ pyfunc = ude_bug_usecase
342
+ cfunc = jit((), **flags)(pyfunc)
343
+ self.check_against_python(flags, pyfunc, cfunc, TypeError)
344
+
345
+ def test_user_code_error_traceback_objmode(self):
346
+ self.check_user_code_error_traceback(flags=force_pyobj_flags)
347
+
348
+ def test_user_code_error_traceback_nopython(self):
349
+ self.check_user_code_error_traceback(flags=no_pyobj_flags)
350
+
351
+ def check_raise_runtime_value(self, flags):
352
+ pyfunc = raise_runtime_value
353
+ cfunc = jit((types.string,), **flags)(pyfunc)
354
+ self.check_against_python(flags, pyfunc, cfunc, ValueError, 'hello')
355
+
356
+ def test_raise_runtime_value_objmode(self):
357
+ self.check_raise_runtime_value(flags=force_pyobj_flags)
358
+
359
+ def test_raise_runtime_value_nopython(self):
360
+ self.check_raise_runtime_value(flags=no_pyobj_flags_w_nrt)
361
+
362
+ def test_raise_runtime_value_nogil(self):
363
+ self.check_raise_runtime_value(flags=no_gil_flags)
364
+
365
+ def check_raise_instance_with_runtime_args(self, flags):
366
+ for clazz in [MyError, UDEArgsToSuper,
367
+ UDENoArgSuper]:
368
+ pyfunc = raise_instance_runtime_args(clazz)
369
+ cfunc = jit((types.int32, types.string), **flags)(pyfunc)
370
+
371
+ self.assertEqual(cfunc(0, 'test'), 0)
372
+ self.check_against_python(flags, pyfunc, cfunc, clazz, 1, 'hello')
373
+ self.check_against_python(flags, pyfunc, cfunc, ValueError, 2,
374
+ 'world')
375
+ self.check_against_python(flags, pyfunc, cfunc,
376
+ np.linalg.linalg.LinAlgError, 3, 'linalg')
377
+
378
+ def test_raise_instance_with_runtime_args_objmode(self):
379
+ self.check_raise_instance_with_runtime_args(flags=force_pyobj_flags)
380
+
381
+ def test_raise_instance_with_runtime_args_nopython(self):
382
+ self.check_raise_instance_with_runtime_args(flags=no_pyobj_flags_w_nrt)
383
+
384
+ def test_raise_instance_with_runtime_args_nogil(self):
385
+ self.check_raise_instance_with_runtime_args(flags=no_gil_flags)
386
+
387
+ def test_dynamic_raise_bad_args(self):
388
+ def raise_literal_dict():
389
+ raise ValueError({'a': 1, 'b': np.ones(4)})
390
+
391
+ def raise_range():
392
+ raise ValueError(range(3))
393
+
394
+ def raise_rng(rng):
395
+ raise ValueError(rng.bit_generator)
396
+
397
+ funcs = [
398
+ (raise_literal_dict, ()),
399
+ (raise_range, ()),
400
+ (raise_rng, (types.npy_rng,)),
401
+ ]
402
+
403
+ for pyfunc, argtypes in funcs:
404
+ msg = '.*Cannot convert native .* to a Python object.*'
405
+ with self.assertRaisesRegex(errors.TypingError, msg):
406
+ njit(argtypes)(pyfunc)
407
+
408
+ def test_dynamic_raise_dict(self):
409
+ @njit
410
+ def raise_literal_dict2():
411
+ raise ValueError({'a': 1, 'b': 3})
412
+
413
+ msg = "{a: 1, b: 3}"
414
+ with self.assertRaisesRegex(ValueError, msg):
415
+ raise_literal_dict2()
416
+
417
+ def test_disable_nrt(self):
418
+ @njit(_nrt=False)
419
+ def raise_with_no_nrt(i):
420
+ raise ValueError(i)
421
+
422
+ msg = 'NRT required but not enabled'
423
+ with self.assertRaisesRegex(errors.NumbaRuntimeError, msg):
424
+ raise_with_no_nrt(123)
425
+
426
+ def test_try_raise(self):
427
+
428
+ @njit
429
+ def raise_(a):
430
+ raise ValueError(a)
431
+
432
+ @njit
433
+ def try_raise(a):
434
+ try:
435
+ raise_(a)
436
+ except Exception:
437
+ pass
438
+ return a + 1
439
+
440
+ self.assertEqual(try_raise.py_func(3), try_raise(3))
441
+
442
+ @expected_failure_py311
443
+ @expected_failure_py312
444
+ @expected_failure_py313
445
+ def test_dynamic_raise(self):
446
+
447
+ @njit
448
+ def raise_(a):
449
+ raise ValueError(a)
450
+
451
+ @njit
452
+ def try_raise_(a):
453
+ try:
454
+ raise_(a)
455
+ except Exception:
456
+ raise ValueError(a)
457
+
458
+ args = [
459
+ 1,
460
+ 1.1,
461
+ 'hello',
462
+ np.ones(3),
463
+ [1, 2],
464
+ (1, 2),
465
+ set([1, 2]),
466
+ ]
467
+ for fn in (raise_, try_raise_):
468
+ for arg in args:
469
+ with self.assertRaises(ValueError) as e:
470
+ fn(arg)
471
+ self.assertEqual((arg,), e.exception.args)
472
+
473
+
474
+ if __name__ == '__main__':
475
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_function_type.py ADDED
@@ -0,0 +1,1408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import sys
3
+ import unittest
4
+ import types as pytypes
5
+ from numba import jit, njit, cfunc, types, int64, float64, float32, errors
6
+ from numba import literal_unroll, typeof
7
+ from numba.core.config import IS_WIN32
8
+ import ctypes
9
+ import warnings
10
+
11
+ from .support import TestCase, MemoryLeakMixin
12
+ from .support import redirect_c_stderr, captured_stderr
13
+
14
+ import numpy as np
15
+
16
+
17
+ def dump(foo): # FOR DEBUGGING, TO BE REMOVED
18
+ from numba.core import function
19
+ foo_type = function.fromobject(foo)
20
+ foo_sig = foo_type.signature()
21
+ foo.compile(foo_sig)
22
+ print('{" LLVM IR OF "+foo.__name__+" ":*^70}')
23
+ print(foo.inspect_llvm(foo_sig.args))
24
+ print('{"":*^70}')
25
+
26
+
27
+ # Decorators for transforming a Python function to different kinds of
28
+ # functions:
29
+
30
+ def mk_cfunc_func(sig):
31
+ def cfunc_func(func):
32
+ assert isinstance(func, pytypes.FunctionType), repr(func)
33
+ f = cfunc(sig)(func)
34
+ f.pyfunc = func
35
+ return f
36
+ return cfunc_func
37
+
38
+
39
+ def njit_func(func):
40
+ assert isinstance(func, pytypes.FunctionType), repr(func)
41
+ f = jit(nopython=True)(func)
42
+ f.pyfunc = func
43
+ return f
44
+
45
+
46
+ def mk_njit_with_sig_func(sig):
47
+ def njit_with_sig_func(func):
48
+ assert isinstance(func, pytypes.FunctionType), repr(func)
49
+ f = jit(sig, nopython=True)(func)
50
+ f.pyfunc = func
51
+ return f
52
+ return njit_with_sig_func
53
+
54
+
55
+ def mk_ctypes_func(sig):
56
+ def ctypes_func(func, sig=int64(int64)):
57
+ assert isinstance(func, pytypes.FunctionType), repr(func)
58
+ cfunc = mk_cfunc_func(sig)(func)
59
+ addr = cfunc._wrapper_address
60
+ if sig == int64(int64):
61
+ f = ctypes.CFUNCTYPE(ctypes.c_int64)(addr)
62
+ f.pyfunc = func
63
+ return f
64
+ raise NotImplementedError(
65
+ f'ctypes decorator for {func} with signature {sig}')
66
+ return ctypes_func
67
+
68
+
69
+ class WAP(types.WrapperAddressProtocol):
70
+ """An example implementation of wrapper address protocol.
71
+
72
+ """
73
+ def __init__(self, func, sig):
74
+ self.pyfunc = func
75
+ self.cfunc = cfunc(sig)(func)
76
+ self.sig = sig
77
+
78
+ def __wrapper_address__(self):
79
+ return self.cfunc._wrapper_address
80
+
81
+ def signature(self):
82
+ return self.sig
83
+
84
+ def __call__(self, *args, **kwargs):
85
+ return self.pyfunc(*args, **kwargs)
86
+
87
+
88
+ def mk_wap_func(sig):
89
+ def wap_func(func):
90
+ return WAP(func, sig)
91
+ return wap_func
92
+
93
+
94
+ class TestFunctionType(TestCase):
95
+ """Test first-class functions in the context of a Numba jit compiled
96
+ function.
97
+
98
+ """
99
+
100
+ def test_in__(self):
101
+ """Function is passed in as an argument.
102
+ """
103
+
104
+ def a(i):
105
+ return i + 1
106
+
107
+ def foo(f):
108
+ return 0
109
+
110
+ sig = int64(int64)
111
+
112
+ for decor in [mk_cfunc_func(sig),
113
+ njit_func,
114
+ mk_njit_with_sig_func(sig),
115
+ mk_ctypes_func(sig),
116
+ mk_wap_func(sig)]:
117
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
118
+ jit_ = jit(**jit_opts)
119
+ with self.subTest(decor=decor.__name__, jit=jit_opts):
120
+ a_ = decor(a)
121
+ self.assertEqual(jit_(foo)(a_), foo(a))
122
+
123
+ def test_in_call__(self):
124
+ """Function is passed in as an argument and called.
125
+ Also test different return values.
126
+ """
127
+
128
+ def a_i64(i):
129
+ return i + 1234567
130
+
131
+ def a_f64(i):
132
+ return i + 1.5
133
+
134
+ def a_str(i):
135
+ return "abc"
136
+
137
+ def foo(f):
138
+ return f(123)
139
+
140
+ for f, sig in [(a_i64, int64(int64)), (a_f64, float64(int64))]:
141
+ for decor in [mk_cfunc_func(sig), njit_func,
142
+ mk_njit_with_sig_func(sig),
143
+ mk_wap_func(sig)]:
144
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
145
+ jit_ = jit(**jit_opts)
146
+ with self.subTest(
147
+ sig=sig, decor=decor.__name__, jit=jit_opts):
148
+ f_ = decor(f)
149
+ self.assertEqual(jit_(foo)(f_), foo(f))
150
+
151
+ def test_in_call_out(self):
152
+ """Function is passed in as an argument, called, and returned.
153
+ """
154
+
155
+ def a(i):
156
+ return i + 1
157
+
158
+ def foo(f):
159
+ f(123)
160
+ return f
161
+
162
+ sig = int64(int64)
163
+
164
+ for decor in [mk_cfunc_func(sig), njit_func,
165
+ mk_njit_with_sig_func(sig), mk_wap_func(sig)]:
166
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
167
+ jit_ = jit(**jit_opts)
168
+ with self.subTest(decor=decor.__name__):
169
+ a_ = decor(a)
170
+ r1 = jit_(foo)(a_).pyfunc
171
+ r2 = foo(a)
172
+ self.assertEqual(r1, r2)
173
+
174
+ def test_in_seq_call(self):
175
+ """Functions are passed in as arguments, used as tuple items, and
176
+ called.
177
+
178
+ """
179
+ def a(i):
180
+ return i + 1
181
+
182
+ def b(i):
183
+ return i + 2
184
+
185
+ def foo(f, g):
186
+ r = 0
187
+ for f_ in (f, g):
188
+ r = r + f_(r)
189
+ return r
190
+
191
+ sig = int64(int64)
192
+
193
+ for decor in [mk_cfunc_func(sig), mk_wap_func(sig),
194
+ mk_njit_with_sig_func(sig)]:
195
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
196
+ jit_ = jit(**jit_opts)
197
+ with self.subTest(decor=decor.__name__):
198
+ a_ = decor(a)
199
+ b_ = decor(b)
200
+ self.assertEqual(jit_(foo)(a_, b_), foo(a, b))
201
+
202
+ def test_in_ns_seq_call(self):
203
+ """Functions are passed in as an argument and via namespace scoping
204
+ (mixed pathways), used as tuple items, and called.
205
+
206
+ """
207
+
208
+ def a(i):
209
+ return i + 1
210
+
211
+ def b(i):
212
+ return i + 2
213
+
214
+ def mkfoo(b_):
215
+ def foo(f):
216
+ r = 0
217
+ for f_ in (f, b_):
218
+ r = r + f_(r)
219
+ return r
220
+ return foo
221
+
222
+ sig = int64(int64)
223
+
224
+ for decor in [mk_cfunc_func(sig),
225
+ mk_njit_with_sig_func(sig), mk_wap_func(sig),
226
+ mk_ctypes_func(sig)][:-1]:
227
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
228
+ jit_ = jit(**jit_opts)
229
+ with self.subTest(decor=decor.__name__):
230
+ a_ = decor(a)
231
+ b_ = decor(b)
232
+ self.assertEqual(jit_(mkfoo(b_))(a_), mkfoo(b)(a))
233
+
234
+ def test_ns_call(self):
235
+ """Function is passed in via namespace scoping and called.
236
+
237
+ """
238
+
239
+ def a(i):
240
+ return i + 1
241
+
242
+ def mkfoo(a_):
243
+ def foo():
244
+ return a_(123)
245
+ return foo
246
+
247
+ sig = int64(int64)
248
+
249
+ for decor in [mk_cfunc_func(sig), njit_func,
250
+ mk_njit_with_sig_func(sig), mk_wap_func(sig)]:
251
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
252
+ jit_ = jit(**jit_opts)
253
+ with self.subTest(decor=decor.__name__):
254
+ a_ = decor(a)
255
+ self.assertEqual(jit_(mkfoo(a_))(), mkfoo(a)())
256
+
257
+ def test_ns_out(self):
258
+ """Function is passed in via namespace scoping and returned.
259
+
260
+ """
261
+ def a(i):
262
+ return i + 1
263
+
264
+ def mkfoo(a_):
265
+ def foo():
266
+ return a_
267
+ return foo
268
+
269
+ sig = int64(int64)
270
+
271
+ for decor in [mk_cfunc_func(sig), njit_func,
272
+ mk_njit_with_sig_func(sig), mk_wap_func(sig),
273
+ mk_ctypes_func(sig)][:-1]:
274
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
275
+ jit_ = jit(**jit_opts)
276
+ with self.subTest(decor=decor.__name__):
277
+ a_ = decor(a)
278
+ self.assertEqual(jit_(mkfoo(a_))().pyfunc, mkfoo(a)())
279
+
280
+ def test_ns_call_out(self):
281
+ """Function is passed in via namespace scoping, called, and then
282
+ returned.
283
+
284
+ """
285
+ def a(i):
286
+ return i + 1
287
+
288
+ def mkfoo(a_):
289
+ def foo():
290
+ a_(123)
291
+ return a_
292
+ return foo
293
+
294
+ sig = int64(int64)
295
+
296
+ for decor in [mk_cfunc_func(sig), njit_func,
297
+ mk_njit_with_sig_func(sig), mk_wap_func(sig),
298
+ mk_ctypes_func(sig)]:
299
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
300
+ jit_ = jit(**jit_opts)
301
+ with self.subTest(decor=decor.__name__):
302
+ a_ = decor(a)
303
+ self.assertEqual(jit_(mkfoo(a_))().pyfunc, mkfoo(a)())
304
+
305
+ def test_in_overload(self):
306
+ """Function is passed in as an argument and called with different
307
+ argument types.
308
+
309
+ """
310
+ def a(i):
311
+ return i + 1
312
+
313
+ def foo(f):
314
+ r1 = f(123)
315
+ r2 = f(123.45)
316
+ return (r1, r2)
317
+
318
+ for decor in [njit_func]:
319
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
320
+ jit_ = jit(**jit_opts)
321
+ with self.subTest(decor=decor.__name__):
322
+ a_ = decor(a)
323
+ self.assertEqual(jit_(foo)(a_), foo(a))
324
+
325
+ def test_ns_overload(self):
326
+ """Function is passed in via namespace scoping and called with
327
+ different argument types.
328
+
329
+ """
330
+ def a(i):
331
+ return i + 1
332
+
333
+ def mkfoo(a_):
334
+ def foo():
335
+ r1 = a_(123)
336
+ r2 = a_(123.45)
337
+ return (r1, r2)
338
+ return foo
339
+
340
+ for decor in [njit_func]:
341
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
342
+ jit_ = jit(**jit_opts)
343
+ with self.subTest(decor=decor.__name__):
344
+ a_ = decor(a)
345
+ self.assertEqual(jit_(mkfoo(a_))(), mkfoo(a)())
346
+
347
+ def test_in_choose(self):
348
+ """Functions are passed in as arguments and called conditionally.
349
+
350
+ """
351
+ def a(i):
352
+ return i + 1
353
+
354
+ def b(i):
355
+ return i + 2
356
+
357
+ def foo(a, b, choose_left):
358
+ if choose_left:
359
+ r = a(1)
360
+ else:
361
+ r = b(2)
362
+ return r
363
+
364
+ sig = int64(int64)
365
+
366
+ for decor in [mk_cfunc_func(sig), njit_func,
367
+ mk_njit_with_sig_func(sig), mk_wap_func(sig)]:
368
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
369
+ jit_ = jit(**jit_opts)
370
+ with self.subTest(decor=decor.__name__):
371
+ a_ = decor(a)
372
+ b_ = decor(b)
373
+ self.assertEqual(jit_(foo)(a_, b_, True), foo(a, b, True))
374
+ self.assertEqual(jit_(foo)(a_, b_, False),
375
+ foo(a, b, False))
376
+ self.assertNotEqual(jit_(foo)(a_, b_, True),
377
+ foo(a, b, False))
378
+
379
+ def test_ns_choose(self):
380
+ """Functions are passed in via namespace scoping and called
381
+ conditionally.
382
+
383
+ """
384
+ def a(i):
385
+ return i + 1
386
+
387
+ def b(i):
388
+ return i + 2
389
+
390
+ def mkfoo(a_, b_):
391
+ def foo(choose_left):
392
+ if choose_left:
393
+ r = a_(1)
394
+ else:
395
+ r = b_(2)
396
+ return r
397
+ return foo
398
+
399
+ sig = int64(int64)
400
+
401
+ for decor in [mk_cfunc_func(sig), njit_func,
402
+ mk_njit_with_sig_func(sig), mk_wap_func(sig)]:
403
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
404
+ jit_ = jit(**jit_opts)
405
+ with self.subTest(decor=decor.__name__):
406
+ a_ = decor(a)
407
+ b_ = decor(b)
408
+ self.assertEqual(jit_(mkfoo(a_, b_))(True),
409
+ mkfoo(a, b)(True))
410
+ self.assertEqual(jit_(mkfoo(a_, b_))(False),
411
+ mkfoo(a, b)(False))
412
+ self.assertNotEqual(jit_(mkfoo(a_, b_))(True),
413
+ mkfoo(a, b)(False))
414
+
415
+ def test_in_choose_out(self):
416
+ """Functions are passed in as arguments and returned conditionally.
417
+
418
+ """
419
+ def a(i):
420
+ return i + 1
421
+
422
+ def b(i):
423
+ return i + 2
424
+
425
+ def foo(a, b, choose_left):
426
+ if choose_left:
427
+ return a
428
+ else:
429
+ return b
430
+
431
+ sig = int64(int64)
432
+
433
+ for decor in [mk_cfunc_func(sig), njit_func,
434
+ mk_njit_with_sig_func(sig), mk_wap_func(sig)]:
435
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
436
+ jit_ = jit(**jit_opts)
437
+ with self.subTest(decor=decor.__name__):
438
+ a_ = decor(a)
439
+ b_ = decor(b)
440
+ self.assertEqual(jit_(foo)(a_, b_, True).pyfunc,
441
+ foo(a, b, True))
442
+ self.assertEqual(jit_(foo)(a_, b_, False).pyfunc,
443
+ foo(a, b, False))
444
+ self.assertNotEqual(jit_(foo)(a_, b_, True).pyfunc,
445
+ foo(a, b, False))
446
+
447
+ def test_in_choose_func_value(self):
448
+ """Functions are passed in as arguments, selected conditionally and
449
+ called.
450
+
451
+ """
452
+ def a(i):
453
+ return i + 1
454
+
455
+ def b(i):
456
+ return i + 2
457
+
458
+ def foo(a, b, choose_left):
459
+ if choose_left:
460
+ f = a
461
+ else:
462
+ f = b
463
+ return f(1)
464
+
465
+ sig = int64(int64)
466
+
467
+ for decor in [mk_cfunc_func(sig), mk_wap_func(sig), njit_func,
468
+ mk_njit_with_sig_func(sig)]:
469
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
470
+ jit_ = jit(**jit_opts)
471
+ with self.subTest(decor=decor.__name__):
472
+ a_ = decor(a)
473
+ b_ = decor(b)
474
+ self.assertEqual(jit_(foo)(a_, b_, True), foo(a, b, True))
475
+ self.assertEqual(jit_(foo)(a_, b_, False),
476
+ foo(a, b, False))
477
+ self.assertNotEqual(jit_(foo)(a_, b_, True),
478
+ foo(a, b, False))
479
+
480
+ def test_in_pick_func_call(self):
481
+ """Functions are passed in as items of tuple argument, retrieved via
482
+ indexing, and called.
483
+
484
+ """
485
+ def a(i):
486
+ return i + 1
487
+
488
+ def b(i):
489
+ return i + 2
490
+
491
+ def foo(funcs, i):
492
+ f = funcs[i]
493
+ r = f(123)
494
+ return r
495
+
496
+ sig = int64(int64)
497
+
498
+ for decor in [mk_cfunc_func(sig), mk_wap_func(sig),
499
+ mk_njit_with_sig_func(sig)]:
500
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
501
+ jit_ = jit(**jit_opts)
502
+ with self.subTest(decor=decor.__name__):
503
+ a_ = decor(a)
504
+ b_ = decor(b)
505
+ self.assertEqual(jit_(foo)((a_, b_), 0), foo((a, b), 0))
506
+ self.assertEqual(jit_(foo)((a_, b_), 1), foo((a, b), 1))
507
+ self.assertNotEqual(jit_(foo)((a_, b_), 0), foo((a, b), 1))
508
+
509
+ def test_in_iter_func_call(self):
510
+ """Functions are passed in as items of tuple argument, retrieved via
511
+ indexing, and called within a variable for-loop.
512
+
513
+ """
514
+ def a(i):
515
+ return i + 1
516
+
517
+ def b(i):
518
+ return i + 2
519
+
520
+ def foo(funcs, n):
521
+ r = 0
522
+ for i in range(n):
523
+ f = funcs[i]
524
+ r = r + f(r)
525
+ return r
526
+
527
+ sig = int64(int64)
528
+
529
+ for decor in [mk_cfunc_func(sig), mk_wap_func(sig),
530
+ mk_njit_with_sig_func(sig)]:
531
+ for jit_opts in [dict(nopython=True), dict(forceobj=True)]:
532
+ jit_ = jit(**jit_opts)
533
+ with self.subTest(decor=decor.__name__):
534
+ a_ = decor(a)
535
+ b_ = decor(b)
536
+ self.assertEqual(jit_(foo)((a_, b_), 2), foo((a, b), 2))
537
+
538
+ def test_experimental_feature_warning(self):
539
+ @jit(nopython=True)
540
+ def more(x):
541
+ return x + 1
542
+
543
+ @jit(nopython=True)
544
+ def less(x):
545
+ return x - 1
546
+
547
+ @jit(nopython=True)
548
+ def foo(sel, x):
549
+ fn = more if sel else less
550
+ return fn(x)
551
+
552
+ with warnings.catch_warnings(record=True) as ws:
553
+ warnings.simplefilter("always")
554
+ res = foo(True, 10)
555
+
556
+ self.assertEqual(res, 11)
557
+ self.assertEqual(foo(False, 10), 9)
558
+
559
+ self.assertGreaterEqual(len(ws), 1)
560
+ pat = "First-class function type feature is experimental"
561
+ for w in ws:
562
+ if pat in str(w.message):
563
+ break
564
+ else:
565
+ self.fail("missing warning")
566
+
567
+
568
+ class TestFunctionTypeExtensions(TestCase):
569
+ """Test calling external library functions within Numba jit compiled
570
+ functions.
571
+
572
+ """
573
+
574
+ def test_wrapper_address_protocol_libm(self):
575
+ """Call cos and sinf from standard math library.
576
+
577
+ """
578
+ import ctypes.util
579
+
580
+ class LibM(types.WrapperAddressProtocol):
581
+
582
+ def __init__(self, fname):
583
+ if IS_WIN32:
584
+ lib = ctypes.cdll.msvcrt
585
+ else:
586
+ libpath = ctypes.util.find_library('m')
587
+ lib = ctypes.cdll.LoadLibrary(libpath)
588
+ self.lib = lib
589
+ self._name = fname
590
+ if fname == 'cos':
591
+ # test for double-precision math function
592
+ addr = ctypes.cast(self.lib.cos, ctypes.c_voidp).value
593
+ signature = float64(float64)
594
+ elif fname == 'sinf':
595
+ # test for single-precision math function
596
+ # Other 32/64 bit platforms define sinf as the
597
+ # single-precision sin function
598
+ addr = ctypes.cast(self.lib.sinf, ctypes.c_voidp).value
599
+ signature = float32(float32)
600
+ else:
601
+ raise NotImplementedError(
602
+ f'wrapper address of `{fname}`'
603
+ f' with signature `{signature}`')
604
+ self._signature = signature
605
+ self._address = addr
606
+
607
+ def __repr__(self):
608
+ return f'{type(self).__name__}({self._name!r})'
609
+
610
+ def __wrapper_address__(self):
611
+ return self._address
612
+
613
+ def signature(self):
614
+ return self._signature
615
+
616
+ mycos = LibM('cos')
617
+ mysin = LibM('sinf')
618
+
619
+ def myeval(f, x):
620
+ return f(x)
621
+
622
+ # Not testing forceobj=True as it requires implementing
623
+ # LibM.__call__ using ctypes which would be out-of-scope here.
624
+ for jit_opts in [dict(nopython=True)]:
625
+ jit_ = jit(**jit_opts)
626
+ with self.subTest(jit=jit_opts):
627
+ if mycos.signature() is not None:
628
+ self.assertEqual(jit_(myeval)(mycos, 0.0), 1.0)
629
+ if mysin.signature() is not None:
630
+ self.assertEqual(jit_(myeval)(mysin, float32(0.0)), 0.0)
631
+
632
+ def test_compilation_results(self):
633
+ """Turn the existing compilation results of a dispatcher instance to
634
+ first-class functions with precise types.
635
+ """
636
+
637
+ @jit(nopython=True)
638
+ def add_template(x, y):
639
+ return x + y
640
+
641
+ # Trigger compilations
642
+ self.assertEqual(add_template(1, 2), 3)
643
+ self.assertEqual(add_template(1.2, 3.4), 4.6)
644
+
645
+ cres1, cres2 = add_template.overloads.values()
646
+
647
+ # Turn compilation results into first-class functions
648
+ iadd = types.CompileResultWAP(cres1)
649
+ fadd = types.CompileResultWAP(cres2)
650
+
651
+ @jit(nopython=True)
652
+ def foo(add, x, y):
653
+ return add(x, y)
654
+
655
+ @jit(forceobj=True)
656
+ def foo_obj(add, x, y):
657
+ return add(x, y)
658
+
659
+ self.assertEqual(foo(iadd, 3, 4), 7)
660
+ self.assertEqual(foo(fadd, 3.4, 4.5), 7.9)
661
+
662
+ self.assertEqual(foo_obj(iadd, 3, 4), 7)
663
+ self.assertEqual(foo_obj(fadd, 3.4, 4.5), 7.9)
664
+
665
+
666
+ class TestMiscIssues(TestCase):
667
+ """Test issues of using first-class functions in the context of Numba
668
+ jit compiled functions.
669
+
670
+ """
671
+
672
+ def test_issue_3405_using_cfunc(self):
673
+
674
+ @cfunc('int64()')
675
+ def a():
676
+ return 2
677
+
678
+ @cfunc('int64()')
679
+ def b():
680
+ return 3
681
+
682
+ def g(arg):
683
+ if arg:
684
+ f = a
685
+ else:
686
+ f = b
687
+ return f()
688
+
689
+ self.assertEqual(jit(nopython=True)(g)(True), 2)
690
+ self.assertEqual(jit(nopython=True)(g)(False), 3)
691
+
692
+ def test_issue_3405_using_njit(self):
693
+
694
+ @jit(nopython=True)
695
+ def a():
696
+ return 2
697
+
698
+ @jit(nopython=True)
699
+ def b():
700
+ return 3
701
+
702
+ def g(arg):
703
+ if not arg:
704
+ f = b
705
+ else:
706
+ f = a
707
+ return f()
708
+
709
+ self.assertEqual(jit(nopython=True)(g)(True), 2)
710
+ self.assertEqual(jit(nopython=True)(g)(False), 3)
711
+
712
+ def test_pr4967_example(self):
713
+
714
+ @cfunc('int64(int64)')
715
+ def a(i):
716
+ return i + 1
717
+
718
+ @cfunc('int64(int64)')
719
+ def b(i):
720
+ return i + 2
721
+
722
+ @jit(nopython=True)
723
+ def foo(f, g):
724
+ i = f(2)
725
+ seq = (f, g)
726
+ for fun in seq:
727
+ i += fun(i)
728
+ return i
729
+
730
+ a_ = a._pyfunc
731
+ b_ = b._pyfunc
732
+ self.assertEqual(foo(a, b),
733
+ a_(2) + a_(a_(2)) + b_(a_(2) + a_(a_(2))))
734
+
735
+ def test_pr4967_array(self):
736
+ import numpy as np
737
+
738
+ @cfunc("intp(intp[:], float64[:])")
739
+ def foo1(x, y):
740
+ return x[0] + y[0]
741
+
742
+ @cfunc("intp(intp[:], float64[:])")
743
+ def foo2(x, y):
744
+ return x[0] - y[0]
745
+
746
+ def bar(fx, fy, i):
747
+ a = np.array([10], dtype=np.intp)
748
+ b = np.array([12], dtype=np.float64)
749
+ if i == 0:
750
+ f = fx
751
+ elif i == 1:
752
+ f = fy
753
+ else:
754
+ return
755
+ return f(a, b)
756
+
757
+ r = jit(nopython=True, no_cfunc_wrapper=True)(bar)(foo1, foo2, 0)
758
+ self.assertEqual(r, bar(foo1, foo2, 0))
759
+ self.assertNotEqual(r, bar(foo1, foo2, 1))
760
+
761
+ def test_reference_example(self):
762
+ import numba
763
+
764
+ @numba.njit
765
+ def composition(funcs, x):
766
+ r = x
767
+ for f in funcs[::-1]:
768
+ r = f(r)
769
+ return r
770
+
771
+ @numba.cfunc("double(double)")
772
+ def a(x):
773
+ return x + 1.0
774
+
775
+ @numba.njit()
776
+ def b(x):
777
+ return x * x
778
+
779
+ r = composition((a, b, b, a), 0.5)
780
+ self.assertEqual(r, (0.5 + 1.0) ** 4 + 1.0)
781
+
782
+ r = composition((b, a, b, b, a), 0.5)
783
+ self.assertEqual(r, ((0.5 + 1.0) ** 4 + 1.0) ** 2)
784
+
785
+ def test_apply_function_in_function(self):
786
+
787
+ def foo(f, f_inner):
788
+ return f(f_inner)
789
+
790
+ @cfunc('int64(float64)')
791
+ def f_inner(i):
792
+ return int64(i * 3)
793
+
794
+ @cfunc(int64(types.FunctionType(f_inner._sig)))
795
+ def f(f_inner):
796
+ return f_inner(123.4)
797
+
798
+ self.assertEqual(jit(nopython=True)(foo)(f, f_inner),
799
+ foo(f._pyfunc, f_inner._pyfunc))
800
+
801
+ def test_function_with_none_argument(self):
802
+
803
+ @cfunc(int64(types.none))
804
+ def a(i):
805
+ return 1
806
+
807
+ @jit(nopython=True)
808
+ def foo(f):
809
+ return f(None)
810
+
811
+ self.assertEqual(foo(a), 1)
812
+
813
+ def test_constant_functions(self):
814
+
815
+ @jit(nopython=True)
816
+ def a():
817
+ return 123
818
+
819
+ @jit(nopython=True)
820
+ def b():
821
+ return 456
822
+
823
+ @jit(nopython=True)
824
+ def foo():
825
+ return a() + b()
826
+
827
+ r = foo()
828
+ if r != 123 + 456:
829
+ print(foo.overloads[()].library.get_llvm_str())
830
+ self.assertEqual(r, 123 + 456)
831
+
832
+ def test_generators(self):
833
+
834
+ @jit(forceobj=True)
835
+ def gen(xs):
836
+ for x in xs:
837
+ x += 1
838
+ yield x
839
+
840
+ @jit(forceobj=True)
841
+ def con(gen_fn, xs):
842
+ return [it for it in gen_fn(xs)]
843
+
844
+ self.assertEqual(con(gen, (1, 2, 3)), [2, 3, 4])
845
+
846
+ @jit(nopython=True)
847
+ def gen_(xs):
848
+ for x in xs:
849
+ x += 1
850
+ yield x
851
+ self.assertEqual(con(gen_, (1, 2, 3)), [2, 3, 4])
852
+
853
+ def test_jit_support(self):
854
+
855
+ @jit(nopython=True)
856
+ def foo(f, x):
857
+ return f(x)
858
+
859
+ @jit()
860
+ def a(x):
861
+ return x + 1
862
+
863
+ @jit()
864
+ def a2(x):
865
+ return x - 1
866
+
867
+ @jit()
868
+ def b(x):
869
+ return x + 1.5
870
+
871
+ self.assertEqual(foo(a, 1), 2)
872
+ a2(5) # pre-compile
873
+ self.assertEqual(foo(a2, 2), 1)
874
+ self.assertEqual(foo(a2, 3), 2)
875
+ self.assertEqual(foo(a, 2), 3)
876
+ self.assertEqual(foo(a, 1.5), 2.5)
877
+ self.assertEqual(foo(a2, 1), 0)
878
+ self.assertEqual(foo(a, 2.5), 3.5)
879
+ self.assertEqual(foo(b, 1.5), 3.0)
880
+ self.assertEqual(foo(b, 1), 2.5)
881
+
882
+ def test_signature_mismatch(self):
883
+ @jit(nopython=True)
884
+ def f1(x):
885
+ return x
886
+
887
+ @jit(nopython=True)
888
+ def f2(x):
889
+ return x
890
+
891
+ @jit(nopython=True)
892
+ def foo(disp1, disp2, sel):
893
+ if sel == 1:
894
+ fn = disp1
895
+ else:
896
+ fn = disp2
897
+ return fn([1]), fn(2)
898
+
899
+ with self.assertRaises(errors.UnsupportedError) as cm:
900
+ foo(f1, f2, sel=1)
901
+ self.assertRegex(
902
+ str(cm.exception), 'mismatch of function types:')
903
+
904
+ # this works because `sel == 1` condition is optimized away:
905
+ self.assertEqual(foo(f1, f1, sel=1), ([1], 2))
906
+
907
+ def test_unique_dispatcher(self):
908
+ # In general, the type of a dispatcher instance is imprecise
909
+ # and when used as an input to type-inference, the typing will
910
+ # likely fail. However, if a dispatcher instance contains
911
+ # exactly one overload and compilation is disabled for the dispatcher,
912
+ # then the type of dispatcher instance is interpreted as precise
913
+ # and is transformed to a FunctionType instance with the defined
914
+ # signature of the single overload.
915
+
916
+ def foo_template(funcs, x):
917
+ r = x
918
+ for f in funcs:
919
+ r = f(r)
920
+ return r
921
+
922
+ a = jit(nopython=True)(lambda x: x + 1)
923
+ b = jit(nopython=True)(lambda x: x + 2)
924
+ foo = jit(nopython=True)(foo_template)
925
+
926
+ # compiling and disabling compilation for `a` is sufficient,
927
+ # `b` will inherit its type from the container Tuple type
928
+ a(0)
929
+ a.disable_compile()
930
+
931
+ r = foo((a, b), 0)
932
+ self.assertEqual(r, 3)
933
+ # the Tuple type of foo's first argument is a precise FunctionType:
934
+ self.assertEqual(foo.signatures[0][0].dtype.is_precise(), True)
935
+
936
+ def test_zero_address(self):
937
+
938
+ sig = int64()
939
+
940
+ @cfunc(sig)
941
+ def test():
942
+ return 123
943
+
944
+ class Good(types.WrapperAddressProtocol):
945
+ """A first-class function type with valid address.
946
+ """
947
+
948
+ def __wrapper_address__(self):
949
+ return test.address
950
+
951
+ def signature(self):
952
+ return sig
953
+
954
+ class Bad(types.WrapperAddressProtocol):
955
+ """A first-class function type with invalid 0 address.
956
+ """
957
+
958
+ def __wrapper_address__(self):
959
+ return 0
960
+
961
+ def signature(self):
962
+ return sig
963
+
964
+ class BadToGood(types.WrapperAddressProtocol):
965
+ """A first-class function type with invalid address that is
966
+ recovered to a valid address.
967
+ """
968
+
969
+ counter = -1
970
+
971
+ def __wrapper_address__(self):
972
+ self.counter += 1
973
+ return test.address * min(1, self.counter)
974
+
975
+ def signature(self):
976
+ return sig
977
+
978
+ good = Good()
979
+ bad = Bad()
980
+ bad2good = BadToGood()
981
+
982
+ @jit(int64(sig.as_type()))
983
+ def foo(func):
984
+ return func()
985
+
986
+ @jit(int64())
987
+ def foo_good():
988
+ return good()
989
+
990
+ @jit(int64())
991
+ def foo_bad():
992
+ return bad()
993
+
994
+ @jit(int64())
995
+ def foo_bad2good():
996
+ return bad2good()
997
+
998
+ self.assertEqual(foo(good), 123)
999
+
1000
+ self.assertEqual(foo_good(), 123)
1001
+
1002
+ with self.assertRaises(ValueError) as cm:
1003
+ foo(bad)
1004
+ self.assertRegex(
1005
+ str(cm.exception),
1006
+ 'wrapper address of <.*> instance must be a positive')
1007
+
1008
+ with self.assertRaises(RuntimeError) as cm:
1009
+ foo_bad()
1010
+ self.assertRegex(
1011
+ str(cm.exception), r'.* function address is null')
1012
+
1013
+ self.assertEqual(foo_bad2good(), 123)
1014
+
1015
+ def test_issue_5470(self):
1016
+
1017
+ @njit()
1018
+ def foo1():
1019
+ return 10
1020
+
1021
+ @njit()
1022
+ def foo2():
1023
+ return 20
1024
+
1025
+ formulae_foo = (foo1, foo1)
1026
+
1027
+ @njit()
1028
+ def bar_scalar(f1, f2):
1029
+ return f1() + f2()
1030
+
1031
+ @njit()
1032
+ def bar():
1033
+ return bar_scalar(*formulae_foo)
1034
+
1035
+ self.assertEqual(bar(), 20)
1036
+
1037
+ formulae_foo = (foo1, foo2)
1038
+
1039
+ @njit()
1040
+ def bar():
1041
+ return bar_scalar(*formulae_foo)
1042
+
1043
+ self.assertEqual(bar(), 30)
1044
+
1045
+ def test_issue_5540(self):
1046
+
1047
+ @njit(types.int64(types.int64))
1048
+ def foo(x):
1049
+ return x + 1
1050
+
1051
+ @njit
1052
+ def bar_bad(foos):
1053
+ f = foos[0]
1054
+ return f(x=1)
1055
+
1056
+ @njit
1057
+ def bar_good(foos):
1058
+ f = foos[0]
1059
+ return f(1)
1060
+
1061
+ self.assertEqual(bar_good((foo, )), 2)
1062
+
1063
+ # new/old style error handling
1064
+ with self.assertRaises((errors.UnsupportedError,
1065
+ errors.TypingError)) as cm:
1066
+ bar_bad((foo, ))
1067
+
1068
+ self.assertRegex(
1069
+ str(cm.exception),
1070
+ r'.*first-class function call cannot use keyword arguments')
1071
+
1072
+ def test_issue_5615(self):
1073
+
1074
+ @njit
1075
+ def foo1(x):
1076
+ return x + 1
1077
+
1078
+ @njit
1079
+ def foo2(x):
1080
+ return x + 2
1081
+
1082
+ @njit
1083
+ def bar(fcs):
1084
+ x = 0
1085
+ a = 10
1086
+ i, j = fcs[0]
1087
+ x += i(j(a))
1088
+ for t in literal_unroll(fcs):
1089
+ i, j = t
1090
+ x += i(j(a))
1091
+ return x
1092
+
1093
+ tup = ((foo1, foo2), (foo2, foo1))
1094
+
1095
+ self.assertEqual(bar(tup), 39)
1096
+
1097
+ def test_issue_5685(self):
1098
+
1099
+ @njit
1100
+ def foo1():
1101
+ return 1
1102
+
1103
+ @njit
1104
+ def foo2(x):
1105
+ return x + 1
1106
+
1107
+ @njit
1108
+ def foo3(x):
1109
+ return x + 2
1110
+
1111
+ @njit
1112
+ def bar(fcs):
1113
+ r = 0
1114
+ for pair in literal_unroll(fcs):
1115
+ f1, f2 = pair
1116
+ r += f1() + f2(2)
1117
+ return r
1118
+
1119
+ self.assertEqual(bar(((foo1, foo2),)), 4)
1120
+ self.assertEqual(bar(((foo1, foo2), (foo1, foo3))), 9) # reproducer
1121
+
1122
+
1123
+ class TestBasicSubtyping(TestCase):
1124
+ def test_basic(self):
1125
+ """
1126
+ Test that a dispatcher object *with* a pre-compiled overload
1127
+ can be used as input to another function with locked-down signature
1128
+ """
1129
+ a = 1
1130
+
1131
+ @njit
1132
+ def foo(x):
1133
+ return x + 1
1134
+
1135
+ foo(a)
1136
+ int_int_fc = types.FunctionType(types.int64(types.int64,))
1137
+
1138
+ @njit(types.int64(int_int_fc))
1139
+ def bar(fc):
1140
+ return fc(a)
1141
+
1142
+ self.assertEqual(bar(foo), foo(a))
1143
+
1144
+ def test_basic2(self):
1145
+ """
1146
+ Test that a dispatcher object *without* a pre-compiled overload
1147
+ can be used as input to another function with locked-down signature
1148
+ """
1149
+ a = 1
1150
+
1151
+ @njit
1152
+ def foo(x):
1153
+ return x + 1
1154
+
1155
+ int_int_fc = types.FunctionType(types.int64(types.int64,))
1156
+
1157
+ @njit(types.int64(int_int_fc))
1158
+ def bar(fc):
1159
+ return fc(a)
1160
+
1161
+ self.assertEqual(bar(foo), foo(a))
1162
+
1163
+ def test_basic3(self):
1164
+ """
1165
+ Test that a dispatcher object *without* a pre-compiled overload
1166
+ can be used as input to another function with locked-down signature and
1167
+ that it behaves as a truly generic function (foo1 does not get locked)
1168
+ """
1169
+ a = 1
1170
+
1171
+ @njit
1172
+ def foo1(x):
1173
+ return x + 1
1174
+
1175
+ @njit
1176
+ def foo2(x):
1177
+ return x + 2
1178
+
1179
+ int_int_fc = types.FunctionType(types.int64(types.int64,))
1180
+
1181
+ @njit(types.int64(int_int_fc))
1182
+ def bar(fc):
1183
+ return fc(a)
1184
+
1185
+ self.assertEqual(bar(foo1) + 1, bar(foo2))
1186
+
1187
+ def test_basic4(self):
1188
+ """
1189
+ Test that a dispatcher object can be used as input to another
1190
+ function with signature as part of a tuple
1191
+ """
1192
+ a = 1
1193
+
1194
+ @njit
1195
+ def foo1(x):
1196
+ return x + 1
1197
+
1198
+ @njit
1199
+ def foo2(x):
1200
+ return x + 2
1201
+
1202
+ tup = (foo1, foo2)
1203
+ int_int_fc = types.FunctionType(types.int64(types.int64,))
1204
+
1205
+ @njit(types.int64(types.UniTuple(int_int_fc, 2)))
1206
+ def bar(fcs):
1207
+ x = 0
1208
+ for i in range(2):
1209
+ x += fcs[i](a)
1210
+ return x
1211
+ self.assertEqual(bar(tup), foo1(a) + foo2(a))
1212
+
1213
+ def test_basic5(self):
1214
+ a = 1
1215
+
1216
+ @njit
1217
+ def foo1(x):
1218
+ return x + 1
1219
+
1220
+ @njit
1221
+ def foo2(x):
1222
+ return x + 2
1223
+
1224
+ @njit
1225
+ def bar1(x):
1226
+ return x / 10
1227
+
1228
+ @njit
1229
+ def bar2(x):
1230
+ return x / 1000
1231
+
1232
+ tup = (foo1, foo2)
1233
+ tup_bar = (bar1, bar2)
1234
+ int_int_fc = types.FunctionType(types.int64(types.int64,))
1235
+
1236
+ flt_flt_fc = types.FunctionType(types.float64(types.float64,))
1237
+
1238
+ @njit((types.UniTuple(int_int_fc, 2), types.UniTuple(flt_flt_fc, 2)))
1239
+ def bar(fcs, ffs):
1240
+ x = 0
1241
+ for i in range(2):
1242
+ x += fcs[i](a)
1243
+ for fn in ffs:
1244
+ x += fn(a)
1245
+ return x
1246
+
1247
+ got = bar(tup, tup_bar)
1248
+ expected = foo1(a) + foo2(a) + bar1(a) + bar2(a)
1249
+ self.assertEqual(got, expected)
1250
+
1251
+
1252
+ class TestMultiFunctionType(MemoryLeakMixin, TestCase):
1253
+
1254
+ def test_base(self):
1255
+ # The test is adapted from https://github.com/numba/numba/issues/9071
1256
+ nb_array = typeof(np.ones(2))
1257
+ callee_int_type = types.FunctionType(int64(int64))
1258
+ sig_int = int64(callee_int_type, int64)
1259
+ callee_array_type = types.FunctionType(float64(nb_array))
1260
+ sig_array = float64(callee_array_type, nb_array)
1261
+
1262
+ @njit([sig_int, sig_array])
1263
+ def caller(callee, a):
1264
+ return callee(a)
1265
+
1266
+ @njit
1267
+ def callee_int(b):
1268
+ return b
1269
+
1270
+ @njit
1271
+ def callee_array(c):
1272
+ return c.sum()
1273
+
1274
+ b = 1
1275
+ c = np.ones(2)
1276
+
1277
+ self.assertEqual(caller(callee_int, b), b)
1278
+ self.assertEqual(caller(callee_array, c), c.sum())
1279
+
1280
+
1281
+ class TestInliningFunctionType(MemoryLeakMixin, TestCase):
1282
+ def count_num_bb_in_cfg(self, dispatcher):
1283
+ dot = dispatcher.inspect_cfg(dispatcher.signatures[0]).dot
1284
+ num_of_nodes = re.findall(r"Node0x[0-9a-z]+", dot)
1285
+ return len(num_of_nodes)
1286
+
1287
+ def test_inlining_global_dispatcher(self):
1288
+ @njit
1289
+ def add(x, y):
1290
+ return x + y
1291
+
1292
+ fnty = types.FunctionType(int64(int64, int64))
1293
+
1294
+ @njit(int64(fnty, int64, int64))
1295
+ def callme(fn, x, y):
1296
+ c = 0
1297
+ for i in range(100):
1298
+ c += fn(x, y)
1299
+ return c
1300
+
1301
+ @njit
1302
+ def bar(x, y):
1303
+ return callme(add, x, y)
1304
+
1305
+ res = bar(123, 321)
1306
+ self.assertEqual(100 * (123 + 321), res)
1307
+ # There's only one BB because LLVM will be able to fully optimize
1308
+ # the reduce-add loop if add() is properly inlined.
1309
+ self.assertEqual(self.count_num_bb_in_cfg(bar), 1)
1310
+
1311
+ def test_not_inlining_dispatcher_args(self):
1312
+ @njit
1313
+ def add(x, y):
1314
+ return x + y
1315
+
1316
+ fnty = types.FunctionType(int64(int64, int64))
1317
+
1318
+ @njit(int64(fnty, int64, int64))
1319
+ def callme(fn, x, y):
1320
+ c = 0
1321
+ for i in range(100):
1322
+ c += fn(x, y)
1323
+ return c
1324
+
1325
+ res = callme(add, 123, 321)
1326
+
1327
+ self.assertEqual(100 * (123 + 321), res)
1328
+ # Since add() is not inline-able. The number of BB will be greater
1329
+ # than 1. See test_inlining_global_dispatcher().
1330
+ self.assertGreater(self.count_num_bb_in_cfg(callme), 1)
1331
+
1332
+
1333
+ class TestExceptionInFunctionType(MemoryLeakMixin, TestCase):
1334
+ def test_exception_raising(self):
1335
+ class MyError(Exception):
1336
+ pass
1337
+
1338
+ @njit
1339
+ def add(x, y):
1340
+ res = x + y
1341
+ if res > 100:
1342
+ raise MyError(res)
1343
+ return res
1344
+
1345
+ fnty = types.FunctionType(int64(int64, int64))
1346
+
1347
+ @njit(int64(fnty))
1348
+ def callme(fn):
1349
+ c = 0
1350
+ for i in range(100):
1351
+ c = fn(c, i)
1352
+ return c
1353
+
1354
+ @njit
1355
+ def bar():
1356
+ return callme(add)
1357
+
1358
+ # Pass Dispatcher as a global reference
1359
+ with self.assertRaises(MyError) as exc:
1360
+ bar()
1361
+ self.assertEqual(exc.exception.args, (105,))
1362
+
1363
+ # Pass Dispatcher by argument
1364
+ with self.assertRaises(MyError) as exc:
1365
+ callme(add)
1366
+ self.assertEqual(exc.exception.args, (105,))
1367
+
1368
+ def test_exception_ignored_in_cfunc(self):
1369
+ class MyError(Exception):
1370
+ pass
1371
+
1372
+ @njit
1373
+ def add(x, y):
1374
+ res = x + y
1375
+ if res > 100:
1376
+ raise MyError(res)
1377
+ return res
1378
+
1379
+ fnty = types.FunctionType(int64(int64, int64))
1380
+
1381
+ @njit(int64(fnty, int64, int64))
1382
+ def callme(fn, x, y):
1383
+ return fn(x, y)
1384
+
1385
+ # Cfunc as argument will ignore raised exception
1386
+ @cfunc(int64(int64, int64))
1387
+ def c_add(x, y):
1388
+ return add(x, y)
1389
+
1390
+ self.assertEqual(callme(c_add, 12, 32), 44)
1391
+
1392
+ # If unittest is buffering (-b), the message goes to Python level stderr
1393
+ # otherwise, it goes to C stderr.
1394
+ with redirect_c_stderr() as c_stderr, captured_stderr() as stderr:
1395
+ # raise ignored and result is garbage
1396
+ callme(c_add, 100, 1)
1397
+ sys.stderr.flush()
1398
+
1399
+ err = c_stderr.read()
1400
+ if not err:
1401
+ err = stderr.getvalue()
1402
+
1403
+ self.assertIn("Exception ignored in:", err)
1404
+ self.assertIn(str(MyError(101)), err)
1405
+
1406
+
1407
+ if __name__ == '__main__':
1408
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_gdb_bindings.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests gdb bindings
3
+ """
4
+ import os
5
+ import platform
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ import threading
10
+ from itertools import permutations
11
+
12
+ from numba import njit, gdb, gdb_init, gdb_breakpoint, prange
13
+ from numba.core import errors
14
+ from numba import jit
15
+
16
+ from numba.tests.support import (TestCase, captured_stdout, tag,
17
+ skip_parfors_unsupported)
18
+ from numba.tests.gdb_support import needs_gdb
19
+ import unittest
20
+
21
+
22
+ _platform = sys.platform
23
+
24
+ _unix_like = (_platform.startswith('linux')
25
+ or _platform.startswith('darwin')
26
+ or ('bsd' in _platform))
27
+
28
+ unix_only = unittest.skipUnless(_unix_like, "unix-like OS is required")
29
+ not_unix = unittest.skipIf(_unix_like, "non unix-like OS is required")
30
+
31
+ _arch_name = platform.machine()
32
+ _is_arm = _arch_name in {'aarch64', 'armv7l'}
33
+ not_arm = unittest.skipIf(_is_arm, "testing disabled on ARM")
34
+
35
+ _gdb_cond = os.environ.get('GDB_TEST', None) == '1'
36
+ needs_gdb_harness = unittest.skipUnless(_gdb_cond, "needs gdb harness")
37
+
38
+ long_running = tag('long_running')
39
+
40
+ _dbg_njit = njit(debug=True)
41
+ _dbg_jit = jit(forceobj=True, debug=True)
42
+
43
+
44
+ def impl_gdb_call(a):
45
+ gdb('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q')
46
+ b = a + 1
47
+ c = a * 2.34
48
+ d = (a, b, c)
49
+ print(a, b, c, d)
50
+
51
+
52
+ def impl_gdb_call_w_bp(a):
53
+ gdb_init('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q')
54
+ b = a + 1
55
+ c = a * 2.34
56
+ d = (a, b, c)
57
+ gdb_breakpoint()
58
+ print(a, b, c, d)
59
+
60
+
61
+ def impl_gdb_split_init_and_break_w_parallel(a):
62
+ gdb_init('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q')
63
+ a += 3
64
+ for i in prange(4):
65
+ b = a + 1
66
+ c = a * 2.34
67
+ d = (a, b, c)
68
+ gdb_breakpoint()
69
+ print(a, b, c, d)
70
+
71
+
72
+ @not_arm
73
+ @unix_only
74
+ class TestGdbBindImpls(TestCase):
75
+ """
76
+ Contains unit test implementations for gdb binding testing. Test must be
77
+ decorated with `@needs_gdb_harness` to prevent their running under normal
78
+ test conditions, the test methods must also end with `_impl` to be
79
+ considered for execution. The tests themselves are invoked by the
80
+ `TestGdbBinding` test class through the parsing of this class for test
81
+ methods and then running the discovered tests in a separate process. Test
82
+ names not including the word `quick` will be tagged as @tag('long_running')
83
+ """
84
+
85
+ @needs_gdb_harness
86
+ def test_gdb_cmd_lang_cpython_quick_impl(self):
87
+ with captured_stdout():
88
+ impl_gdb_call(10)
89
+
90
+ @needs_gdb_harness
91
+ def test_gdb_cmd_lang_nopython_quick_impl(self):
92
+ with captured_stdout():
93
+ _dbg_njit(impl_gdb_call)(10)
94
+
95
+ @needs_gdb_harness
96
+ def test_gdb_cmd_lang_objmode_quick_impl(self):
97
+ with captured_stdout():
98
+ _dbg_jit(impl_gdb_call)(10)
99
+
100
+ @needs_gdb_harness
101
+ def test_gdb_split_init_and_break_cpython_impl(self):
102
+ with captured_stdout():
103
+ impl_gdb_call_w_bp(10)
104
+
105
+ @needs_gdb_harness
106
+ def test_gdb_split_init_and_break_nopython_impl(self):
107
+ with captured_stdout():
108
+ _dbg_njit(impl_gdb_call_w_bp)(10)
109
+
110
+ @needs_gdb_harness
111
+ def test_gdb_split_init_and_break_objmode_impl(self):
112
+ with captured_stdout():
113
+ _dbg_jit(impl_gdb_call_w_bp)(10)
114
+
115
+ @skip_parfors_unsupported
116
+ @needs_gdb_harness
117
+ def test_gdb_split_init_and_break_w_parallel_cpython_impl(self):
118
+ with captured_stdout():
119
+ impl_gdb_split_init_and_break_w_parallel(10)
120
+
121
+ @skip_parfors_unsupported
122
+ @needs_gdb_harness
123
+ def test_gdb_split_init_and_break_w_parallel_nopython_impl(self):
124
+ with captured_stdout():
125
+ _dbg_njit(impl_gdb_split_init_and_break_w_parallel)(10)
126
+
127
+ @skip_parfors_unsupported
128
+ @needs_gdb_harness
129
+ def test_gdb_split_init_and_break_w_parallel_objmode_impl(self):
130
+ with captured_stdout():
131
+ _dbg_jit(impl_gdb_split_init_and_break_w_parallel)(10)
132
+
133
+
134
+ @not_arm
135
+ @unix_only
136
+ @needs_gdb
137
+ class TestGdbBinding(TestCase):
138
+ """
139
+ This test class is used to generate tests which will run the test cases
140
+ defined in TestGdbBindImpls in isolated subprocesses, this is for safety
141
+ in case something goes awry.
142
+ """
143
+
144
+ # test mutates env
145
+ _numba_parallel_test_ = False
146
+
147
+ _DEBUG = True
148
+
149
+ def run_cmd(self, cmdline, env, kill_is_ok=False):
150
+ popen = subprocess.Popen(cmdline,
151
+ stdout=subprocess.PIPE,
152
+ stderr=subprocess.PIPE,
153
+ env=env,
154
+ shell=True)
155
+ # finish in 20s or kill it, there's no work being done
156
+
157
+ def kill():
158
+ popen.stdout.flush()
159
+ popen.stderr.flush()
160
+ popen.kill()
161
+ timeout = threading.Timer(20., kill)
162
+ try:
163
+ timeout.start()
164
+ out, err = popen.communicate()
165
+ retcode = popen.returncode
166
+ if retcode != 0:
167
+ raise AssertionError(
168
+ "process failed with code %s: "
169
+ "stderr follows\n%s\n"
170
+ "stdout :%s" % (retcode, err.decode(), out.decode()))
171
+ return out.decode(), err.decode()
172
+ finally:
173
+ timeout.cancel()
174
+ return None, None
175
+
176
+ def run_test_in_separate_process(self, test, **kwargs):
177
+ env_copy = os.environ.copy()
178
+ env_copy['NUMBA_OPT'] = '1'
179
+ # Set GDB_TEST to permit the execution of tests decorated with
180
+ # @needs_gdb_harness
181
+ env_copy['GDB_TEST'] = '1'
182
+ cmdline = [sys.executable, "-m", "numba.runtests", test]
183
+ return self.run_cmd(' '.join(cmdline), env_copy, **kwargs)
184
+
185
+ @classmethod
186
+ def _inject(cls, name):
187
+ themod = TestGdbBindImpls.__module__
188
+ thecls = TestGdbBindImpls.__name__
189
+ # strip impl
190
+ assert name.endswith('_impl')
191
+ methname = name.replace('_impl', '')
192
+ injected_method = '%s.%s.%s' % (themod, thecls, name)
193
+
194
+ def test_template(self):
195
+ o, e = self.run_test_in_separate_process(injected_method)
196
+ dbgmsg = f'\nSTDOUT={o}\nSTDERR={e}\n'
197
+ # If the test was skipped in the subprocess, then mark this as a
198
+ # skipped test.
199
+ m = re.search(r"\.\.\. skipped '(.*?)'", e)
200
+ if m is not None:
201
+ self.skipTest(m.group(1))
202
+ self.assertIn('GNU gdb', o, msg=dbgmsg)
203
+ self.assertIn('OK', e, msg=dbgmsg)
204
+ self.assertNotIn('FAIL', e, msg=dbgmsg)
205
+ self.assertNotIn('ERROR', e, msg=dbgmsg)
206
+ if 'quick' in name:
207
+ setattr(cls, methname, test_template)
208
+ else:
209
+ setattr(cls, methname, long_running(test_template))
210
+
211
+ @classmethod
212
+ def generate(cls):
213
+ for name in dir(TestGdbBindImpls):
214
+ if name.startswith('test_gdb'):
215
+ cls._inject(name)
216
+
217
+
218
+ TestGdbBinding.generate()
219
+
220
+
221
+ @not_arm
222
+ @unix_only
223
+ @needs_gdb
224
+ class TestGdbMisc(TestCase):
225
+
226
+ @long_running
227
+ def test_call_gdb_twice(self):
228
+ def gen(f1, f2):
229
+ @njit
230
+ def impl():
231
+ a = 1
232
+ f1()
233
+ b = 2
234
+ f2()
235
+ return a + b
236
+ return impl
237
+
238
+ msg_head = "Calling either numba.gdb() or numba.gdb_init() more than"
239
+
240
+ def check(func):
241
+ with self.assertRaises(errors.UnsupportedError) as raises:
242
+ func()
243
+ self.assertIn(msg_head, str(raises.exception))
244
+
245
+ for g1, g2 in permutations([gdb, gdb_init]):
246
+ func = gen(g1, g2)
247
+ check(func)
248
+
249
+ @njit
250
+ def use_globals():
251
+ a = 1
252
+ gdb()
253
+ b = 2
254
+ gdb_init()
255
+ return a + b
256
+
257
+ check(use_globals)
258
+
259
+
260
+ @not_unix
261
+ class TestGdbExceptions(TestCase):
262
+
263
+ def test_call_gdb(self):
264
+ def nop_compiler(x):
265
+ return x
266
+ for compiler in [nop_compiler, jit(forceobj=True), njit]:
267
+ for meth in [gdb, gdb_init]:
268
+ def python_func():
269
+ meth()
270
+ with self.assertRaises(errors.TypingError) as raises:
271
+ compiler(python_func)()
272
+ msg = "gdb support is only available on unix-like systems"
273
+ self.assertIn(msg, str(raises.exception))
274
+
275
+
276
+ if __name__ == '__main__':
277
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_gil.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import ctypes.util
3
+ import os
4
+ import sys
5
+ import threading
6
+ import warnings
7
+
8
+ import numpy as np
9
+
10
+ import unittest
11
+ from numba import jit
12
+ from numba.core import errors
13
+ from numba.tests.support import TestCase, tag
14
+
15
+
16
+ # This CPython API function is a portable way to get the current thread id.
17
+ PyThread_get_thread_ident = ctypes.pythonapi.PyThread_get_thread_ident
18
+ PyThread_get_thread_ident.restype = ctypes.c_long
19
+ PyThread_get_thread_ident.argtypes = []
20
+
21
+ # A way of sleeping from nopython code
22
+ if os.name == 'nt':
23
+ sleep = ctypes.windll.kernel32.Sleep
24
+ sleep.argtypes = [ctypes.c_uint]
25
+ sleep.restype = None
26
+ sleep_factor = 1 # milliseconds
27
+ else:
28
+ sleep = ctypes.CDLL(ctypes.util.find_library("c")).usleep
29
+ sleep.argtypes = [ctypes.c_uint]
30
+ sleep.restype = ctypes.c_int
31
+ sleep_factor = 1000 # microseconds
32
+
33
+
34
+ def f(a, indices):
35
+ # If run from one thread at a time, the function will always fill the
36
+ # array with identical values.
37
+ # If run from several threads at a time, the function will probably
38
+ # fill the array with differing values.
39
+ for idx in indices:
40
+ # Let another thread run
41
+ sleep(10 * sleep_factor)
42
+ a[idx] = PyThread_get_thread_ident()
43
+
44
+ f_sig = "void(int64[:], intp[:])"
45
+
46
+ def lifted_f(a, indices):
47
+ """
48
+ Same as f(), but inside a lifted loop
49
+ """
50
+ object() # Force object mode
51
+ for idx in indices:
52
+ # Let another thread run
53
+ sleep(10 * sleep_factor)
54
+ a[idx] = PyThread_get_thread_ident()
55
+
56
+ def object_f(a, indices):
57
+ """
58
+ Same as f(), but in object mode
59
+ """
60
+ for idx in indices:
61
+ # Let another thread run
62
+ sleep(10 * sleep_factor)
63
+ object() # Force object mode
64
+ a[idx] = PyThread_get_thread_ident()
65
+
66
+
67
+ class TestGILRelease(TestCase):
68
+
69
+ def make_test_array(self, n_members):
70
+ return np.arange(n_members, dtype=np.int64)
71
+
72
+ def run_in_threads(self, func, n_threads):
73
+ # Run the function in parallel over an array and collect results.
74
+ threads = []
75
+ # Warm up compilation, since we don't want that to interfere with
76
+ # the test proper.
77
+ func(self.make_test_array(1), np.arange(1, dtype=np.intp))
78
+ arr = self.make_test_array(50)
79
+ for i in range(n_threads):
80
+ # Ensure different threads write into the array in different
81
+ # orders.
82
+ indices = np.arange(arr.size, dtype=np.intp)
83
+ np.random.shuffle(indices)
84
+ t = threading.Thread(target=func, args=(arr, indices))
85
+ threads.append(t)
86
+ for t in threads:
87
+ t.start()
88
+ for t in threads:
89
+ t.join()
90
+ return arr
91
+
92
+ def check_gil_held(self, func):
93
+ arr = self.run_in_threads(func, n_threads=4)
94
+ distinct = set(arr)
95
+ self.assertEqual(len(distinct), 1, distinct)
96
+
97
+ def check_gil_released(self, func):
98
+ for n_threads in (4, 12, 32):
99
+ # Try harder each time. On an empty machine 4 threads seems
100
+ # sufficient, but in some contexts (e.g. Travis CI) we need more.
101
+ arr = self.run_in_threads(func, n_threads)
102
+ distinct = set(arr)
103
+ try:
104
+ self.assertGreater(len(distinct), 1, distinct)
105
+ except AssertionError as e:
106
+ failure = e
107
+ else:
108
+ return
109
+ raise failure
110
+
111
+ def test_gil_held(self):
112
+ """
113
+ Test the GIL is held by default, by checking serialized runs
114
+ produce deterministic results.
115
+ """
116
+ cfunc = jit(f_sig, nopython=True)(f)
117
+ self.check_gil_held(cfunc)
118
+
119
+ def test_gil_released(self):
120
+ """
121
+ Test releasing the GIL, by checking parallel runs produce
122
+ unpredictable results.
123
+ """
124
+ cfunc = jit(f_sig, nopython=True, nogil=True)(f)
125
+ self.check_gil_released(cfunc)
126
+
127
+ def test_gil_released_inside_lifted_loop(self):
128
+ """
129
+ Test the GIL can by released by a lifted loop even though the
130
+ surrounding code uses object mode.
131
+ """
132
+ cfunc = jit(f_sig, forceobj=True, nogil=True)(lifted_f)
133
+ self.check_gil_released(cfunc)
134
+
135
+ def test_gil_released_by_caller(self):
136
+ """
137
+ Releasing the GIL in the caller is sufficient to have it
138
+ released in a callee.
139
+ """
140
+ compiled_f = jit(f_sig, nopython=True)(f)
141
+ @jit(f_sig, nopython=True, nogil=True)
142
+ def caller(a, i):
143
+ compiled_f(a, i)
144
+ self.check_gil_released(caller)
145
+
146
+ def test_gil_released_by_caller_and_callee(self):
147
+ """
148
+ Same, but with both caller and callee asking to release the GIL.
149
+ """
150
+ compiled_f = jit(f_sig, nopython=True, nogil=True)(f)
151
+ @jit(f_sig, nopython=True, nogil=True)
152
+ def caller(a, i):
153
+ compiled_f(a, i)
154
+ self.check_gil_released(caller)
155
+
156
+ def test_gil_ignored_by_callee(self):
157
+ """
158
+ When only the callee asks to release the GIL, it gets ignored.
159
+ """
160
+ compiled_f = jit(f_sig, nopython=True, nogil=True)(f)
161
+ @jit(f_sig, nopython=True)
162
+ def caller(a, i):
163
+ compiled_f(a, i)
164
+ self.check_gil_held(caller)
165
+
166
+ def test_object_mode(self):
167
+ """
168
+ When the function is compiled in object mode, a warning is
169
+ printed out.
170
+ """
171
+ with warnings.catch_warnings(record=True) as wlist:
172
+ warnings.simplefilter('always', errors.NumbaWarning)
173
+ cfunc = jit(f_sig, forceobj=True, nogil=True)(object_f)
174
+ self.assertTrue(any(w.category is errors.NumbaWarning
175
+ and "Code running in object mode won't allow parallel execution" in str(w.message)
176
+ for w in wlist), wlist)
177
+ # Just check it doesn't crash.
178
+ self.run_in_threads(cfunc, 2)
179
+
180
+
181
+ if __name__ == '__main__':
182
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_hashing.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Test hashing of various supported types.
4
+ """
5
+
6
+ import unittest
7
+
8
+ import os
9
+ import sys
10
+ import subprocess
11
+ from collections import defaultdict
12
+ from textwrap import dedent
13
+
14
+ import numpy as np
15
+
16
+ from numba import jit, config, typed, typeof
17
+ from numba.core import types, utils
18
+ import unittest
19
+ from numba.tests.support import (TestCase, skip_unless_py10_or_later,
20
+ run_in_subprocess)
21
+
22
+ from numba.cpython.unicode import compile_time_get_string_data
23
+ from numba.cpython import hashing
24
+ from numba.np.numpy_support import numpy_version
25
+
26
+
27
+ def hash_usecase(x):
28
+ return hash(x)
29
+
30
+
31
+ class TestHashingSetup(TestCase):
32
+
33
+ def test_warn_on_fnv(self):
34
+ # FNV hash alg variant is not supported, check Numba warns
35
+ work = """
36
+ import sys
37
+ import warnings
38
+ from collections import namedtuple
39
+
40
+ # hash_info is a StructSequence, mock as a named tuple
41
+ fields = ["width", "modulus", "inf", "nan", "imag", "algorithm",
42
+ "hash_bits", "seed_bits", "cutoff"]
43
+
44
+ hinfo = sys.hash_info
45
+ FAKE_HASHINFO = namedtuple('FAKE_HASHINFO', fields)
46
+
47
+ fd = dict()
48
+ for f in fields:
49
+ fd[f] = getattr(hinfo, f)
50
+
51
+ fd['algorithm'] = 'fnv'
52
+
53
+ fake_hashinfo = FAKE_HASHINFO(**fd)
54
+
55
+ # replace the hashinfo with the fnv version
56
+ sys.hash_info = fake_hashinfo
57
+ with warnings.catch_warnings(record=True) as warns:
58
+ # Cause all warnings to always be triggered.
59
+ warnings.simplefilter("always")
60
+ from numba import njit
61
+ @njit
62
+ def foo():
63
+ hash(1)
64
+ foo()
65
+ assert len(warns) > 0
66
+ expect = "FNV hashing is not implemented in Numba. See PEP 456"
67
+ for w in warns:
68
+ if expect in str(w.message):
69
+ break
70
+ else:
71
+ raise RuntimeError("Expected warning not found")
72
+ """
73
+ subprocess.check_call([sys.executable, '-c', dedent(work)])
74
+
75
+
76
+ class TestHashAlgs(TestCase):
77
+ # This tests Numba hashing replication against cPython "gold", i.e. the
78
+ # actual hash values for given inputs, algs and PYTHONHASHSEEDs
79
+ # Test adapted from:
80
+ # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Lib/test/test_hash.py#L197-L264
81
+ # and
82
+ # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Lib/test/test_hash.py#L174-L189
83
+
84
+ # 32bit little, 64bit little, 32bit big, 64bit big
85
+ known_hashes = {
86
+ 'djba33x': [ # only used for small strings
87
+ # seed 0, 'abc'
88
+ [193485960, 193485960, 193485960, 193485960],
89
+ # seed 42, 'abc'
90
+ [-678966196, 573763426263223372, -820489388, -4282905804826039665],
91
+ ],
92
+ 'siphash13': [
93
+ # NOTE: PyUCS2 layout depends on endianness
94
+ # seed 0, 'abc'
95
+ [69611762, -4594863902769663758, 69611762, -4594863902769663758],
96
+ # seed 42, 'abc'
97
+ [-975800855, 3869580338025362921, -975800855, 3869580338025362921],
98
+ # seed 42, 'abcdefghijk'
99
+ [-595844228, 7764564197781545852, -595844228, 7764564197781545852],
100
+ # seed 0, 'äú∑ℇ'
101
+ [-1093288643, -2810468059467891395, -1041341092, 4925090034378237276],
102
+ # seed 42, 'äú∑ℇ'
103
+ [-585999602, -2845126246016066802, -817336969, -2219421378907968137],
104
+ ],
105
+ 'siphash24': [
106
+ # NOTE: PyUCS2 layout depends on endianness
107
+ # seed 0, 'abc'
108
+ [1198583518, 4596069200710135518, 1198583518, 4596069200710135518],
109
+ # seed 42, 'abc'
110
+ [273876886, -4501618152524544106, 273876886, -4501618152524544106],
111
+ # seed 42, 'abcdefghijk'
112
+ [-1745215313, 4436719588892876975, -1745215313, 4436719588892876975],
113
+ # seed 0, 'äú∑ℇ'
114
+ [493570806, 5749986484189612790, -1006381564, -5915111450199468540],
115
+ # seed 42, 'äú∑ℇ'
116
+ [-1677110816, -2947981342227738144, -1860207793, -4296699217652516017],
117
+ ],
118
+ }
119
+
120
+ def get_expected_hash(self, position, length):
121
+ if length < sys.hash_info.cutoff:
122
+ algorithm = "djba33x"
123
+ else:
124
+ algorithm = sys.hash_info.algorithm
125
+ IS_64BIT = not config.IS_32BITS
126
+ if sys.byteorder == 'little':
127
+ platform = 1 if IS_64BIT else 0
128
+ else:
129
+ assert(sys.byteorder == 'big')
130
+ platform = 3 if IS_64BIT else 2
131
+ return self.known_hashes[algorithm][position][platform]
132
+
133
+ def get_hash_command(self, repr_):
134
+ return 'print(hash(eval(%a)))' % repr_
135
+
136
+ def get_hash(self, repr_, seed=None):
137
+ env = os.environ.copy()
138
+ if seed is not None:
139
+ env['PYTHONHASHSEED'] = str(seed)
140
+ else:
141
+ env.pop('PYTHONHASHSEED', None)
142
+ out, _ = run_in_subprocess(code=self.get_hash_command(repr_),
143
+ env=env)
144
+ stdout = out.decode().strip()
145
+ return int(stdout)
146
+
147
+ def test_against_cpython_gold(self):
148
+
149
+ args = (('abc', 0, 0), ('abc', 42, 1), ('abcdefghijk', 42, 2),
150
+ ('äú∑ℇ', 0, 3), ('äú∑ℇ', 42, 4),)
151
+
152
+ for input_str, seed, position in args:
153
+ with self.subTest(input_str=input_str, seed=seed):
154
+ got = self.get_hash(repr(input_str), seed=seed)
155
+ expected = self.get_expected_hash(position, len(input_str))
156
+ self.assertEqual(got, expected)
157
+
158
+
159
+ class BaseTest(TestCase):
160
+
161
+ def setUp(self):
162
+ self.cfunc = jit(nopython=True)(hash_usecase)
163
+
164
+ def check_hash_values(self, values):
165
+ cfunc = self.cfunc
166
+ for val in list(values):
167
+ nb_hash = cfunc(val)
168
+ self.assertIsInstance(nb_hash, int)
169
+ try:
170
+ self.assertEqual(nb_hash, hash(val))
171
+ except AssertionError as e:
172
+ print("val, nb_hash, hash(val)")
173
+ print(val, nb_hash, hash(val))
174
+ print("abs(val), hashing._PyHASH_MODULUS - 1")
175
+ print(abs(val), hashing._PyHASH_MODULUS - 1)
176
+ raise e
177
+
178
+ def int_samples(self, typ=np.int64):
179
+ for start in (0, -50, 60000, 1 << 32):
180
+ info = np.iinfo(typ)
181
+ if not info.min <= start <= info.max:
182
+ continue
183
+ n = 100
184
+ yield range(start, start + n)
185
+ yield range(start, start + 100 * n, 100)
186
+ yield range(start, start + 128 * n, 128)
187
+ yield [-1]
188
+
189
+ def float_samples(self, typ):
190
+ info = np.finfo(typ)
191
+
192
+ for start in (0, 10, info.max ** 0.5, info.max / 1000.0):
193
+ n = 100
194
+ min_step = max(info.tiny, start * info.resolution)
195
+ for step in (1.2, min_step ** 0.5, min_step):
196
+ if step < min_step:
197
+ continue
198
+ a = np.linspace(start, start + n * step, n)
199
+ a = a.astype(typ)
200
+ yield a
201
+ yield -a
202
+ yield a + a.mean()
203
+
204
+ # Infs, nans, zeros, magic -1
205
+ a = [0.0, 0.5, -0.0, -1.0, float('inf'), -float('inf'),]
206
+
207
+ # Python 3.10 has a hash for nan based on the pointer to the PyObject
208
+ # containing the nan, skip this input and use explicit test instead.
209
+
210
+ yield typ(a)
211
+
212
+ def complex_samples(self, typ, float_ty):
213
+ for real in self.float_samples(float_ty):
214
+ for imag in self.float_samples(float_ty):
215
+ # Ensure equal sizes
216
+ real = real[:len(imag)]
217
+ imag = imag[:len(real)]
218
+ a = real + typ(1j) * imag
219
+ # Python 3.10 has a hash for nan based on the pointer to the
220
+ # PyObject containing the nan, skip input that ends up as nan
221
+ if not np.any(np.isnan(a)):
222
+ yield a
223
+
224
+
225
+ class TestNumberHashing(BaseTest):
226
+ """
227
+ Test hashing of number types.
228
+ """
229
+
230
+ def setUp(self):
231
+ if numpy_version >= (2, 0):
232
+ # Temporarily set promotions state to legacy,
233
+ # to ensure overflow logic works
234
+ self.initial_state = np._get_promotion_state()
235
+ np._set_promotion_state("legacy")
236
+
237
+ return super().setUp()
238
+
239
+ def tearDown(self) -> None:
240
+ if numpy_version >= (2, 0):
241
+ # Reset numpy promotion state to initial state
242
+ # since the setting is global
243
+ np._set_promotion_state(self.initial_state)
244
+
245
+ return super().tearDown()
246
+
247
+ def check_floats(self, typ):
248
+ for a in self.float_samples(typ):
249
+ self.assertEqual(a.dtype, np.dtype(typ))
250
+ self.check_hash_values(a)
251
+
252
+ def check_complex(self, typ, float_ty):
253
+ for a in self.complex_samples(typ, float_ty):
254
+ self.assertEqual(a.dtype, np.dtype(typ))
255
+ self.check_hash_values(a)
256
+
257
+ def test_floats(self):
258
+ self.check_floats(np.float32)
259
+ self.check_floats(np.float64)
260
+
261
+ def test_complex(self):
262
+ self.check_complex(np.complex64, np.float32)
263
+ self.check_complex(np.complex128, np.float64)
264
+
265
+ def test_bool(self):
266
+ self.check_hash_values([False, True])
267
+
268
+ def test_ints(self):
269
+ minmax = []
270
+
271
+ for ty in [np.int8, np.uint8, np.int16, np.uint16,
272
+ np.int32, np.uint32, np.int64, np.uint64]:
273
+ for a in self.int_samples(ty):
274
+ self.check_hash_values(a)
275
+ info = np.iinfo(ty)
276
+ # check hash(-1) = -2
277
+ # check hash(0) = 0
278
+ self.check_hash_values([ty(-1)])
279
+ self.check_hash_values([ty(0)])
280
+ signed = 'uint' not in str(ty)
281
+ # check bit shifting patterns from min through to max
282
+ sz = ty().itemsize
283
+ for x in [info.min, info.max]:
284
+ shifts = 8 * sz
285
+ # x is a python int, do shifts etc as a python int and init
286
+ # numpy type from that to avoid numpy type rules
287
+ y = x
288
+ for i in range(shifts):
289
+ twiddle1 = 0xaaaaaaaaaaaaaaaa
290
+ twiddle2 = 0x5555555555555555
291
+ vals = [y]
292
+ for tw in [twiddle1, twiddle2]:
293
+ val = y & twiddle1
294
+ if val < sys.maxsize:
295
+ vals.append(val)
296
+ for v in vals:
297
+ self.check_hash_values([ty(v)])
298
+ if signed: # try the same with flipped signs
299
+ # negated signed INT_MIN will overflow
300
+ for v in vals:
301
+ if v != info.min:
302
+ self.check_hash_values([ty(-v)])
303
+ if x == 0: # unsigned min is 0, shift up
304
+ y = (y | 1) << 1
305
+ else: # everything else shift down
306
+ y = y >> 1
307
+
308
+ # these straddle the branch between returning the int as the hash and
309
+ # doing the PyLong hash alg
310
+ self.check_hash_values([np.int64(0x1ffffffffffffffe)])
311
+ self.check_hash_values([np.int64(0x1fffffffffffffff)])
312
+ self.check_hash_values([np.uint64(0x1ffffffffffffffe)])
313
+ self.check_hash_values([np.uint64(0x1fffffffffffffff)])
314
+
315
+ # check some values near sys int mins
316
+ self.check_hash_values([np.int64(-0x7fffffffffffffff)])
317
+ self.check_hash_values([np.int64(-0x7ffffffffffffff6)])
318
+ self.check_hash_values([np.int64(-0x7fffffffffffff9c)])
319
+ self.check_hash_values([np.int32(-0x7fffffff)])
320
+ self.check_hash_values([np.int32(-0x7ffffff6)])
321
+ self.check_hash_values([np.int32(-0x7fffff9c)])
322
+
323
+ @skip_unless_py10_or_later
324
+ def test_py310_nan_hash(self):
325
+ # On Python 3.10+ nan's hash to a value which is based on the pointer to
326
+ # the PyObject containing the nan. Numba cannot replicate as there's no
327
+ # object, it instead produces equivalent behaviour, i.e. hashes to
328
+ # something "unique".
329
+
330
+ # Run 10 hashes, make sure that the "uniqueness" is sufficient that
331
+ # there's more than one hash value. Not much more can be done!
332
+ x = [float('nan') for i in range(10)]
333
+ out = set([self.cfunc(z) for z in x])
334
+ self.assertGreater(len(out), 1)
335
+
336
+
337
+ class TestTupleHashing(BaseTest):
338
+ """
339
+ Test hashing of tuples.
340
+ """
341
+
342
+ def setUp(self):
343
+ if numpy_version >= (2, 0):
344
+ # Temporarily set promotions state to legacy,
345
+ # to ensure overflow logic works
346
+ self.initial_state = np._get_promotion_state()
347
+ np._set_promotion_state("legacy")
348
+
349
+ return super().setUp()
350
+
351
+ def tearDown(self) -> None:
352
+ if numpy_version >= (2, 0):
353
+ # Reset numpy promotion state to initial state
354
+ # since the setting is global
355
+ np._set_promotion_state(self.initial_state)
356
+
357
+ return super().tearDown()
358
+
359
+ def check_tuples(self, value_generator, split):
360
+ for values in value_generator:
361
+ tuples = [split(a) for a in values]
362
+ self.check_hash_values(tuples)
363
+
364
+ def test_homogeneous_tuples(self):
365
+ typ = np.uint64
366
+
367
+ def split2(i):
368
+ """
369
+ Split i's bits into 2 integers.
370
+ """
371
+ i = typ(i)
372
+ return (i & typ(0x5555555555555555),
373
+ i & typ(0xaaaaaaaaaaaaaaaa),
374
+ )
375
+
376
+ def split3(i):
377
+ """
378
+ Split i's bits into 3 integers.
379
+ """
380
+ i = typ(i)
381
+ return (i & typ(0x2492492492492492),
382
+ i & typ(0x4924924924924924),
383
+ i & typ(0x9249249249249249),
384
+ )
385
+
386
+ self.check_tuples(self.int_samples(), split2)
387
+ self.check_tuples(self.int_samples(), split3)
388
+
389
+ # Check exact. Sample values from:
390
+ # https://github.com/python/cpython/blob/b738237d6792acba85b1f6e6c8993a812c7fd815/Lib/test/test_tuple.py#L80-L93
391
+ # Untypable empty tuples are replaced with (7,).
392
+ self.check_hash_values([(7,), (0,), (0, 0), (0.5,),
393
+ (0.5, (7,), (-2, 3, (4, 6)))])
394
+
395
+ def test_heterogeneous_tuples(self):
396
+ modulo = 2**63
397
+
398
+ def split(i):
399
+ a = i & 0x5555555555555555
400
+ b = (i & 0xaaaaaaaa) ^ ((i >> 32) & 0xaaaaaaaa)
401
+ return np.int64(a), np.float64(b * 0.0001)
402
+
403
+ self.check_tuples(self.int_samples(), split)
404
+
405
+
406
+ class TestUnicodeHashing(BaseTest):
407
+
408
+ def test_basic_unicode(self):
409
+ kind1_string = "abcdefghijklmnopqrstuvwxyz"
410
+ for i in range(len(kind1_string)):
411
+ self.check_hash_values([kind1_string[:i]])
412
+
413
+ sep = "眼"
414
+ kind2_string = sep.join(list(kind1_string))
415
+ for i in range(len(kind2_string)):
416
+ self.check_hash_values([kind2_string[:i]])
417
+
418
+ sep = "🐍⚡"
419
+ kind4_string = sep.join(list(kind1_string))
420
+ for i in range(len(kind4_string)):
421
+ self.check_hash_values([kind4_string[:i]])
422
+
423
+ empty_string = ""
424
+ self.check_hash_values(empty_string)
425
+
426
+ def test_hash_passthrough(self):
427
+ # no `hash` call made, this just checks that `._hash` is correctly
428
+ # passed through from an already existing string
429
+ kind1_string = "abcdefghijklmnopqrstuvwxyz"
430
+
431
+ @jit(nopython=True)
432
+ def fn(x):
433
+ return x._hash
434
+
435
+ hash_value = compile_time_get_string_data(kind1_string)[-1]
436
+ self.assertTrue(hash_value != -1)
437
+ self.assertEqual(fn(kind1_string), hash_value)
438
+
439
+ def test_hash_passthrough_call(self):
440
+ # check `x._hash` and hash(x) are the same
441
+ kind1_string = "abcdefghijklmnopqrstuvwxyz"
442
+
443
+ @jit(nopython=True)
444
+ def fn(x):
445
+ return x._hash, hash(x)
446
+
447
+ hash_value = compile_time_get_string_data(kind1_string)[-1]
448
+ self.assertTrue(hash_value != -1)
449
+ self.assertEqual(fn(kind1_string), (hash_value, hash_value))
450
+
451
+ @unittest.skip("Needs hash computation at const unpickling time")
452
+ def test_hash_literal(self):
453
+ # a strconst always seem to have an associated hash value so the hash
454
+ # member of the returned value should contain the correct hash
455
+ @jit(nopython=True)
456
+ def fn():
457
+ x = "abcdefghijklmnopqrstuvwxyz"
458
+ return x
459
+ val = fn()
460
+ tmp = hash("abcdefghijklmnopqrstuvwxyz")
461
+ self.assertEqual(tmp, (compile_time_get_string_data(val)[-1]))
462
+
463
+ def test_hash_on_str_creation(self):
464
+ # In cPython some? new strings do not have a cached hash until hash() is
465
+ # called
466
+ def impl(do_hash):
467
+ const1 = "aaaa"
468
+ const2 = "眼眼眼眼"
469
+ new = const1 + const2
470
+ if do_hash:
471
+ hash(new)
472
+ return new
473
+
474
+ jitted = jit(nopython=True)(impl)
475
+
476
+ # do not compute the hash, cPython will have no cached hash, but Numba
477
+ # will
478
+ compute_hash = False
479
+ expected = impl(compute_hash)
480
+ got = jitted(compute_hash)
481
+ a = (compile_time_get_string_data(expected))
482
+ b = (compile_time_get_string_data(got))
483
+ self.assertEqual(a[:-1], b[:-1])
484
+ self.assertTrue(a[-1] != b[-1])
485
+
486
+ # now with compute hash enabled, cPython will have a cached hash as will
487
+ # Numba
488
+ compute_hash = True
489
+ expected = impl(compute_hash)
490
+ got = jitted(compute_hash)
491
+ a = (compile_time_get_string_data(expected))
492
+ b = (compile_time_get_string_data(got))
493
+ self.assertEqual(a, b)
494
+
495
+
496
+ class TestUnhashable(TestCase):
497
+ # Tests that unhashable types behave correctly and raise a TypeError at
498
+ # runtime.
499
+
500
+ def test_hash_unhashable(self):
501
+ unhashables = (typed.Dict().empty(types.int64, types.int64),
502
+ typed.List().empty_list(types.int64),
503
+ np.ones(4))
504
+ cfunc = jit(nopython=True)(hash_usecase)
505
+ for ty in unhashables:
506
+ with self.assertRaises(TypeError) as raises:
507
+ cfunc(ty)
508
+ expected = f"unhashable type: '{str(typeof(ty))}'"
509
+ self.assertIn(expected, str(raises.exception))
510
+
511
+ def test_no_generic_hash(self):
512
+ # In CPython, if there's no attr `__hash__` on an object, a hash of the
513
+ # object's pointer is returned (see: _Py_HashPointer in the CPython
514
+ # source). Numba has no access to such objects and can't create them
515
+ # either, so it catches this case and raises an exception.
516
+
517
+ @jit(nopython=True)
518
+ def foo():
519
+ hash(np.cos)
520
+
521
+ with self.assertRaises(TypeError) as raises:
522
+ foo()
523
+
524
+ expected = ("No __hash__ is defined for object ")
525
+ self.assertIn(expected, str(raises.exception))
526
+
527
+
528
+ if __name__ == "__main__":
529
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_heapq.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import heapq as hq
2
+ import itertools
3
+
4
+ import numpy as np
5
+
6
+ from numba import jit, typed
7
+ from numba.tests.support import TestCase, MemoryLeakMixin
8
+
9
+
10
+ def heapify(x):
11
+ return hq.heapify(x)
12
+
13
+
14
+ def heappop(heap):
15
+ return hq.heappop(heap)
16
+
17
+
18
+ def heappush(heap, item):
19
+ return hq.heappush(heap, item)
20
+
21
+
22
+ def heappushpop(heap, item):
23
+ return hq.heappushpop(heap, item)
24
+
25
+
26
+ def heapreplace(heap, item):
27
+ return hq.heapreplace(heap, item)
28
+
29
+
30
+ def nsmallest(n, iterable):
31
+ return hq.nsmallest(n, iterable)
32
+
33
+
34
+ def nlargest(n, iterable):
35
+ return hq.nlargest(n, iterable)
36
+
37
+
38
+ class _TestHeapq(MemoryLeakMixin):
39
+
40
+ def setUp(self):
41
+ super(_TestHeapq, self).setUp()
42
+ self.rnd = np.random.RandomState(42)
43
+
44
+ def test_heapify_basic_sanity(self):
45
+ pyfunc = heapify
46
+ cfunc = jit(nopython=True)(pyfunc)
47
+
48
+ a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
49
+ b = self.listimpl(a)
50
+
51
+ pyfunc(a)
52
+ cfunc(b)
53
+ self.assertPreciseEqual(a, list(b))
54
+
55
+ # includes non-finite elements
56
+ element_pool = [3.142, -10.0, 5.5, np.nan, -np.inf, np.inf]
57
+
58
+ # list which may contain duplicate elements
59
+ for x in itertools.combinations_with_replacement(element_pool, 6):
60
+ a = list(x)
61
+ b = self.listimpl(a)
62
+
63
+ pyfunc(a)
64
+ cfunc(b)
65
+ self.assertPreciseEqual(a, list(b))
66
+
67
+ # single element list
68
+ for i in range(len(element_pool)):
69
+ a = [element_pool[i]]
70
+ b = self.listimpl(a)
71
+
72
+ pyfunc(a)
73
+ cfunc(b)
74
+ self.assertPreciseEqual(a, list(b))
75
+
76
+ # elements are tuples
77
+ a = [(3, 33), (1, 11), (2, 22)]
78
+ b = self.listimpl(a)
79
+ pyfunc(a)
80
+ cfunc(b)
81
+ self.assertPreciseEqual(a, list(b))
82
+
83
+ def check_invariant(self, heap):
84
+ for pos, item in enumerate(heap):
85
+ if pos:
86
+ parentpos = (pos - 1) >> 1
87
+ self.assertTrue(heap[parentpos] <= item)
88
+
89
+ def test_push_pop(self):
90
+ # inspired by
91
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
92
+ pyfunc_heappush = heappush
93
+ cfunc_heappush = jit(nopython=True)(pyfunc_heappush)
94
+
95
+ pyfunc_heappop = heappop
96
+ cfunc_heappop = jit(nopython=True)(pyfunc_heappop)
97
+
98
+ heap = self.listimpl([-1.0])
99
+ data = self.listimpl([-1.0])
100
+ self.check_invariant(heap)
101
+ for i in range(256):
102
+ item = self.rnd.randn(1).item(0)
103
+ data.append(item)
104
+ cfunc_heappush(heap, item)
105
+ self.check_invariant(heap)
106
+ results = []
107
+ while heap:
108
+ item = cfunc_heappop(heap)
109
+ self.check_invariant(heap)
110
+ results.append(item)
111
+ data_sorted = data[:]
112
+ data_sorted.sort()
113
+ self.assertPreciseEqual(list(data_sorted), results)
114
+ self.check_invariant(results)
115
+
116
+ def test_heapify(self):
117
+ # inspired by
118
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
119
+ pyfunc = heapify
120
+ cfunc = jit(nopython=True)(pyfunc)
121
+
122
+ for size in list(range(1, 30)) + [20000]:
123
+ heap = self.listimpl(self.rnd.random_sample(size))
124
+ cfunc(heap)
125
+ self.check_invariant(heap)
126
+
127
+ def test_heapify_exceptions(self):
128
+ pyfunc = heapify
129
+ cfunc = jit(nopython=True)(pyfunc)
130
+
131
+ # Exceptions leak references
132
+ self.disable_leak_check()
133
+
134
+ with self.assertTypingError() as e:
135
+ cfunc((1, 5, 4))
136
+
137
+ msg = 'heap argument must be a list'
138
+ self.assertIn(msg, str(e.exception))
139
+
140
+ with self.assertTypingError() as e:
141
+ cfunc(self.listimpl([1 + 1j, 2 - 3j]))
142
+
143
+ msg = ("'<' not supported between instances "
144
+ "of 'complex' and 'complex'")
145
+ self.assertIn(msg, str(e.exception))
146
+
147
+ def test_heappop_basic_sanity(self):
148
+ pyfunc = heappop
149
+ cfunc = jit(nopython=True)(pyfunc)
150
+
151
+ def a_variations():
152
+ yield [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
153
+ yield [(3, 33), (1, 111), (2, 2222)]
154
+ yield np.full(5, fill_value=np.nan).tolist()
155
+ yield np.linspace(-10, -5, 100).tolist()
156
+
157
+ for a in a_variations():
158
+ heapify(a)
159
+ b = self.listimpl(a)
160
+
161
+ for i in range(len(a)):
162
+ val_py = pyfunc(a)
163
+ val_c = cfunc(b)
164
+ self.assertPreciseEqual(a, list(b))
165
+ self.assertPreciseEqual(val_py, val_c)
166
+
167
+ def test_heappop_exceptions(self):
168
+ pyfunc = heappop
169
+ cfunc = jit(nopython=True)(pyfunc)
170
+
171
+ # Exceptions leak references
172
+ self.disable_leak_check()
173
+
174
+ with self.assertTypingError() as e:
175
+ cfunc((1, 5, 4))
176
+
177
+ msg = 'heap argument must be a list'
178
+ self.assertIn(msg, str(e.exception))
179
+
180
+ def iterables(self):
181
+ yield self.listimpl([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
182
+ a = np.linspace(-10, 2, 23)
183
+ yield self.listimpl(a)
184
+ yield self.listimpl(a[::-1])
185
+ self.rnd.shuffle(a)
186
+ yield self.listimpl(a)
187
+
188
+ def test_heappush_basic(self):
189
+ pyfunc_push = heappush
190
+ cfunc_push = jit(nopython=True)(pyfunc_push)
191
+
192
+ pyfunc_pop = heappop
193
+ cfunc_pop = jit(nopython=True)(pyfunc_pop)
194
+
195
+ for iterable in self.iterables():
196
+ expected = sorted(iterable)
197
+ heap = self.listimpl([iterable.pop(0)]) # must initialise heap
198
+
199
+ for value in iterable:
200
+ cfunc_push(heap, value)
201
+
202
+ got = [cfunc_pop(heap) for _ in range(len(heap))]
203
+ self.assertPreciseEqual(expected, got)
204
+
205
+ def test_heappush_exceptions(self):
206
+ pyfunc = heappush
207
+ cfunc = jit(nopython=True)(pyfunc)
208
+
209
+ # Exceptions leak references
210
+ self.disable_leak_check()
211
+
212
+ with self.assertTypingError() as e:
213
+ cfunc((1, 5, 4), 6)
214
+
215
+ msg = 'heap argument must be a list'
216
+ self.assertIn(msg, str(e.exception))
217
+
218
+ with self.assertTypingError() as e:
219
+ cfunc(self.listimpl([1, 5, 4]), 6.0)
220
+
221
+ msg = 'heap type must be the same as item type'
222
+ self.assertIn(msg, str(e.exception))
223
+
224
+ def test_nsmallest_basic(self):
225
+ pyfunc = nsmallest
226
+ cfunc = jit(nopython=True)(pyfunc)
227
+
228
+ for iterable in self.iterables():
229
+ for n in range(-5, len(iterable) + 3):
230
+ expected = pyfunc(1, iterable)
231
+ got = cfunc(1, iterable)
232
+ self.assertPreciseEqual(expected, got)
233
+
234
+ # n is boolean
235
+ out = cfunc(False, self.listimpl([3, 2, 1]))
236
+ self.assertPreciseEqual(out, [])
237
+
238
+ out = cfunc(True, self.listimpl([3, 2, 1]))
239
+ self.assertPreciseEqual(out, [1])
240
+
241
+ # iterable is not a list
242
+ out = cfunc(2, (6, 5, 4, 3, 2, 1))
243
+ self.assertPreciseEqual(out, [1, 2])
244
+
245
+ out = cfunc(3, np.arange(6))
246
+ self.assertPreciseEqual(out, [0, 1, 2])
247
+
248
+ def test_nlargest_basic(self):
249
+ pyfunc = nlargest
250
+ cfunc = jit(nopython=True)(pyfunc)
251
+
252
+ for iterable in self.iterables():
253
+ for n in range(-5, len(iterable) + 3):
254
+ expected = pyfunc(1, iterable)
255
+ got = cfunc(1, iterable)
256
+ self.assertPreciseEqual(expected, got)
257
+
258
+ # n is boolean
259
+ out = cfunc(False, self.listimpl([3, 2, 1]))
260
+ self.assertPreciseEqual(out, [])
261
+
262
+ out = cfunc(True, self.listimpl([3, 2, 1]))
263
+ self.assertPreciseEqual(out, [3])
264
+
265
+ # iterable is not a list
266
+ out = cfunc(2, (6, 5, 4, 3, 2, 1))
267
+ self.assertPreciseEqual(out, [6, 5])
268
+
269
+ out = cfunc(3, np.arange(6))
270
+ self.assertPreciseEqual(out, [5, 4, 3])
271
+
272
+ def _assert_typing_error(self, cfunc):
273
+
274
+ # Exceptions leak references
275
+ self.disable_leak_check()
276
+
277
+ with self.assertTypingError() as e:
278
+ cfunc(2.2, self.listimpl([3, 2, 1]))
279
+
280
+ msg = "First argument 'n' must be an integer"
281
+ self.assertIn(msg, str(e.exception))
282
+
283
+ with self.assertTypingError() as e:
284
+ cfunc(2, 100)
285
+
286
+ msg = "Second argument 'iterable' must be iterable"
287
+ self.assertIn(msg, str(e.exception))
288
+
289
+ def test_nsmallest_exceptions(self):
290
+ pyfunc = nsmallest
291
+ cfunc = jit(nopython=True)(pyfunc)
292
+ self._assert_typing_error(cfunc)
293
+
294
+ def test_nlargest_exceptions(self):
295
+ pyfunc = nlargest
296
+ cfunc = jit(nopython=True)(pyfunc)
297
+ self._assert_typing_error(cfunc)
298
+
299
+ def test_heapreplace_basic(self):
300
+ pyfunc = heapreplace
301
+ cfunc = jit(nopython=True)(pyfunc)
302
+
303
+ a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
304
+
305
+ heapify(a)
306
+ b = self.listimpl(a)
307
+
308
+ for item in [-4, 4, 14]:
309
+ pyfunc(a, item)
310
+ cfunc(b, item)
311
+ self.assertPreciseEqual(a, list(b))
312
+
313
+ a = np.linspace(-3, 13, 20)
314
+ a[4] = np.nan
315
+ a[-1] = np.inf
316
+ a = a.tolist()
317
+
318
+ heapify(a)
319
+ b = self.listimpl(a)
320
+
321
+ for item in [-4.0, 3.142, -np.inf, np.inf]:
322
+ pyfunc(a, item)
323
+ cfunc(b, item)
324
+ self.assertPreciseEqual(a, list(b))
325
+
326
+ def test_heapreplace_exceptions(self):
327
+ pyfunc = heapreplace
328
+ cfunc = jit(nopython=True)(pyfunc)
329
+
330
+ # Exceptions leak references
331
+ self.disable_leak_check()
332
+
333
+ with self.assertTypingError() as e:
334
+ cfunc((1, 5, 4), -1)
335
+
336
+ msg = 'heap argument must be a list'
337
+ self.assertIn(msg, str(e.exception))
338
+
339
+ with self.assertTypingError() as e:
340
+ cfunc(self.listimpl([1, 5, 4]), -1.0)
341
+
342
+ msg = 'heap type must be the same as item type'
343
+ self.assertIn(msg, str(e.exception))
344
+
345
+ def heapiter(self, heap):
346
+ try:
347
+ while 1:
348
+ yield heappop(heap)
349
+ except IndexError:
350
+ pass
351
+
352
+ def test_nbest(self):
353
+ # inspired by
354
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
355
+ cfunc_heapify = jit(nopython=True)(heapify)
356
+ cfunc_heapreplace = jit(nopython=True)(heapreplace)
357
+
358
+ data = self.rnd.choice(range(2000), 1000).tolist()
359
+ heap = self.listimpl(data[:10])
360
+ cfunc_heapify(heap)
361
+
362
+ for item in data[10:]:
363
+ if item > heap[0]:
364
+ cfunc_heapreplace(heap, item)
365
+
366
+ self.assertPreciseEqual(list(self.heapiter(list(heap))),
367
+ sorted(data)[-10:])
368
+
369
+ def test_heapsort(self):
370
+ # inspired by
371
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
372
+ cfunc_heapify = jit(nopython=True)(heapify)
373
+ cfunc_heappush = jit(nopython=True)(heappush)
374
+ cfunc_heappop = jit(nopython=True)(heappop)
375
+
376
+ for trial in range(100):
377
+ # Ensure consistency of typing, use float64 as it's double
378
+ # everywhere
379
+ values = np.arange(5, dtype=np.float64)
380
+ data = self.listimpl(self.rnd.choice(values, 10))
381
+ if trial & 1:
382
+ heap = data[:]
383
+ cfunc_heapify(heap)
384
+ else:
385
+ heap = self.listimpl([data[0]])
386
+ for item in data[1:]:
387
+ cfunc_heappush(heap, item)
388
+ heap_sorted = [cfunc_heappop(heap) for _ in range(10)]
389
+ self.assertPreciseEqual(heap_sorted, sorted(data))
390
+
391
+ def test_nsmallest(self):
392
+ # inspired by
393
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
394
+ pyfunc = nsmallest
395
+ cfunc = jit(nopython=True)(pyfunc)
396
+
397
+ data = self.listimpl(self.rnd.choice(range(2000), 1000))
398
+
399
+ for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
400
+ self.assertPreciseEqual(list(cfunc(n, data)), sorted(data)[:n])
401
+
402
+ def test_nlargest(self):
403
+ # inspired by
404
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
405
+ pyfunc = nlargest
406
+ cfunc = jit(nopython=True)(pyfunc)
407
+
408
+ data = self.listimpl(self.rnd.choice(range(2000), 1000))
409
+
410
+ for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
411
+ self.assertPreciseEqual(list(cfunc(n, data)),
412
+ sorted(data, reverse=True)[:n])
413
+
414
+ def test_nbest_with_pushpop(self):
415
+ # inspired by
416
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
417
+ pyfunc_heappushpop = heappushpop
418
+ cfunc_heappushpop = jit(nopython=True)(pyfunc_heappushpop)
419
+
420
+ pyfunc_heapify = heapify
421
+ cfunc_heapify = jit(nopython=True)(pyfunc_heapify)
422
+
423
+ # Ensure consistency of typing, use float64 as it's double everywhere
424
+ values = np.arange(2000, dtype=np.float64)
425
+ data = self.listimpl(self.rnd.choice(values, 1000))
426
+ heap = data[:10]
427
+ cfunc_heapify(heap)
428
+
429
+ for item in data[10:]:
430
+ cfunc_heappushpop(heap, item)
431
+
432
+ self.assertPreciseEqual(list(self.heapiter(list(heap))),
433
+ sorted(data)[-10:])
434
+
435
+ def test_heappushpop(self):
436
+ # inspired by
437
+ # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
438
+ pyfunc = heappushpop
439
+ cfunc = jit(nopython=True)(pyfunc)
440
+
441
+ h = self.listimpl([1.0])
442
+ x = cfunc(h, 10.0)
443
+ self.assertPreciseEqual((list(h), x), ([10.0], 1.0))
444
+ self.assertPreciseEqual(type(h[0]), float)
445
+ self.assertPreciseEqual(type(x), float)
446
+
447
+ h = self.listimpl([10])
448
+ x = cfunc(h, 9)
449
+ self.assertPreciseEqual((list(h), x), ([10], 9))
450
+
451
+ h = self.listimpl([10])
452
+ x = cfunc(h, 11)
453
+ self.assertPreciseEqual((list(h), x), ([11], 10))
454
+
455
+ def test_heappushpop_exceptions(self):
456
+ pyfunc = heappushpop
457
+ cfunc = jit(nopython=True)(pyfunc)
458
+
459
+ # Exceptions leak references
460
+ self.disable_leak_check()
461
+
462
+ with self.assertTypingError() as e:
463
+ cfunc((1, 5, 4), -1)
464
+
465
+ msg = 'heap argument must be a list'
466
+ self.assertIn(msg, str(e.exception))
467
+
468
+ with self.assertTypingError() as e:
469
+ cfunc(self.listimpl([1, 5, 4]), False)
470
+
471
+ msg = 'heap type must be the same as item type'
472
+ self.assertIn(msg, str(e.exception))
473
+
474
+
475
+ class TestHeapqReflectedList(_TestHeapq, TestCase):
476
+ """Test heapq with reflected lists"""
477
+
478
+ listimpl = list
479
+
480
+
481
+ class TestHeapqTypedList(_TestHeapq, TestCase):
482
+ """Test heapq with typed lists"""
483
+
484
+ listimpl = typed.List
lib/python3.10/site-packages/numba/tests/test_inlining.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import numpy as np
3
+
4
+ from numba.tests.support import (TestCase, override_config, captured_stdout,
5
+ skip_parfors_unsupported)
6
+ from numba import jit, njit
7
+ from numba.core import types, ir, postproc, compiler
8
+ from numba.core.ir_utils import (guard, find_callname, find_const,
9
+ get_definition, simplify_CFG)
10
+ from numba.core.registry import CPUDispatcher
11
+ from numba.core.inline_closurecall import inline_closure_call
12
+
13
+ from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, FixupArgs,
14
+ IRProcessing, DeadBranchPrune,
15
+ RewriteSemanticConstants, GenericRewrites,
16
+ WithLifting, PreserveIR, InlineClosureLikes)
17
+
18
+ from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes,
19
+ NopythonRewrites, PreParforPass, ParforPass,
20
+ DumpParforDiagnostics, NativeLowering,
21
+ NativeParforLowering, IRLegalization,
22
+ NoPythonBackend, NativeLowering,
23
+ ParforFusionPass, ParforPreLoweringPass)
24
+
25
+ from numba.core.compiler_machinery import FunctionPass, PassManager, register_pass
26
+ import unittest
27
+
28
+ @register_pass(analysis_only=False, mutates_CFG=True)
29
+ class InlineTestPass(FunctionPass):
30
+ _name = "inline_test_pass"
31
+
32
+ def __init__(self):
33
+ FunctionPass.__init__(self)
34
+
35
+ def run_pass(self, state):
36
+ # assuming the function has one block with one call inside
37
+ assert len(state.func_ir.blocks) == 1
38
+ block = list(state.func_ir.blocks.values())[0]
39
+ for i, stmt in enumerate(block.body):
40
+ if guard(find_callname,state.func_ir, stmt.value) is not None:
41
+ inline_closure_call(state.func_ir, {}, block, i, lambda: None,
42
+ state.typingctx, state.targetctx, (),
43
+ state.typemap, state.calltypes)
44
+ break
45
+ # also fix up the IR
46
+ post_proc = postproc.PostProcessor(state.func_ir)
47
+ post_proc.run()
48
+ post_proc.remove_dels()
49
+ return True
50
+
51
+
52
+ def gen_pipeline(state, test_pass):
53
+ name = 'inline_test'
54
+ pm = PassManager(name)
55
+ pm.add_pass(TranslateByteCode, "analyzing bytecode")
56
+ pm.add_pass(FixupArgs, "fix up args")
57
+ pm.add_pass(IRProcessing, "processing IR")
58
+ pm.add_pass(WithLifting, "Handle with contexts")
59
+ # pre typing
60
+ if not state.flags.no_rewrites:
61
+ pm.add_pass(GenericRewrites, "nopython rewrites")
62
+ pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants")
63
+ pm.add_pass(DeadBranchPrune, "dead branch pruning")
64
+ pm.add_pass(InlineClosureLikes,
65
+ "inline calls to locally defined closures")
66
+ # typing
67
+ pm.add_pass(NopythonTypeInference, "nopython frontend")
68
+
69
+ if state.flags.auto_parallel.enabled:
70
+ pm.add_pass(PreParforPass, "Preprocessing for parfors")
71
+ if not state.flags.no_rewrites:
72
+ pm.add_pass(NopythonRewrites, "nopython rewrites")
73
+ if state.flags.auto_parallel.enabled:
74
+ pm.add_pass(ParforPass, "convert to parfors")
75
+ pm.add_pass(ParforFusionPass, "fuse parfors")
76
+ pm.add_pass(ParforPreLoweringPass, "parfor prelowering")
77
+
78
+ pm.add_pass(test_pass, "inline test")
79
+
80
+ # legalise
81
+ pm.add_pass(IRLegalization, "ensure IR is legal prior to lowering")
82
+ pm.add_pass(AnnotateTypes, "annotate types")
83
+ pm.add_pass(PreserveIR, "preserve IR")
84
+
85
+ # lower
86
+ if state.flags.auto_parallel.enabled:
87
+ pm.add_pass(NativeParforLowering, "native parfor lowering")
88
+ else:
89
+ pm.add_pass(NativeLowering, "native lowering")
90
+ pm.add_pass(NoPythonBackend, "nopython mode backend")
91
+ pm.add_pass(DumpParforDiagnostics, "dump parfor diagnostics")
92
+ return pm
93
+
94
+ class InlineTestPipeline(compiler.CompilerBase):
95
+ """compiler pipeline for testing inlining after optimization
96
+ """
97
+ def define_pipelines(self):
98
+ pm = gen_pipeline(self.state, InlineTestPass)
99
+ pm.finalize()
100
+ return [pm]
101
+
102
+ class TestInlining(TestCase):
103
+ """
104
+ Check that jitted inner functions are inlined into outer functions,
105
+ in nopython mode.
106
+ Note that not all inner functions are guaranteed to be inlined.
107
+ We just trust LLVM's inlining heuristics.
108
+ """
109
+
110
+ def make_pattern(self, fullname):
111
+ """
112
+ Make regexpr to match mangled name
113
+ """
114
+ parts = fullname.split('.')
115
+ return r'_ZN?' + r''.join([r'\d+{}'.format(p) for p in parts])
116
+
117
+ def assert_has_pattern(self, fullname, text):
118
+ pat = self.make_pattern(fullname)
119
+ self.assertIsNotNone(re.search(pat, text),
120
+ msg='expected {}'.format(pat))
121
+
122
+ def assert_not_has_pattern(self, fullname, text):
123
+ pat = self.make_pattern(fullname)
124
+ self.assertIsNone(re.search(pat, text),
125
+ msg='unexpected {}'.format(pat))
126
+
127
+ def test_inner_function(self):
128
+ from numba.tests.inlining_usecases import outer_simple, \
129
+ __name__ as prefix
130
+
131
+ with override_config('DUMP_ASSEMBLY', True):
132
+ with captured_stdout() as out:
133
+ cfunc = jit((types.int32,), nopython=True)(outer_simple)
134
+ self.assertPreciseEqual(cfunc(1), 4)
135
+ # Check the inner function was elided from the output (which also
136
+ # guarantees it was inlined into the outer function).
137
+ asm = out.getvalue()
138
+ self.assert_has_pattern('%s.outer_simple' % prefix, asm)
139
+ self.assert_not_has_pattern('%s.inner' % prefix, asm)
140
+
141
+ def test_multiple_inner_functions(self):
142
+ from numba.tests.inlining_usecases import outer_multiple, \
143
+ __name__ as prefix
144
+ # Same with multiple inner functions, and multiple calls to
145
+ # the same inner function (inner()). This checks that linking in
146
+ # the same library/module twice doesn't produce linker errors.
147
+ with override_config('DUMP_ASSEMBLY', True):
148
+ with captured_stdout() as out:
149
+ cfunc = jit((types.int32,), nopython=True)(outer_multiple)
150
+ self.assertPreciseEqual(cfunc(1), 6)
151
+ asm = out.getvalue()
152
+ self.assert_has_pattern('%s.outer_multiple' % prefix, asm)
153
+ self.assert_not_has_pattern('%s.more' % prefix, asm)
154
+ self.assert_not_has_pattern('%s.inner' % prefix, asm)
155
+
156
+ @skip_parfors_unsupported
157
+ def test_inline_call_after_parfor(self):
158
+ from numba.tests.inlining_usecases import __dummy__
159
+ # replace the call to make sure inlining doesn't cause label conflict
160
+ # with parfor body
161
+ def test_impl(A):
162
+ __dummy__()
163
+ return A.sum()
164
+ j_func = njit(parallel=True, pipeline_class=InlineTestPipeline)(
165
+ test_impl)
166
+ A = np.arange(10)
167
+ self.assertEqual(test_impl(A), j_func(A))
168
+
169
+ @skip_parfors_unsupported
170
+ def test_inline_update_target_def(self):
171
+
172
+ def test_impl(a):
173
+ if a == 1:
174
+ b = 2
175
+ else:
176
+ b = 3
177
+ return b
178
+
179
+ func_ir = compiler.run_frontend(test_impl)
180
+ blocks = list(func_ir.blocks.values())
181
+ for block in blocks:
182
+ for i, stmt in enumerate(block.body):
183
+ # match b = 2 and replace with lambda: 2
184
+ if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Var)
185
+ and guard(find_const, func_ir, stmt.value) == 2):
186
+ # replace expr with a dummy call
187
+ func_ir._definitions[stmt.target.name].remove(stmt.value)
188
+ stmt.value = ir.Expr.call(ir.Var(block.scope, "myvar", loc=stmt.loc), (), (), stmt.loc)
189
+ func_ir._definitions[stmt.target.name].append(stmt.value)
190
+ #func = g.py_func#
191
+ inline_closure_call(func_ir, {}, block, i, lambda: 2)
192
+ break
193
+
194
+ self.assertEqual(len(func_ir._definitions['b']), 2)
195
+
196
+ @skip_parfors_unsupported
197
+ def test_inline_var_dict_ret(self):
198
+ # make sure inline_closure_call returns the variable replacement dict
199
+ # and it contains the original variable name used in locals
200
+ @njit(locals={'b': types.float64})
201
+ def g(a):
202
+ b = a + 1
203
+ return b
204
+
205
+ def test_impl():
206
+ return g(1)
207
+
208
+ func_ir = compiler.run_frontend(test_impl)
209
+ blocks = list(func_ir.blocks.values())
210
+ for block in blocks:
211
+ for i, stmt in enumerate(block.body):
212
+ if (isinstance(stmt, ir.Assign)
213
+ and isinstance(stmt.value, ir.Expr)
214
+ and stmt.value.op == 'call'):
215
+ func_def = guard(get_definition, func_ir, stmt.value.func)
216
+ if (isinstance(func_def, (ir.Global, ir.FreeVar))
217
+ and isinstance(func_def.value, CPUDispatcher)):
218
+ py_func = func_def.value.py_func
219
+ _, var_map = inline_closure_call(
220
+ func_ir, py_func.__globals__, block, i, py_func)
221
+ break
222
+
223
+ self.assertTrue('b' in var_map)
224
+
225
+ @skip_parfors_unsupported
226
+ def test_inline_call_branch_pruning(self):
227
+ # branch pruning pass should run properly in inlining to enable
228
+ # functions with type checks
229
+ @njit
230
+ def foo(A=None):
231
+ if A is None:
232
+ return 2
233
+ else:
234
+ return A
235
+
236
+ def test_impl(A=None):
237
+ return foo(A)
238
+
239
+ @register_pass(analysis_only=False, mutates_CFG=True)
240
+ class PruningInlineTestPass(FunctionPass):
241
+ _name = "pruning_inline_test_pass"
242
+
243
+ def __init__(self):
244
+ FunctionPass.__init__(self)
245
+
246
+ def run_pass(self, state):
247
+ # assuming the function has one block with one call inside
248
+ assert len(state.func_ir.blocks) == 1
249
+ block = list(state.func_ir.blocks.values())[0]
250
+ for i, stmt in enumerate(block.body):
251
+ if (guard(find_callname, state.func_ir, stmt.value)
252
+ is not None):
253
+ inline_closure_call(state.func_ir, {}, block, i,
254
+ foo.py_func, state.typingctx, state.targetctx,
255
+ (state.typemap[stmt.value.args[0].name],),
256
+ state.typemap, state.calltypes)
257
+ break
258
+ return True
259
+
260
+ class InlineTestPipelinePrune(compiler.CompilerBase):
261
+
262
+ def define_pipelines(self):
263
+ pm = gen_pipeline(self.state, PruningInlineTestPass)
264
+ pm.finalize()
265
+ return [pm]
266
+
267
+ # make sure inline_closure_call runs in full pipeline
268
+ j_func = njit(pipeline_class=InlineTestPipelinePrune)(test_impl)
269
+ A = 3
270
+ self.assertEqual(test_impl(A), j_func(A))
271
+ self.assertEqual(test_impl(), j_func())
272
+
273
+ # make sure IR doesn't have branches
274
+ fir = j_func.overloads[(types.Omitted(None),)].metadata['preserved_ir']
275
+ fir.blocks = simplify_CFG(fir.blocks)
276
+ self.assertEqual(len(fir.blocks), 1)
277
+
278
+ if __name__ == '__main__':
279
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_ir_utils.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numba
2
+ from numba.tests.support import TestCase, unittest
3
+ from numba.core.registry import cpu_target
4
+ from numba.core.compiler import CompilerBase, Flags
5
+ from numba.core.compiler_machinery import PassManager
6
+ from numba.core import types, ir, bytecode, compiler, ir_utils, registry
7
+ from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode,
8
+ FixupArgs, IRProcessing,)
9
+
10
+ from numba.core.typed_passes import (NopythonTypeInference,
11
+ type_inference_stage, DeadCodeElimination)
12
+ from numba.experimental import jitclass
13
+
14
+ # global constant for testing find_const
15
+ GLOBAL_B = 11
16
+
17
+
18
+ @jitclass([('val', numba.core.types.List(numba.intp))])
19
+ class Dummy(object):
20
+ def __init__(self, val):
21
+ self.val = val
22
+
23
+
24
+ class TestIrUtils(TestCase):
25
+ """
26
+ Tests ir handling utility functions like find_callname.
27
+ """
28
+
29
+ def test_obj_func_match(self):
30
+ """Test matching of an object method (other than Array see #3449)
31
+ """
32
+
33
+ def test_func():
34
+ d = Dummy([1])
35
+ d.val.append(2)
36
+
37
+ test_ir = compiler.run_frontend(test_func)
38
+ typingctx = cpu_target.typing_context
39
+ targetctx = cpu_target.target_context
40
+ typing_res = type_inference_stage(
41
+ typingctx, targetctx, test_ir, (), None)
42
+ matched_call = ir_utils.find_callname(
43
+ test_ir, test_ir.blocks[0].body[7].value, typing_res.typemap)
44
+ self.assertTrue(isinstance(matched_call, tuple) and
45
+ len(matched_call) == 2 and
46
+ matched_call[0] == 'append')
47
+
48
+ def test_dead_code_elimination(self):
49
+
50
+ class Tester(CompilerBase):
51
+
52
+ @classmethod
53
+ def mk_pipeline(cls, args, return_type=None, flags=None, locals={},
54
+ library=None, typing_context=None,
55
+ target_context=None):
56
+ if not flags:
57
+ flags = Flags()
58
+ flags.nrt = True
59
+ if typing_context is None:
60
+ typing_context = registry.cpu_target.typing_context
61
+ if target_context is None:
62
+ target_context = registry.cpu_target.target_context
63
+ return cls(typing_context, target_context, library, args,
64
+ return_type, flags, locals)
65
+
66
+ def compile_to_ir(self, func, DCE=False):
67
+ """
68
+ Compile and return IR
69
+ """
70
+ func_id = bytecode.FunctionIdentity.from_function(func)
71
+ self.state.func_id = func_id
72
+ ExtractByteCode().run_pass(self.state)
73
+ state = self.state
74
+
75
+ name = "DCE_testing"
76
+ pm = PassManager(name)
77
+ pm.add_pass(TranslateByteCode, "analyzing bytecode")
78
+ pm.add_pass(FixupArgs, "fix up args")
79
+ pm.add_pass(IRProcessing, "processing IR")
80
+ pm.add_pass(NopythonTypeInference, "nopython frontend")
81
+ if DCE is True:
82
+ pm.add_pass(DeadCodeElimination, "DCE after typing")
83
+ pm.finalize()
84
+ pm.run(state)
85
+ return state.func_ir
86
+
87
+ def check_initial_ir(the_ir):
88
+ # dead stuff:
89
+ # a const int value 0xdead
90
+ # an assign of above into to variable `dead`
91
+ # a const int above 0xdeaddead
92
+ # an assign of said int to variable `deaddead`
93
+ # this is 2 statements to remove
94
+
95
+ self.assertEqual(len(the_ir.blocks), 1)
96
+ block = the_ir.blocks[0]
97
+ deads = []
98
+ for x in block.find_insts(ir.Assign):
99
+ if isinstance(getattr(x, 'target', None), ir.Var):
100
+ if 'dead' in getattr(x.target, 'name', ''):
101
+ deads.append(x)
102
+
103
+ self.assertEqual(len(deads), 2)
104
+ for d in deads:
105
+ # check the ir.Const is the definition and the value is expected
106
+ const_val = the_ir.get_definition(d.value)
107
+ self.assertTrue(int('0x%s' % d.target.name, 16),
108
+ const_val.value)
109
+
110
+ return deads
111
+
112
+ def check_dce_ir(the_ir):
113
+ self.assertEqual(len(the_ir.blocks), 1)
114
+ block = the_ir.blocks[0]
115
+ deads = []
116
+ consts = []
117
+ for x in block.find_insts(ir.Assign):
118
+ if isinstance(getattr(x, 'target', None), ir.Var):
119
+ if 'dead' in getattr(x.target, 'name', ''):
120
+ deads.append(x)
121
+ if isinstance(getattr(x, 'value', None), ir.Const):
122
+ consts.append(x)
123
+ self.assertEqual(len(deads), 0)
124
+
125
+ # check the consts to make sure there's no reference to 0xdead or
126
+ # 0xdeaddead
127
+ for x in consts:
128
+ self.assertTrue(x.value.value not in [0xdead, 0xdeaddead])
129
+
130
+ def foo(x):
131
+ y = x + 1
132
+ dead = 0xdead # noqa
133
+ z = y + 2
134
+ deaddead = 0xdeaddead # noqa
135
+ ret = z * z
136
+ return ret
137
+
138
+ test_pipeline = Tester.mk_pipeline((types.intp,))
139
+ no_dce = test_pipeline.compile_to_ir(foo)
140
+ removed = check_initial_ir(no_dce)
141
+
142
+ test_pipeline = Tester.mk_pipeline((types.intp,))
143
+ w_dce = test_pipeline.compile_to_ir(foo, DCE=True)
144
+ check_dce_ir(w_dce)
145
+
146
+ # check that the count of initial - removed = dce
147
+ self.assertEqual(len(no_dce.blocks[0].body) - len(removed),
148
+ len(w_dce.blocks[0].body))
149
+
150
+ def test_find_const_global(self):
151
+ """
152
+ Test find_const() for values in globals (ir.Global) and freevars
153
+ (ir.FreeVar) that are considered constants for compilation.
154
+ """
155
+ FREEVAR_C = 12
156
+
157
+ def foo(a):
158
+ b = GLOBAL_B
159
+ c = FREEVAR_C
160
+ return a + b + c
161
+
162
+ f_ir = compiler.run_frontend(foo)
163
+ block = f_ir.blocks[0]
164
+ const_b = None
165
+ const_c = None
166
+
167
+ for inst in block.body:
168
+ if isinstance(inst, ir.Assign) and inst.target.name == 'b':
169
+ const_b = ir_utils.guard(
170
+ ir_utils.find_const, f_ir, inst.target)
171
+ if isinstance(inst, ir.Assign) and inst.target.name == 'c':
172
+ const_c = ir_utils.guard(
173
+ ir_utils.find_const, f_ir, inst.target)
174
+
175
+ self.assertEqual(const_b, GLOBAL_B)
176
+ self.assertEqual(const_c, FREEVAR_C)
177
+
178
+ def test_flatten_labels(self):
179
+ """ tests flatten_labels """
180
+ def foo(a):
181
+ acc = 0
182
+ if a > 3:
183
+ acc += 1
184
+ if a > 19:
185
+ return 53
186
+ elif a < 1000:
187
+ if a >= 12:
188
+ acc += 1
189
+ for x in range(10):
190
+ acc -= 1
191
+ if acc < 2:
192
+ break
193
+ else:
194
+ acc += 7
195
+ else:
196
+ raise ValueError("some string")
197
+ # prevents inline of return on py310
198
+ py310_defeat1 = 1 # noqa
199
+ py310_defeat2 = 2 # noqa
200
+ py310_defeat3 = 3 # noqa
201
+ py310_defeat4 = 4 # noqa
202
+ return acc
203
+
204
+ def bar(a):
205
+ acc = 0
206
+ z = 12
207
+ if a > 3:
208
+ acc += 1
209
+ z += 12
210
+ if a > 19:
211
+ z += 12
212
+ return 53
213
+ elif a < 1000:
214
+ if a >= 12:
215
+ z += 12
216
+ acc += 1
217
+ for x in range(10):
218
+ z += 12
219
+ acc -= 1
220
+ if acc < 2:
221
+ break
222
+ else:
223
+ z += 12
224
+ acc += 7
225
+ else:
226
+ raise ValueError("some string")
227
+ py310_defeat1 = 1 # noqa
228
+ py310_defeat2 = 2 # noqa
229
+ py310_defeat3 = 3 # noqa
230
+ py310_defeat4 = 4 # noqa
231
+ return acc
232
+
233
+ def baz(a):
234
+ acc = 0
235
+ if a > 3:
236
+ acc += 1
237
+ if a > 19:
238
+ return 53
239
+ else: # extra control flow in comparison to foo
240
+ return 55
241
+ elif a < 1000:
242
+ if a >= 12:
243
+ acc += 1
244
+ for x in range(10):
245
+ acc -= 1
246
+ if acc < 2:
247
+ break
248
+ else:
249
+ acc += 7
250
+ else:
251
+ raise ValueError("some string")
252
+ py310_defeat1 = 1 # noqa
253
+ py310_defeat2 = 2 # noqa
254
+ py310_defeat3 = 3 # noqa
255
+ py310_defeat4 = 4 # noqa
256
+ return acc
257
+
258
+ def get_flat_cfg(func):
259
+ func_ir = ir_utils.compile_to_numba_ir(func, dict())
260
+ flat_blocks = ir_utils.flatten_labels(func_ir.blocks)
261
+ self.assertEqual(max(flat_blocks.keys()) + 1, len(func_ir.blocks))
262
+ return ir_utils.compute_cfg_from_blocks(flat_blocks)
263
+
264
+ foo_cfg = get_flat_cfg(foo)
265
+ bar_cfg = get_flat_cfg(bar)
266
+ baz_cfg = get_flat_cfg(baz)
267
+
268
+ self.assertEqual(foo_cfg, bar_cfg)
269
+ self.assertNotEqual(foo_cfg, baz_cfg)
270
+
271
+
272
+ if __name__ == "__main__":
273
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_jitmethod.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+
5
+ from numba import jit
6
+ from numba.tests.support import override_config
7
+
8
+
9
+ class TestJITMethod(unittest.TestCase):
10
+ def test_bound_jit_method_with_loop_lift(self):
11
+ class Something(object):
12
+ def __init__(self, x0):
13
+ self.x0 = x0
14
+
15
+ @jit(forceobj=True)
16
+ def method(self, x):
17
+ a = np.empty(shape=5, dtype=np.float32)
18
+ x0 = self.x0
19
+
20
+ for i in range(a.shape[0]):
21
+ a[i] = x0 * x
22
+
23
+ return a
24
+
25
+ something = Something(3)
26
+ np.testing.assert_array_equal(something.method(5),
27
+ np.array([15, 15, 15, 15, 15], dtype=np.float32))
28
+
29
+ # Check that loop lifting in nopython mode was successful
30
+ [cres] = something.method.overloads.values()
31
+ jitloop = cres.lifted[0]
32
+ [loopcres] = jitloop.overloads.values()
33
+ self.assertTrue(loopcres.fndesc.native)
34
+
35
+ def test_unbound_jit_method(self):
36
+ class Something(object):
37
+ def __init__(self, x0):
38
+ self.x0 = x0
39
+
40
+ @jit(forceobj=True)
41
+ def method(self):
42
+ return self.x0
43
+
44
+ something = Something(3)
45
+ self.assertEqual(Something.method(something), 3)
46
+
47
+
48
+ class TestDisabledJIT(unittest.TestCase):
49
+ def test_decorated_function(self):
50
+ with override_config('DISABLE_JIT', True):
51
+ def method(x):
52
+ return x
53
+ jitted = jit(method)
54
+
55
+ self.assertEqual(jitted, method)
56
+ self.assertEqual(10, method(10))
57
+ self.assertEqual(10, jitted(10))
58
+
59
+ def test_decorated_function_with_kwargs(self):
60
+ with override_config('DISABLE_JIT', True):
61
+ def method(x):
62
+ return x
63
+ jitted = jit(nopython=True)(method)
64
+
65
+ self.assertEqual(jitted, method)
66
+ self.assertEqual(10, method(10))
67
+ self.assertEqual(10, jitted(10))
68
+
69
+ if __name__ == '__main__':
70
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_listimpl.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing C implementation of the numba typed-list
3
+ """
4
+
5
+ import ctypes
6
+ import struct
7
+
8
+ from numba.tests.support import TestCase
9
+ from numba import _helperlib
10
+
11
+
12
+ LIST_OK = 0
13
+ LIST_ERR_INDEX = -1
14
+ LIST_ERR_NO_MEMORY = -2
15
+ LIST_ERR_MUTATED = -3
16
+ LIST_ERR_ITER_EXHAUSTED = -4
17
+ LIST_ERR_IMMUTABLE = -5
18
+
19
+
20
+ class List(object):
21
+ """A wrapper around the C-API to provide a minimal list object for
22
+ testing.
23
+ """
24
+ def __init__(self, tc, item_size, allocated):
25
+ """
26
+ Parameters
27
+ ----------
28
+ tc : TestCase instance
29
+ item_size : int
30
+ byte size for the items
31
+ allocated : int
32
+ number of items to allocate for
33
+ """
34
+ self.tc = tc
35
+ self.item_size = item_size
36
+ self.lp = self.list_new(item_size, allocated)
37
+
38
+ # The following methods implement part of the list API
39
+
40
+ def __del__(self):
41
+ self.tc.numba_list_free(self.lp)
42
+
43
+ def __len__(self):
44
+ return self.list_length()
45
+
46
+ def __setitem__(self, i, item):
47
+ return self.list_setitem(i, item)
48
+
49
+ def __getitem__(self, i):
50
+ return self.list_getitem(i)
51
+
52
+ def __iter__(self):
53
+ return ListIter(self)
54
+
55
+ def __delitem__(self, i):
56
+ self.list_delitem(i)
57
+
58
+ def handle_index(self, i):
59
+ # handling negative indices is done at the compiler level, so we only
60
+ # support -1 to be last element of the list here
61
+ if i < -1 or len(self) == 0:
62
+ IndexError("list index out of range")
63
+ elif i == -1:
64
+ i = len(self) - 1
65
+ return i
66
+
67
+ @property
68
+ def allocated(self):
69
+ return self.list_allocated()
70
+
71
+ @property
72
+ def is_mutable(self):
73
+ return self.list_is_mutable()
74
+
75
+ def set_mutable(self):
76
+ return self.list_set_is_mutable(1)
77
+
78
+ def set_immutable(self):
79
+ return self.list_set_is_mutable(0)
80
+
81
+ def append(self, item):
82
+ self.list_append(item)
83
+
84
+ def pop(self, i=-1):
85
+ return self.list_pop(i)
86
+
87
+ # The methods below are higher-level wrappers for the C-API wrappers
88
+
89
+ def list_new(self, item_size, allocated):
90
+ lp = ctypes.c_void_p()
91
+ status = self.tc.numba_list_new(
92
+ ctypes.byref(lp), item_size, allocated,
93
+ )
94
+ self.tc.assertEqual(status, LIST_OK)
95
+ return lp
96
+
97
+ def list_length(self):
98
+ return self.tc.numba_list_length(self.lp)
99
+
100
+ def list_allocated(self):
101
+ return self.tc.numba_list_allocated(self.lp)
102
+
103
+ def list_is_mutable(self):
104
+ return self.tc.numba_list_is_mutable(self.lp)
105
+
106
+ def list_set_is_mutable(self, is_mutable):
107
+ return self.tc.numba_list_set_is_mutable(self.lp, is_mutable)
108
+
109
+ def list_setitem(self, i, item):
110
+ status = self.tc.numba_list_setitem(self.lp, i, item)
111
+ if status == LIST_ERR_INDEX:
112
+ raise IndexError("list index out of range")
113
+ elif status == LIST_ERR_IMMUTABLE:
114
+ raise ValueError("list is immutable")
115
+ else:
116
+ self.tc.assertEqual(status, LIST_OK)
117
+
118
+ def list_getitem(self, i):
119
+ i = self.handle_index(i)
120
+ item_out_buffer = ctypes.create_string_buffer(self.item_size)
121
+ status = self.tc.numba_list_getitem(self.lp, i, item_out_buffer)
122
+ if status == LIST_ERR_INDEX:
123
+ raise IndexError("list index out of range")
124
+ else:
125
+ self.tc.assertEqual(status, LIST_OK)
126
+ return item_out_buffer.raw
127
+
128
+ def list_append(self, item):
129
+ status = self.tc.numba_list_append(self.lp, item)
130
+ if status == LIST_ERR_IMMUTABLE:
131
+ raise ValueError("list is immutable")
132
+ self.tc.assertEqual(status, LIST_OK)
133
+
134
+ def list_pop(self, i):
135
+ # pop is getitem and delitem
136
+ i = self.handle_index(i)
137
+ item = self.list_getitem(i)
138
+ self.list_delitem(i)
139
+ return item
140
+
141
+ def list_delitem(self, i):
142
+ # special case slice
143
+ if isinstance(i, slice):
144
+ status = self.tc.numba_list_delete_slice(self.lp,
145
+ i.start,
146
+ i.stop,
147
+ i.step)
148
+ if status == LIST_ERR_IMMUTABLE:
149
+ raise ValueError("list is immutable")
150
+ self.tc.assertEqual(status, LIST_OK)
151
+ # must be an integer, defer to delitem
152
+ else:
153
+ i = self.handle_index(i)
154
+ status = self.tc.numba_list_delitem(self.lp, i)
155
+ if status == LIST_ERR_INDEX:
156
+ raise IndexError("list index out of range")
157
+ elif status == LIST_ERR_IMMUTABLE:
158
+ raise ValueError("list is immutable")
159
+ self.tc.assertEqual(status, LIST_OK)
160
+
161
+ def list_iter(self, itptr):
162
+ self.tc.numba_list_iter(itptr, self.lp)
163
+
164
+ def list_iter_next(self, itptr):
165
+ bi = ctypes.c_void_p(0)
166
+ status = self.tc.numba_list_iter_next(
167
+ itptr, ctypes.byref(bi),
168
+ )
169
+ if status == LIST_ERR_MUTATED:
170
+ raise ValueError('list mutated')
171
+ elif status == LIST_ERR_ITER_EXHAUSTED:
172
+ raise StopIteration
173
+ else:
174
+ self.tc.assertGreaterEqual(status, 0)
175
+ item = (ctypes.c_char * self.item_size).from_address(bi.value)
176
+ return item.value
177
+
178
+
179
+ class ListIter(object):
180
+ """An iterator for the `List`.
181
+ """
182
+ def __init__(self, parent):
183
+ self.parent = parent
184
+ itsize = self.parent.tc.numba_list_iter_sizeof()
185
+ self.it_state_buf = (ctypes.c_char_p * itsize)(0)
186
+ self.it = ctypes.cast(self.it_state_buf, ctypes.c_void_p)
187
+ self.parent.list_iter(self.it)
188
+
189
+ def __iter__(self):
190
+ return self
191
+
192
+ def __next__(self):
193
+ return self.parent.list_iter_next(self.it)
194
+
195
+ next = __next__ # needed for py2 only
196
+
197
+
198
+ class TestListImpl(TestCase):
199
+ def setUp(self):
200
+ """Bind to the c_helper library and provide the ctypes wrapper.
201
+ """
202
+ list_t = ctypes.c_void_p
203
+ iter_t = ctypes.c_void_p
204
+
205
+ def wrap(name, restype, argtypes=()):
206
+ proto = ctypes.CFUNCTYPE(restype, *argtypes)
207
+ return proto(_helperlib.c_helpers[name])
208
+
209
+ # numba_test_list()
210
+ self.numba_test_list = wrap(
211
+ 'test_list',
212
+ ctypes.c_int,
213
+ )
214
+
215
+ # numba_list_new(NB_List *l, Py_ssize_t item_size, Py_ssize_t allocated)
216
+ self.numba_list_new = wrap(
217
+ 'list_new',
218
+ ctypes.c_int,
219
+ [ctypes.POINTER(list_t), ctypes.c_ssize_t, ctypes.c_ssize_t],
220
+ )
221
+ # numba_list_free(NB_List *l)
222
+ self.numba_list_free = wrap(
223
+ 'list_free',
224
+ None,
225
+ [list_t],
226
+ )
227
+ # numba_list_length(NB_List *l)
228
+ self.numba_list_length = wrap(
229
+ 'list_length',
230
+ ctypes.c_int,
231
+ [list_t],
232
+ )
233
+ # numba_list_allocated(NB_List *l)
234
+ self.numba_list_allocated = wrap(
235
+ 'list_allocated',
236
+ ctypes.c_int,
237
+ [list_t],
238
+ )
239
+ # numba_list_is_mutable(NB_List *lp)
240
+ self.numba_list_is_mutable = wrap(
241
+ 'list_is_mutable',
242
+ ctypes.c_int,
243
+ [list_t],
244
+ )
245
+ # numba_list_set_is_mutable(NB_List *lp, int is_mutable)
246
+ self.numba_list_set_is_mutable = wrap(
247
+ 'list_set_is_mutable',
248
+ None,
249
+ [list_t, ctypes.c_int],
250
+ )
251
+ # numba_list_setitem(NB_List *l, Py_ssize_t i, const char *item)
252
+ self.numba_list_setitem = wrap(
253
+ 'list_setitem',
254
+ ctypes.c_int,
255
+ [list_t, ctypes.c_ssize_t, ctypes.c_char_p],
256
+ )
257
+ # numba_list_append(NB_List *l, const char *item)
258
+ self.numba_list_append = wrap(
259
+ 'list_append',
260
+ ctypes.c_int,
261
+ [list_t, ctypes.c_char_p],
262
+ )
263
+ # numba_list_getitem(NB_List *l, Py_ssize_t i, char *out)
264
+ self.numba_list_getitem = wrap(
265
+ 'list_getitem',
266
+ ctypes.c_int,
267
+ [list_t, ctypes.c_ssize_t, ctypes.c_char_p],
268
+ )
269
+ # numba_list_delitem(NB_List *l, Py_ssize_t i)
270
+ self.numba_list_delitem = wrap(
271
+ 'list_delitem',
272
+ ctypes.c_int,
273
+ [list_t, ctypes.c_ssize_t],
274
+ )
275
+ # numba_list_delete_slice(NB_List *l,
276
+ # Py_ssize_t start,
277
+ # Py_ssize_t stop,
278
+ # Py_ssize_t step)
279
+ self.numba_list_delete_slice = wrap(
280
+ 'list_delete_slice',
281
+ ctypes.c_int,
282
+ [list_t, ctypes.c_ssize_t, ctypes.c_ssize_t, ctypes.c_ssize_t],
283
+ )
284
+ # numba_list_iter_sizeof()
285
+ self.numba_list_iter_sizeof = wrap(
286
+ 'list_iter_sizeof',
287
+ ctypes.c_size_t,
288
+ )
289
+ # numba_list_iter(NB_ListIter *it, NB_List *l)
290
+ self.numba_list_iter = wrap(
291
+ 'list_iter',
292
+ None,
293
+ [
294
+ iter_t,
295
+ list_t,
296
+ ],
297
+ )
298
+ # numba_list_iter_next(NB_ListIter *it, const char **item_ptr)
299
+ self.numba_list_iter_next = wrap(
300
+ 'list_iter_next',
301
+ ctypes.c_int,
302
+ [
303
+ iter_t, # it
304
+ ctypes.POINTER(ctypes.c_void_p), # item_ptr
305
+ ],
306
+ )
307
+
308
+ def test_simple_c_test(self):
309
+ # Runs the basic test in C.
310
+ ret = self.numba_test_list()
311
+ self.assertEqual(ret, 0)
312
+
313
+ def test_length(self):
314
+ l = List(self, 8, 0)
315
+ self.assertEqual(len(l), 0)
316
+
317
+ def test_allocation(self):
318
+ for i in range(16):
319
+ l = List(self, 8, i)
320
+ self.assertEqual(len(l), 0)
321
+ self.assertEqual(l.allocated, i)
322
+
323
+ def test_append_get_string(self):
324
+ l = List(self, 8, 1)
325
+ l.append(b"abcdefgh")
326
+ self.assertEqual(len(l), 1)
327
+ r = l[0]
328
+ self.assertEqual(r, b"abcdefgh")
329
+
330
+ def test_append_get_int(self):
331
+ l = List(self, 8, 1)
332
+ l.append(struct.pack("q", 1))
333
+ self.assertEqual(len(l), 1)
334
+ r = struct.unpack("q", l[0])[0]
335
+ self.assertEqual(r, 1)
336
+
337
+ def test_append_get_string_realloc(self):
338
+ l = List(self, 8, 1)
339
+ l.append(b"abcdefgh")
340
+ self.assertEqual(len(l), 1)
341
+ l.append(b"hijklmno")
342
+ self.assertEqual(len(l), 2)
343
+ r = l[1]
344
+ self.assertEqual(r, b"hijklmno")
345
+
346
+ def test_set_item_getitem_index_error(self):
347
+ l = List(self, 8, 0)
348
+ with self.assertRaises(IndexError):
349
+ l[0]
350
+ with self.assertRaises(IndexError):
351
+ l[0] = b"abcdefgh"
352
+
353
+ def test_iter(self):
354
+ l = List(self, 1, 0)
355
+ values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h']
356
+ for i in values:
357
+ l.append(i)
358
+ received = []
359
+ for j in l:
360
+ received.append(j)
361
+ self.assertEqual(values, received)
362
+
363
+ def test_pop(self):
364
+ l = List(self, 1, 0)
365
+ values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h']
366
+ for i in values:
367
+ l.append(i)
368
+ self.assertEqual(len(l), 8)
369
+
370
+ received = l.pop()
371
+ self.assertEqual(b'h', received)
372
+ self.assertEqual(len(l), 7)
373
+ received = [j for j in l]
374
+ self.assertEqual(received, values[:-1])
375
+
376
+ received = l.pop(0)
377
+ self.assertEqual(b'a', received)
378
+ self.assertEqual(len(l), 6)
379
+
380
+ received = l.pop(2)
381
+ self.assertEqual(b'd', received)
382
+ self.assertEqual(len(l), 5)
383
+
384
+ expected = [b'b', b'c', b'e', b'f', b'g']
385
+ received = [j for j in l]
386
+ self.assertEqual(received, expected)
387
+
388
+ def test_pop_index_error(self):
389
+ l = List(self, 8, 0)
390
+ with self.assertRaises(IndexError):
391
+ l.pop()
392
+
393
+ def test_pop_byte(self):
394
+ l = List(self, 4, 0)
395
+ values = [b'aaaa', b'bbbb', b'cccc', b'dddd',
396
+ b'eeee', b'ffff', b'gggg', b'hhhhh']
397
+ for i in values:
398
+ l.append(i)
399
+ self.assertEqual(len(l), 8)
400
+
401
+ received = l.pop()
402
+ self.assertEqual(b'hhhh', received)
403
+ self.assertEqual(len(l), 7)
404
+ received = [j for j in l]
405
+ self.assertEqual(received, values[:-1])
406
+
407
+ received = l.pop(0)
408
+ self.assertEqual(b'aaaa', received)
409
+ self.assertEqual(len(l), 6)
410
+
411
+ received = l.pop(2)
412
+ self.assertEqual(b'dddd', received)
413
+ self.assertEqual(len(l), 5)
414
+
415
+ expected = [b'bbbb', b'cccc', b'eeee', b'ffff', b'gggg']
416
+ received = [j for j in l]
417
+ self.assertEqual(received, expected)
418
+
419
+ def test_delitem(self):
420
+ l = List(self, 1, 0)
421
+ values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h']
422
+ for i in values:
423
+ l.append(i)
424
+ self.assertEqual(len(l), 8)
425
+
426
+ # delete first item
427
+ del l[0]
428
+ self.assertEqual(len(l), 7)
429
+ self.assertEqual(list(l), values[1:])
430
+ # delete last item
431
+ del l[-1]
432
+ self.assertEqual(len(l), 6)
433
+ self.assertEqual(list(l), values[1:-1])
434
+ # delete item from middle
435
+ del l[2]
436
+ self.assertEqual(len(l), 5)
437
+ self.assertEqual(list(l), [b'b', b'c', b'e', b'f', b'g'])
438
+
439
+ def test_delete_slice(self):
440
+ l = List(self, 1, 0)
441
+ values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h']
442
+ for i in values:
443
+ l.append(i)
444
+ self.assertEqual(len(l), 8)
445
+
446
+ # delete every second item
447
+ # no slice default normalization here, be explicit about start anb stop
448
+ del l[0:8:2]
449
+ self.assertEqual(len(l), 4)
450
+ self.assertEqual(list(l), values[1:8:2])
451
+
452
+ # delete first item
453
+ del l[0:1:1]
454
+ self.assertEqual(len(l), 3)
455
+ self.assertEqual(list(l), [b'd', b'f', b'h'])
456
+
457
+ # delete last item
458
+ del l[2:3:1]
459
+ self.assertEqual(len(l), 2)
460
+ self.assertEqual(list(l), [b'd', b'f'])
461
+
462
+ # delete all left items
463
+ del l[0:2:1]
464
+ self.assertEqual(len(l), 0)
465
+ self.assertEqual(list(l), [])
466
+
467
+ def check_sizing(self, item_size, nmax):
468
+ # Helper to verify different item_sizes
469
+ l = List(self, item_size, 0)
470
+
471
+ def make_item(v):
472
+ tmp = "{:0{}}".format(nmax - v - 1, item_size).encode("latin-1")
473
+ return tmp[:item_size]
474
+
475
+ for i in range(nmax):
476
+ l.append(make_item(i))
477
+
478
+ self.assertEqual(len(l), nmax)
479
+
480
+ for i in range(nmax):
481
+ self.assertEqual(l[i], make_item(i))
482
+
483
+ def test_sizing(self):
484
+ # Check different sizes of the key & value.
485
+ for i in range(1, 16):
486
+ self.check_sizing(item_size=i, nmax=2**i)
487
+
488
+ def test_mutability(self):
489
+ # setup and populate a singleton
490
+ l = List(self, 8, 1)
491
+ one = struct.pack("q", 1)
492
+ l.append(one)
493
+ self.assertTrue(l.is_mutable)
494
+ self.assertEqual(len(l), 1)
495
+ r = struct.unpack("q", l[0])[0]
496
+ self.assertEqual(r, 1)
497
+
498
+ # set to immutable and test guards
499
+ l.set_immutable()
500
+ self.assertFalse(l.is_mutable)
501
+ # append
502
+ with self.assertRaises(ValueError) as raises:
503
+ l.append(one)
504
+ self.assertIn("list is immutable", str(raises.exception))
505
+ # setitem
506
+ with self.assertRaises(ValueError) as raises:
507
+ l[0] = one
508
+ self.assertIn("list is immutable", str(raises.exception))
509
+ # pop
510
+ with self.assertRaises(ValueError) as raises:
511
+ l.pop()
512
+ self.assertIn("list is immutable", str(raises.exception))
513
+ # delitem with index
514
+ with self.assertRaises(ValueError) as raises:
515
+ del l[0]
516
+ self.assertIn("list is immutable", str(raises.exception))
517
+ # delitem with slice
518
+ with self.assertRaises(ValueError) as raises:
519
+ del l[0:1:1]
520
+ self.assertIn("list is immutable", str(raises.exception))
521
+ l.set_mutable()
522
+
523
+ # check that nothing has changed
524
+ self.assertTrue(l.is_mutable)
525
+ self.assertEqual(len(l), 1)
526
+ r = struct.unpack("q", l[0])[0]
527
+ self.assertEqual(r, 1)
lib/python3.10/site-packages/numba/tests/test_llvm_version_check.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import sys
3
+
4
+ import unittest
5
+
6
+
7
+ class TestLlvmVersion(unittest.TestCase):
8
+
9
+ def test_llvmlite_version(self):
10
+ # test the system it's running on
11
+ import llvmlite
12
+ import numba
13
+ self.assertTrue(numba.__version__)
14
+
15
+ llvmlite_version = llvmlite.__version__
16
+ def cleanup():
17
+ llvmlite.__version__ = llvmlite_version
18
+ self.addCleanup(cleanup)
19
+
20
+ # explicitly test all 3 cases of version string
21
+ ver = numba._min_llvmlite_version
22
+ version_pass = '%d.%d.%d' % ver
23
+ git_version_pass = '%d.%d.%d-10-g92584ed' % ver
24
+ rc_version_pass = '%d.%d.%drc1' % (ver[0], ver[1], ver[2] + 1)
25
+ version_fail = '%d.%d.0' % (ver[0], ver[1] - 1)
26
+ git_version_fail = '%d.%d.9-10-g92584ed' % (ver[0], ver[1] - 1)
27
+
28
+ ver_pass = (version_pass, git_version_pass, rc_version_pass)
29
+ ver_fail = (version_fail, git_version_fail)
30
+ for v in ver_pass:
31
+ llvmlite.__version__ = v
32
+ importlib.reload(numba)
33
+ self.assertTrue(numba.__version__)
34
+
35
+ for v in ver_fail:
36
+ with self.assertRaises(ImportError):
37
+ llvmlite.__version__ = v
38
+ importlib.reload(numba)
39
+
40
+
41
+ if __name__ == '__main__':
42
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_mandelbrot.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from numba import njit
3
+ from numba.core import types
4
+
5
+
6
+ def is_in_mandelbrot(c):
7
+ i = 0
8
+ z = 0.0j
9
+ for i in range(100):
10
+ z = z ** 2 + c
11
+ if (z.real * z.real + z.imag * z.imag) >= 4:
12
+ return False
13
+ return True
14
+
15
+
16
+ class TestMandelbrot(unittest.TestCase):
17
+
18
+ def test_mandelbrot(self):
19
+ pyfunc = is_in_mandelbrot
20
+ cfunc = njit((types.complex64,))(pyfunc)
21
+
22
+ points = [0+0j, 1+0j, 0+1j, 1+1j, 0.1+0.1j]
23
+ for p in points:
24
+ self.assertEqual(cfunc(p), pyfunc(p))
25
+
26
+
27
+ if __name__ == '__main__':
28
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_mathlib.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import math
3
+ import sys
4
+ import unittest
5
+ import warnings
6
+
7
+ import numpy as np
8
+
9
+ from numba import njit, types
10
+ from numba.tests.support import TestCase
11
+ from numba.np import numpy_support
12
+
13
+
14
+ def sin(x):
15
+ return math.sin(x)
16
+
17
+
18
+ def cos(x):
19
+ return math.cos(x)
20
+
21
+
22
+ def tan(x):
23
+ return math.tan(x)
24
+
25
+
26
+ def sinh(x):
27
+ return math.sinh(x)
28
+
29
+
30
+ def cosh(x):
31
+ return math.cosh(x)
32
+
33
+
34
+ def tanh(x):
35
+ return math.tanh(x)
36
+
37
+
38
+ def asin(x):
39
+ return math.asin(x)
40
+
41
+
42
+ def acos(x):
43
+ return math.acos(x)
44
+
45
+
46
+ def atan(x):
47
+ return math.atan(x)
48
+
49
+
50
+ def atan2(y, x):
51
+ return math.atan2(y, x)
52
+
53
+
54
+ def asinh(x):
55
+ return math.asinh(x)
56
+
57
+
58
+ def acosh(x):
59
+ return math.acosh(x)
60
+
61
+
62
+ def atanh(x):
63
+ return math.atanh(x)
64
+
65
+
66
+ def sqrt(x):
67
+ return math.sqrt(x)
68
+
69
+
70
+ def npy_sqrt(x):
71
+ return np.sqrt(x)
72
+
73
+
74
+ def exp(x):
75
+ return math.exp(x)
76
+
77
+
78
+ def expm1(x):
79
+ return math.expm1(x)
80
+
81
+
82
+ def log(x):
83
+ return math.log(x)
84
+
85
+
86
+ def log1p(x):
87
+ return math.log1p(x)
88
+
89
+
90
+ def log10(x):
91
+ return math.log10(x)
92
+
93
+
94
+ def log2(x):
95
+ return math.log2(x)
96
+
97
+
98
+ def floor(x):
99
+ return math.floor(x)
100
+
101
+
102
+ def ceil(x):
103
+ return math.ceil(x)
104
+
105
+
106
+ def trunc(x):
107
+ return math.trunc(x)
108
+
109
+
110
+ def isnan(x):
111
+ return math.isnan(x)
112
+
113
+
114
+ def isinf(x):
115
+ return math.isinf(x)
116
+
117
+
118
+ def isfinite(x):
119
+ return math.isfinite(x)
120
+
121
+
122
+ def hypot(x, y):
123
+ return math.hypot(x, y)
124
+
125
+
126
+ def nextafter(x, y):
127
+ return math.nextafter(x, y)
128
+
129
+
130
+ def degrees(x):
131
+ return math.degrees(x)
132
+
133
+
134
+ def radians(x):
135
+ return math.radians(x)
136
+
137
+
138
+ def erf(x):
139
+ return math.erf(x)
140
+
141
+
142
+ def erfc(x):
143
+ return math.erfc(x)
144
+
145
+
146
+ def gamma(x):
147
+ return math.gamma(x)
148
+
149
+
150
+ def lgamma(x):
151
+ return math.lgamma(x)
152
+
153
+
154
+ def pow(x, y):
155
+ return math.pow(x, y)
156
+
157
+ def gcd(x, y):
158
+ return math.gcd(x, y)
159
+
160
+ def copysign(x, y):
161
+ return math.copysign(x, y)
162
+
163
+
164
+ def frexp(x):
165
+ return math.frexp(x)
166
+
167
+
168
+ def ldexp(x, e):
169
+ return math.ldexp(x, e)
170
+
171
+
172
+ def get_constants():
173
+ return math.pi, math.e
174
+
175
+
176
+ class TestMathLib(TestCase):
177
+
178
+ def test_constants(self):
179
+ cfunc = njit(get_constants)
180
+ self.assertPreciseEqual(cfunc(), cfunc.py_func())
181
+
182
+ def run_unary(self, pyfunc, x_types, x_values, prec='exact', **kwargs):
183
+ cfunc = njit(pyfunc)
184
+ for tx, vx in zip(x_types, x_values):
185
+ got = cfunc(vx)
186
+ expected = pyfunc(vx)
187
+ actual_prec = 'single' if tx is types.float32 else prec
188
+ msg = 'for input %r' % (vx,)
189
+ self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg,
190
+ **kwargs)
191
+
192
+ def run_binary(self, pyfunc, x_types, x_values, y_values, prec='exact'):
193
+ cfunc = njit(pyfunc)
194
+ for ty, x, y in zip(x_types, x_values, y_values):
195
+ got = cfunc(x, y)
196
+ expected = pyfunc(x, y)
197
+ actual_prec = 'single' if ty is types.float32 else prec
198
+ msg = 'for inputs (%r, %r)' % (x, y)
199
+ self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg)
200
+
201
+ def check_predicate_func(self, pyfunc):
202
+ x_types = [types.int16, types.int32, types.int64,
203
+ types.uint16, types.uint32, types.uint64,
204
+ types.float32, types.float32, types.float32,
205
+ types.float64, types.float64, types.float64]
206
+ x_values = [0, 0, 0, 0, 0, 0,
207
+ float('inf'), 0.0, float('nan'),
208
+ float('inf'), 0.0, float('nan')]
209
+ self.run_unary(pyfunc, x_types, x_values)
210
+
211
+ def test_sin(self):
212
+ pyfunc = sin
213
+ x_types = [types.int16, types.int32, types.int64,
214
+ types.uint16, types.uint32, types.uint64,
215
+ types.float32, types.float64]
216
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
217
+ self.run_unary(pyfunc, x_types, x_values)
218
+
219
+ @unittest.skipIf(sys.platform == 'win32',
220
+ "not exactly equal on win32 (issue #597)")
221
+ def test_cos(self):
222
+ pyfunc = cos
223
+ x_types = [types.int16, types.int32, types.int64,
224
+ types.uint16, types.uint32, types.uint64,
225
+ types.float32, types.float64]
226
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
227
+ self.run_unary(pyfunc, x_types, x_values)
228
+
229
+ def test_tan(self):
230
+ pyfunc = tan
231
+ x_types = [types.int16, types.int32, types.int64,
232
+ types.uint16, types.uint32, types.uint64,
233
+ types.float32, types.float64]
234
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
235
+ self.run_unary(pyfunc, x_types, x_values)
236
+
237
+ def test_sqrt(self):
238
+ pyfunc = sqrt
239
+ x_types = [types.int16, types.int32, types.int64,
240
+ types.uint16, types.uint32, types.uint64,
241
+ types.float32, types.float64]
242
+ x_values = [2, 1, 2, 2, 1, 2, .1, .2]
243
+ self.run_unary(pyfunc, x_types, x_values)
244
+
245
+ def test_npy_sqrt(self):
246
+ pyfunc = npy_sqrt
247
+ x_values = [2, 1, 2, 2, 1, 2, .1, .2]
248
+ # XXX poor precision for int16 inputs
249
+ x_types = [types.int16, types.uint16]
250
+ self.run_unary(pyfunc, x_types, x_values, prec='single')
251
+ x_types = [types.int32, types.int64,
252
+ types.uint32, types.uint64,
253
+ types.float32, types.float64]
254
+ self.run_unary(pyfunc, x_types, x_values)
255
+
256
+ def test_exp(self):
257
+ pyfunc = exp
258
+ x_types = [types.int16, types.int32, types.int64,
259
+ types.uint16, types.uint32, types.uint64,
260
+ types.float32, types.float64]
261
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
262
+ self.run_unary(pyfunc, x_types, x_values)
263
+
264
+ def test_expm1(self):
265
+ pyfunc = expm1
266
+ x_types = [types.int16, types.int32, types.int64,
267
+ types.uint16, types.uint32, types.uint64,
268
+ types.float32, types.float64]
269
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
270
+ self.run_unary(pyfunc, x_types, x_values)
271
+
272
+ def test_log(self):
273
+ pyfunc = log
274
+ x_types = [types.int16, types.int32, types.int64,
275
+ types.uint16, types.uint32, types.uint64,
276
+ types.float32, types.float64]
277
+ x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1]
278
+ self.run_unary(pyfunc, x_types, x_values)
279
+
280
+ def test_log1p(self):
281
+ pyfunc = log1p
282
+ x_types = [types.int16, types.int32, types.int64,
283
+ types.uint16, types.uint32, types.uint64,
284
+ types.float32, types.float64]
285
+ x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1]
286
+ self.run_unary(pyfunc, x_types, x_values)
287
+
288
+ def test_log10(self):
289
+ pyfunc = log10
290
+ x_types = [types.int16, types.int32, types.int64,
291
+ types.uint16, types.uint32, types.uint64,
292
+ types.float32, types.float64]
293
+ x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1]
294
+ self.run_unary(pyfunc, x_types, x_values)
295
+
296
+ def test_log2(self):
297
+ pyfunc = log2
298
+ x_types = [types.int16, types.int32, types.int64,
299
+ types.uint16, types.uint32, types.uint64,
300
+ types.float32, types.float64]
301
+ x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1]
302
+ self.run_unary(pyfunc, x_types, x_values)
303
+
304
+ def test_asin(self):
305
+ pyfunc = asin
306
+ x_types = [types.int16, types.int32, types.int64,
307
+ types.uint16, types.uint32, types.uint64,
308
+ types.float32, types.float64]
309
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
310
+ self.run_unary(pyfunc, x_types, x_values)
311
+
312
+ def test_acos(self):
313
+ pyfunc = acos
314
+ x_types = [types.int16, types.int32, types.int64,
315
+ types.uint16, types.uint32, types.uint64,
316
+ types.float32, types.float64]
317
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
318
+ self.run_unary(pyfunc, x_types, x_values)
319
+
320
+ def test_atan(self):
321
+ pyfunc = atan
322
+ x_types = [types.int16, types.int32, types.int64,
323
+ types.uint16, types.uint32, types.uint64,
324
+ types.float32, types.float64]
325
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
326
+ self.run_unary(pyfunc, x_types, x_values)
327
+
328
+ def test_atan2(self):
329
+ pyfunc = atan2
330
+ x_types = [types.int16, types.int32, types.int64,
331
+ types.uint16, types.uint32, types.uint64,
332
+ types.float32, types.float64]
333
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
334
+ y_values = [x * 2 for x in x_values]
335
+ self.run_binary(pyfunc, x_types, x_values, y_values)
336
+
337
+ def test_asinh(self):
338
+ pyfunc = asinh
339
+ x_types = [types.int16, types.int32, types.int64,
340
+ types.uint16, types.uint32, types.uint64,
341
+ types.float32, types.float64]
342
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
343
+ self.run_unary(pyfunc, x_types, x_values, prec='double')
344
+
345
+ def test_acosh(self):
346
+ pyfunc = acosh
347
+ x_types = [types.int16, types.int32, types.int64,
348
+ types.uint16, types.uint32, types.uint64,
349
+ types.float32, types.float64]
350
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
351
+ self.run_unary(pyfunc, x_types, x_values)
352
+
353
+ def test_atanh(self):
354
+ pyfunc = atanh
355
+ x_types = [types.int16, types.int32, types.int64,
356
+ types.uint16, types.uint32, types.uint64,
357
+ types.float32, types.float64]
358
+ x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1]
359
+ self.run_unary(pyfunc, x_types, x_values, prec='double')
360
+
361
+ def test_sinh(self):
362
+ pyfunc = sinh
363
+ x_types = [types.int16, types.int32, types.int64,
364
+ types.uint16, types.uint32, types.uint64,
365
+ types.float32, types.float64]
366
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
367
+ self.run_unary(pyfunc, x_types, x_values)
368
+
369
+ def test_cosh(self):
370
+ pyfunc = cosh
371
+ x_types = [types.int16, types.int32, types.int64,
372
+ types.uint16, types.uint32, types.uint64,
373
+ types.float32, types.float64]
374
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
375
+ self.run_unary(pyfunc, x_types, x_values)
376
+
377
+ def test_tanh(self):
378
+ pyfunc = tanh
379
+ x_types = [types.int16, types.int32, types.int64,
380
+ types.uint16, types.uint32, types.uint64,
381
+ types.float32, types.float64]
382
+ x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1]
383
+ self.run_unary(pyfunc, x_types, x_values)
384
+
385
+ def test_floor(self):
386
+ pyfunc = floor
387
+ x_types = [types.int16, types.int32, types.int64,
388
+ types.uint16, types.uint32, types.uint64,
389
+ types.float32, types.float64]
390
+ x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9]
391
+ self.run_unary(pyfunc, x_types, x_values)
392
+
393
+ def test_ceil(self):
394
+ pyfunc = ceil
395
+ x_types = [types.int16, types.int32, types.int64,
396
+ types.uint16, types.uint32, types.uint64,
397
+ types.float32, types.float64]
398
+ x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9]
399
+ self.run_unary(pyfunc, x_types, x_values)
400
+
401
+ def test_trunc(self):
402
+ pyfunc = trunc
403
+ x_types = [types.int16, types.int32, types.int64,
404
+ types.uint16, types.uint32, types.uint64,
405
+ types.float32, types.float64]
406
+ x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9]
407
+ self.run_unary(pyfunc, x_types, x_values)
408
+
409
+ def test_isnan(self):
410
+ self.check_predicate_func(isnan)
411
+
412
+ def test_isinf(self):
413
+ self.check_predicate_func(isinf)
414
+
415
+ def test_isfinite(self):
416
+ self.check_predicate_func(isfinite)
417
+
418
+ def test_hypot(self):
419
+ pyfunc = hypot
420
+ x_types = [types.int64, types.uint64,
421
+ types.float32, types.float64]
422
+ x_values = [1, 2, 3, 4, 5, 6, .21, .34]
423
+ y_values = [x + 2 for x in x_values]
424
+ # Issue #563: precision issues with math.hypot() under Windows.
425
+ prec = 'single'
426
+ self.run_binary(pyfunc, x_types, x_values, y_values, prec)
427
+ # Check that values that overflow in naive implementations do not
428
+ # in the numba impl
429
+
430
+ def naive_hypot(x, y):
431
+ return math.sqrt(x * x + y * y)
432
+
433
+ cfunc = njit(pyfunc)
434
+ for fltty in (types.float32, types.float64):
435
+ dt = numpy_support.as_dtype(fltty).type
436
+ val = dt(np.finfo(dt).max / 30.)
437
+ nb_ans = cfunc(val, val)
438
+ self.assertPreciseEqual(nb_ans, pyfunc(val, val), prec='single')
439
+ self.assertTrue(np.isfinite(nb_ans))
440
+
441
+ with warnings.catch_warnings():
442
+ warnings.simplefilter("error", RuntimeWarning)
443
+ self.assertRaisesRegex(RuntimeWarning,
444
+ 'overflow encountered in .*scalar',
445
+ naive_hypot, val, val)
446
+
447
+ def test_nextafter(self):
448
+ pyfunc = nextafter
449
+ x_types = [types.float32, types.float64,
450
+ types.int32, types.int64,
451
+ types.uint32, types.uint64]
452
+ x_values = [0.0, .21, .34, 1005382.042, -25.328]
453
+ y1_values = [x + 2 for x in x_values]
454
+ y2_values = [x - 2 for x in x_values]
455
+
456
+ self.run_binary(pyfunc, x_types, x_values, y1_values)
457
+ self.run_binary(pyfunc, x_types, x_values, y2_values)
458
+
459
+ # Test using pos/neg inf
460
+ self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [math.inf]*3)
461
+ self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [-math.inf]*3)
462
+
463
+ # if both args to nextafter are equal, then it is returned unchanged.
464
+ self.run_binary(pyfunc, x_types, x_values, x_values)
465
+
466
+ def test_degrees(self):
467
+ pyfunc = degrees
468
+ x_types = [types.int16, types.int32, types.int64,
469
+ types.uint16, types.uint32, types.uint64,
470
+ types.float32, types.float64]
471
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
472
+ self.run_unary(pyfunc, x_types, x_values)
473
+
474
+ def test_radians(self):
475
+ pyfunc = radians
476
+ x_types = [types.int16, types.int32, types.int64,
477
+ types.uint16, types.uint32, types.uint64,
478
+ types.float32, types.float64]
479
+ x_values = [1, 1, 1, 1, 1, 1, 1., 1.]
480
+ self.run_unary(pyfunc, x_types, x_values)
481
+
482
+ def test_erf(self):
483
+ pyfunc = erf
484
+ x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')]
485
+ x_types = [types.float32, types.float64] * (len(x_values) // 2)
486
+ self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=2)
487
+
488
+ def test_erfc(self):
489
+ pyfunc = erfc
490
+ x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')]
491
+ x_types = [types.float32, types.float64] * (len(x_values) // 2)
492
+ self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=4)
493
+
494
+ def test_gamma(self):
495
+ pyfunc = gamma
496
+ x_values = [1., -0.9, -0.5, 0.5]
497
+ x_types = [types.float32, types.float64] * (len(x_values) // 2)
498
+ self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=3)
499
+ x_values = [-0.1, 0.1, 2.5, 10.1, 50., float('inf')]
500
+ x_types = [types.float64] * len(x_values)
501
+ self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=8)
502
+
503
+ def test_lgamma(self):
504
+ pyfunc = lgamma
505
+ x_values = [1., -0.9, -0.1, 0.1, 200., 1e10, 1e30, float('inf')]
506
+ x_types = [types.float32, types.float64] * (len(x_values) // 2)
507
+ self.run_unary(pyfunc, x_types, x_values, prec='double')
508
+
509
+ def test_pow(self):
510
+ pyfunc = pow
511
+ x_types = [types.int16, types.int32, types.int64,
512
+ types.uint16, types.uint32, types.uint64,
513
+ types.float32, types.float64]
514
+ x_values = [-2, -1, -2, 2, 1, 2, .1, .2]
515
+ y_values = [x * 2 for x in x_values]
516
+ self.run_binary(pyfunc, x_types, x_values, y_values)
517
+
518
+ def test_gcd(self):
519
+ from itertools import product, repeat, chain
520
+ pyfunc = gcd
521
+ signed_args = product(
522
+ sorted(types.signed_domain), *repeat((-2, -1, 0, 1, 2, 7, 10), 2)
523
+ )
524
+ unsigned_args = product(
525
+ sorted(types.unsigned_domain), *repeat((0, 1, 2, 7, 9, 16), 2)
526
+ )
527
+ x_types, x_values, y_values = zip(*chain(signed_args, unsigned_args))
528
+ self.run_binary(pyfunc, x_types, x_values, y_values)
529
+
530
+ def test_copysign(self):
531
+ pyfunc = copysign
532
+ value_types = [types.float32, types.float64]
533
+ values = [-2, -1, -0.0, 0.0, 1, 2, float('-inf'), float('inf'),
534
+ float('nan')]
535
+ x_types, x_values, y_values = list(zip(
536
+ *itertools.product(value_types, values, values)))
537
+ self.run_binary(pyfunc, x_types, x_values, y_values)
538
+
539
+ def test_frexp(self):
540
+ pyfunc = frexp
541
+ x_types = [types.float32, types.float64]
542
+ x_values = [-2.5, -0.0, 0.0, 3.5,
543
+ float('-inf'), float('inf'), float('nan')]
544
+ self.run_unary(pyfunc, x_types, x_values, prec='exact')
545
+
546
+ def test_ldexp(self):
547
+ pyfunc = ldexp
548
+ cfunc = njit(pyfunc)
549
+ for fltty in (types.float32, types.float64):
550
+ for args in [(2.5, -2), (2.5, 1), (0.0, 0), (0.0, 1),
551
+ (-0.0, 0), (-0.0, 1),
552
+ (float('inf'), 0), (float('-inf'), 0),
553
+ (float('nan'), 0)]:
554
+ msg = 'for input %r' % (args,)
555
+ self.assertPreciseEqual(cfunc(*args), pyfunc(*args))
556
+
557
+
558
+ if __name__ == '__main__':
559
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_misc_coverage_support.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import patch
3
+
4
+ from numba.tests.support import TestCase
5
+
6
+ from numba import njit
7
+ from numba.core import ir
8
+ from numba.misc.coverage_support import NotifyLocBase, _the_registry
9
+
10
+
11
+ class TestMiscCoverageSupport(TestCase):
12
+ @TestCase.run_test_in_subprocess(envvars={"NUMBA_JIT_COVERAGE": "1"})
13
+ def test_custom_loc_notifier(self):
14
+ class MyNotify(NotifyLocBase):
15
+ records = []
16
+
17
+ def notify(self, loc):
18
+ self.records.append(("NOTIFY", loc))
19
+
20
+ def close(self):
21
+ self.records.append(("CLOSE", None))
22
+
23
+ # Patch to install registry for testing
24
+ new_the_registry = _the_registry + [MyNotify]
25
+ gv = "numba.misc.coverage_support._the_registry"
26
+ with patch(gv, new_the_registry):
27
+
28
+ @njit
29
+ def foo():
30
+ return 123
31
+
32
+ res = foo()
33
+
34
+ self.assertEqual(res, 123)
35
+
36
+ # offset by +2 because:
37
+ # +1 for the decorator
38
+ # +1 for the `def` line
39
+ first_offset = 2
40
+ offset = foo.__code__.co_firstlineno + first_offset
41
+ loc = ir.Loc(__file__, 1)
42
+ self.assertIn(("NOTIFY", loc.with_lineno(offset)), MyNotify.records)
43
+ self.assertIn(("CLOSE", None), MyNotify.records)
44
+
45
+ # Test dead branch pruned
46
+ with patch(gv, new_the_registry):
47
+ cond = False
48
+
49
+ @njit
50
+ def foo():
51
+ if cond:
52
+ return 321
53
+ return 123
54
+
55
+ res = foo()
56
+
57
+ self.assertEqual(res, 123)
58
+
59
+ # `if cond` line is compiled
60
+ offset = foo.__code__.co_firstlineno + first_offset
61
+ self.assertIn(("NOTIFY", loc.with_lineno(offset)), MyNotify.records)
62
+
63
+ # ` return 321` line is not compiled
64
+ self.assertNotIn(
65
+ ("NOTIFY", loc.with_lineno(offset + 1)), MyNotify.records
66
+ )
67
+
68
+ # ` return 123` line is compiled
69
+ self.assertIn(("NOTIFY", loc.with_lineno(offset + 2)), MyNotify.records)
70
+
71
+ self.assertIn(("CLOSE", None), MyNotify.records)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_nested_calls.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test problems in nested calls.
3
+ Usually due to invalid type conversion between function boundaries.
4
+ """
5
+
6
+
7
+ from numba import int32, int64
8
+ from numba import jit
9
+ from numba.core import types
10
+ from numba.extending import overload
11
+ from numba.tests.support import TestCase, tag
12
+ import unittest
13
+
14
+
15
+ @jit(nopython=True)
16
+ def f_inner(a, b, c):
17
+ return a, b, c
18
+
19
+ def f(x, y, z):
20
+ return f_inner(x, c=y, b=z)
21
+
22
+ @jit(nopython=True)
23
+ def g_inner(a, b=2, c=3):
24
+ return a, b, c
25
+
26
+ def g(x, y, z):
27
+ return g_inner(x, b=y), g_inner(a=z, c=x)
28
+
29
+ @jit(nopython=True)
30
+ def star_inner(a=5, *b):
31
+ return a, b
32
+
33
+ def star(x, y, z):
34
+ return star_inner(a=x), star_inner(x, y, z)
35
+
36
+ def star_call(x, y, z):
37
+ return star_inner(x, *y), star_inner(*z)
38
+
39
+ @jit(nopython=True)
40
+ def argcast_inner(a, b):
41
+ if b:
42
+ # Here `a` is unified to int64 (from int32 originally)
43
+ a = int64(0)
44
+ return a
45
+
46
+ def argcast(a, b):
47
+ return argcast_inner(int32(a), b)
48
+
49
+
50
+ def generated_inner(x, y=5, z=6):
51
+ assert 0, "unreachable"
52
+
53
+
54
+ @overload(generated_inner)
55
+ def ol_generated_inner(x, y=5, z=6):
56
+ if isinstance(x, types.Complex):
57
+ def impl(x, y=5, z=6):
58
+ return x + y, z
59
+ else:
60
+ def impl(x, y=5, z=6):
61
+ return x - y, z
62
+ return impl
63
+
64
+
65
+ def call_generated(a, b):
66
+ return generated_inner(a, z=b)
67
+
68
+
69
+ class TestNestedCall(TestCase):
70
+
71
+ def compile_func(self, pyfunc, objmode=False):
72
+ def check(*args, **kwargs):
73
+ expected = pyfunc(*args, **kwargs)
74
+ result = f(*args, **kwargs)
75
+ self.assertPreciseEqual(result, expected)
76
+ flags = dict(forceobj=True) if objmode else dict(nopython=True)
77
+ f = jit(**flags)(pyfunc)
78
+ return f, check
79
+
80
+ def test_boolean_return(self):
81
+ @jit(nopython=True)
82
+ def inner(x):
83
+ return not x
84
+
85
+ @jit(nopython=True)
86
+ def outer(x):
87
+ if inner(x):
88
+ return True
89
+ else:
90
+ return False
91
+
92
+ self.assertFalse(outer(True))
93
+ self.assertTrue(outer(False))
94
+
95
+ def test_named_args(self, objmode=False):
96
+ """
97
+ Test a nested function call with named (keyword) arguments.
98
+ """
99
+ cfunc, check = self.compile_func(f, objmode)
100
+ check(1, 2, 3)
101
+ check(1, y=2, z=3)
102
+
103
+ def test_named_args_objmode(self):
104
+ self.test_named_args(objmode=True)
105
+
106
+ def test_default_args(self, objmode=False):
107
+ """
108
+ Test a nested function call using default argument values.
109
+ """
110
+ cfunc, check = self.compile_func(g, objmode)
111
+ check(1, 2, 3)
112
+ check(1, y=2, z=3)
113
+
114
+ def test_default_args_objmode(self):
115
+ self.test_default_args(objmode=True)
116
+
117
+ def test_star_args(self):
118
+ """
119
+ Test a nested function call to a function with *args in its signature.
120
+ """
121
+ cfunc, check = self.compile_func(star)
122
+ check(1, 2, 3)
123
+
124
+ def test_star_call(self, objmode=False):
125
+ """
126
+ Test a function call with a *args.
127
+ """
128
+ cfunc, check = self.compile_func(star_call, objmode)
129
+ check(1, (2,), (3,))
130
+
131
+ def test_star_call_objmode(self):
132
+ self.test_star_call(objmode=True)
133
+
134
+ def test_argcast(self):
135
+ """
136
+ Issue #1488: implicitly casting an argument variable should not
137
+ break nested calls.
138
+ """
139
+ cfunc, check = self.compile_func(argcast)
140
+ check(1, 0)
141
+ check(1, 1)
142
+
143
+ def test_call_generated(self):
144
+ """
145
+ Test a nested function call to a generated jit function.
146
+ """
147
+ cfunc = jit(nopython=True)(call_generated)
148
+ self.assertPreciseEqual(cfunc(1, 2), (-4, 2))
149
+ self.assertPreciseEqual(cfunc(1j, 2), (1j + 5, 2))
150
+
151
+
152
+ if __name__ == '__main__':
153
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_new_type_system.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from numba import njit, config
4
+ from numba.tests.support import TestCase
5
+
6
+
7
+ class TestTypes(TestCase):
8
+
9
+ def setUp(self) -> None:
10
+ if config.USE_LEGACY_TYPE_SYSTEM:
11
+ self.skipTest("This test is only for the new type system")
12
+ return super().setUp()
13
+
14
+ def test_return_types(self):
15
+ @njit
16
+ def foo(x):
17
+ return x
18
+
19
+ cases = [
20
+ # Python types
21
+ 1,
22
+ 1.2,
23
+ (1 + 2j),
24
+ True,
25
+ # NumPy types
26
+ np.int32(1),
27
+ np.float64(1.2),
28
+ np.complex64(1 + 2j),
29
+ np.complex128(1 + 2j),
30
+ np.bool_(True),
31
+ np.datetime64('2020-01-01'),
32
+ np.timedelta64(1, 'D'),
33
+ ]
34
+
35
+ for case in cases:
36
+ self.assertEqual(foo(case), case)
37
+ self.assertEqual(type(foo(case)), type(case))
lib/python3.10/site-packages/numba/tests/test_npdatetime.py ADDED
@@ -0,0 +1,1180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test np.datetime64 and np.timedelta64 support.
3
+ """
4
+
5
+ # NOTE: datetime64 and timedelta64 ufuncs are tested in test_ufuncs.
6
+
7
+
8
+ import contextlib
9
+ import itertools
10
+ import re
11
+ import unittest
12
+ import warnings
13
+
14
+ import numpy as np
15
+
16
+ from numba import jit, vectorize, njit
17
+ from numba.np.numpy_support import numpy_version
18
+ from numba.core import types, config
19
+ from numba.core.errors import TypingError
20
+ from numba.tests.support import TestCase, tag, skip_parfors_unsupported
21
+ from numba.np import npdatetime_helpers, numpy_support
22
+
23
+ TIMEDELTA_M = np.dtype('timedelta64[M]')
24
+ TIMEDELTA_Y = np.dtype('timedelta64[Y]')
25
+
26
+ def value_unit(val):
27
+ ty = numpy_support.from_dtype(val.dtype)
28
+ return ty.unit
29
+
30
+
31
+ date_units = ('Y', 'M')
32
+ time_units = ('W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as')
33
+ # All except generic ("")
34
+ all_units = date_units + time_units
35
+
36
+
37
+ def add_usecase(x, y):
38
+ return x + y
39
+
40
+ def sub_usecase(x, y):
41
+ return x - y
42
+
43
+ def mul_usecase(x, y):
44
+ return x * y
45
+
46
+ def div_usecase(x, y):
47
+ return x / y
48
+
49
+ def floordiv_usecase(x, y):
50
+ return x // y
51
+
52
+ def eq_usecase(x, y):
53
+ return x == y
54
+
55
+ def ne_usecase(x, y):
56
+ return x != y
57
+
58
+ def lt_usecase(x, y):
59
+ return x < y
60
+
61
+ def le_usecase(x, y):
62
+ return x <= y
63
+
64
+ def gt_usecase(x, y):
65
+ return x > y
66
+
67
+ def ge_usecase(x, y):
68
+ return x >= y
69
+
70
+ def pos_usecase(x):
71
+ return +x
72
+
73
+ def neg_usecase(x):
74
+ return -x
75
+
76
+ def abs_usecase(x):
77
+ return abs(x)
78
+
79
+ def hash_usecase(x):
80
+ return hash(x)
81
+
82
+ def min_usecase(x, y):
83
+ return min(x, y)
84
+
85
+ def max_usecase(x, y):
86
+ return max(x, y)
87
+
88
+ def int_cast_usecase(x):
89
+ return int(x)
90
+
91
+ def make_add_constant(const):
92
+ def add_constant(x):
93
+ return x + const
94
+ return add_constant
95
+
96
+
97
+ class TestModuleHelpers(TestCase):
98
+ """
99
+ Test the various helpers in numba.npdatetime_helpers.
100
+ """
101
+
102
+ def test_can_cast_timedelta(self):
103
+ f = npdatetime_helpers.can_cast_timedelta_units
104
+ for a, b in itertools.product(date_units, time_units):
105
+ self.assertFalse(f(a, b), (a, b))
106
+ self.assertFalse(f(b, a), (a, b))
107
+ for unit in all_units:
108
+ self.assertFalse(f(unit, ''))
109
+ self.assertTrue(f('', unit))
110
+ for unit in all_units + ('',):
111
+ self.assertTrue(f(unit, unit))
112
+
113
+ def check_units_group(group):
114
+ for i, a in enumerate(group):
115
+ for b in group[:i]:
116
+ # large into smaller is ok
117
+ self.assertTrue(f(b, a))
118
+ # small into larger is not
119
+ self.assertFalse(f(a, b))
120
+
121
+ check_units_group(date_units)
122
+ check_units_group(time_units)
123
+
124
+ def test_timedelta_conversion(self):
125
+ f = npdatetime_helpers.get_timedelta_conversion_factor
126
+ for unit in all_units + ('',):
127
+ self.assertEqual(f(unit, unit), 1)
128
+ for unit in all_units:
129
+ self.assertEqual(f('', unit), 1)
130
+ for a, b in itertools.product(time_units, date_units):
131
+ self.assertIs(f(a, b), None)
132
+ self.assertIs(f(b, a), None)
133
+
134
+ def check_units_group(group):
135
+ for i, a in enumerate(group):
136
+ for b in group[:i]:
137
+ self.assertGreater(f(b, a), 1, (b, a))
138
+ self.assertIs(f(a, b), None)
139
+
140
+ check_units_group(date_units)
141
+ check_units_group(time_units)
142
+
143
+ # Check some hand-picked values
144
+ self.assertEqual(f('Y', 'M'), 12)
145
+ self.assertEqual(f('W', 'h'), 24 * 7)
146
+ self.assertEqual(f('W', 'm'), 24 * 7 * 60)
147
+ self.assertEqual(f('W', 'us'), 24 * 7 * 3600 * 1000 * 1000)
148
+
149
+ def test_datetime_timedelta_scaling(self):
150
+ f = npdatetime_helpers.get_datetime_timedelta_conversion
151
+ def check_error(dt_unit, td_unit):
152
+ with self.assertRaises(RuntimeError):
153
+ f(dt_unit, td_unit)
154
+ # Cannot combine a Y or M timedelta64 with a finer-grained datetime64
155
+ for dt_unit, td_unit in itertools.product(time_units, date_units):
156
+ check_error(dt_unit, td_unit)
157
+ # Sanity check that all other unit pairs can be converted, we'll
158
+ # check individual results below
159
+ for dt_unit, td_unit in itertools.product(time_units, time_units):
160
+ f(dt_unit, td_unit)
161
+ for dt_unit, td_unit in itertools.product(date_units, time_units):
162
+ f(dt_unit, td_unit)
163
+ for dt_unit, td_unit in itertools.product(date_units, date_units):
164
+ f(dt_unit, td_unit)
165
+ # No-op conversions
166
+ for unit in all_units:
167
+ self.assertEqual(f(unit, unit), (unit, 1, 1))
168
+ self.assertEqual(f(unit, ''), (unit, 1, 1))
169
+ self.assertEqual(f('', unit), ('', 1, 1))
170
+ self.assertEqual(f('', ''), ('', 1, 1))
171
+ # "Regular" values
172
+ self.assertEqual(f('Y', 'M'), ('M', 12, 1))
173
+ self.assertEqual(f('M', 'Y'), ('M', 1, 12))
174
+ self.assertEqual(f('W', 'D'), ('D', 7, 1))
175
+ self.assertEqual(f('D', 'W'), ('D', 1, 7))
176
+ self.assertEqual(f('W', 's'), ('s', 7 * 24 * 3600, 1))
177
+ self.assertEqual(f('s', 'W'), ('s', 1, 7 * 24 * 3600))
178
+ self.assertEqual(f('s', 'as'), ('as', 1000 ** 6, 1))
179
+ self.assertEqual(f('as', 's'), ('as', 1, 1000 ** 6))
180
+ # "Interesting" values
181
+ self.assertEqual(f('Y', 'D'), ('D', 97 + 400 * 365, 400))
182
+ self.assertEqual(f('Y', 'W'), ('W', 97 + 400 * 365, 400 * 7))
183
+ self.assertEqual(f('M', 'D'), ('D', 97 + 400 * 365, 400 * 12))
184
+ self.assertEqual(f('M', 'W'), ('W', 97 + 400 * 365, 400 * 12 * 7))
185
+ self.assertEqual(f('Y', 's'), ('s', (97 + 400 * 365) * 24 * 3600, 400))
186
+ self.assertEqual(f('M', 's'), ('s', (97 + 400 * 365) * 24 * 3600, 400 * 12))
187
+
188
+ def test_combine_datetime_timedelta_units(self):
189
+ f = npdatetime_helpers.combine_datetime_timedelta_units
190
+ for unit in all_units:
191
+ self.assertEqual(f(unit, unit), unit)
192
+ self.assertEqual(f('', unit), unit)
193
+ self.assertEqual(f(unit, ''), unit)
194
+ self.assertEqual(f('', ''), '')
195
+ for dt_unit, td_unit in itertools.product(time_units, date_units):
196
+ self.assertIs(f(dt_unit, td_unit), None)
197
+ for dt_unit, td_unit in itertools.product(date_units, time_units):
198
+ self.assertEqual(f(dt_unit, td_unit), td_unit)
199
+
200
+ def test_same_kind(self):
201
+ f = npdatetime_helpers.same_kind
202
+ for u in all_units:
203
+ self.assertTrue(f(u, u))
204
+ A = ('Y', 'M', 'W', 'D')
205
+ B = ('h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as')
206
+ for a, b in itertools.product(A, A):
207
+ self.assertTrue(f(a, b))
208
+ for a, b in itertools.product(B, B):
209
+ self.assertTrue(f(a, b))
210
+ for a, b in itertools.product(A, B):
211
+ self.assertFalse(f(a, b))
212
+ self.assertFalse(f(b, a))
213
+
214
+
215
+ TD = np.timedelta64
216
+ DT = np.datetime64
217
+
218
+
219
+ class TestMiscCompiling(TestCase):
220
+
221
+ def test_jit_explicit_signature(self):
222
+ def _check_explicit_signature(sig):
223
+ f = jit(sig, nopython=True)(add_usecase)
224
+ # Just a sanity check
225
+ args = DT(1, 'ms'), TD(2, 'us')
226
+ expected = add_usecase(*args)
227
+ self.assertPreciseEqual(f(*args), expected)
228
+
229
+ # Test passing the signature in object form
230
+ sig = types.NPDatetime('us')(types.NPDatetime('ms'), types.NPTimedelta('us'))
231
+ _check_explicit_signature(sig)
232
+ # Same with the signature in string form
233
+ sig = "NPDatetime('us')(NPDatetime('ms'), NPTimedelta('us'))"
234
+ _check_explicit_signature(sig)
235
+
236
+ def test_vectorize_explicit_signature(self):
237
+ def _check_explicit_signature(sig):
238
+ f = vectorize([sig], nopython=True)(mul_usecase)
239
+ # This isn't really right but we can't do better than this,
240
+ # since Numpy's ufuncs don't store the metadata of return types.
241
+ # Related to https://github.com/numpy/numpy/issues/5429
242
+ self.assertPreciseEqual(f(TD(2), 3), TD(6))
243
+
244
+ # Test passing the signature in object form (issue #917)
245
+ sig = types.NPTimedelta('s')(types.NPTimedelta('s'), types.int64)
246
+ _check_explicit_signature(sig)
247
+ # Same with the signature in string form
248
+ sig = "NPTimedelta('s')(NPTimedelta('s'), int64)"
249
+ _check_explicit_signature(sig)
250
+
251
+ def test_constant_datetime(self):
252
+ def check(const):
253
+ pyfunc = make_add_constant(const)
254
+ f = jit(nopython=True)(pyfunc)
255
+ x = TD(4, 'D')
256
+ expected = pyfunc(x)
257
+ self.assertPreciseEqual(f(x), expected)
258
+ check(DT('2001-01-01'))
259
+ check(DT('NaT', 'D'))
260
+
261
+ def test_constant_timedelta(self):
262
+ def check(const):
263
+ pyfunc = make_add_constant(const)
264
+ f = jit(nopython=True)(pyfunc)
265
+ x = TD(4, 'D')
266
+ expected = pyfunc(x)
267
+ self.assertPreciseEqual(f(x), expected)
268
+ check(TD(4, 'D'))
269
+ check(TD(-4, 'D'))
270
+ check(TD('NaT', 'D'))
271
+
272
+
273
+ class TestTimedeltaArithmetic(TestCase):
274
+
275
+ jitargs = dict(forceobj=True)
276
+
277
+ def jit(self, pyfunc):
278
+ return jit(**self.jitargs)(pyfunc)
279
+
280
+ def test_add(self):
281
+ f = self.jit(add_usecase)
282
+ def check(a, b, expected):
283
+ self.assertPreciseEqual(f(a, b), expected)
284
+ self.assertPreciseEqual(f(b, a), expected)
285
+
286
+ check(TD(1), TD(2), TD(3))
287
+ check(TD(1, 's'), TD(2, 's'), TD(3, 's'))
288
+ # Implicit unit promotion
289
+ check(TD(1, 's'), TD(2, 'us'), TD(1000002, 'us'))
290
+ check(TD(1, 'W'), TD(2, 'D'), TD(9, 'D'))
291
+ # NaTs
292
+ check(TD('NaT'), TD(1), TD('NaT'))
293
+ check(TD('NaT', 's'), TD(1, 'D'), TD('NaT', 's'))
294
+ check(TD('NaT', 's'), TD(1, 'ms'), TD('NaT', 'ms'))
295
+ # Cannot add days and months
296
+ with self.assertRaises((TypeError, TypingError)):
297
+ f(TD(1, 'M'), TD(1, 'D'))
298
+
299
+ def test_sub(self):
300
+ f = self.jit(sub_usecase)
301
+ def check(a, b, expected):
302
+ self.assertPreciseEqual(f(a, b), expected)
303
+ self.assertPreciseEqual(f(b, a), -expected)
304
+
305
+ check(TD(3), TD(2), TD(1))
306
+ check(TD(3, 's'), TD(2, 's'), TD(1, 's'))
307
+ # Implicit unit promotion
308
+ check(TD(3, 's'), TD(2, 'us'), TD(2999998, 'us'))
309
+ check(TD(1, 'W'), TD(2, 'D'), TD(5, 'D'))
310
+ # NaTs
311
+ check(TD('NaT'), TD(1), TD('NaT'))
312
+ check(TD('NaT', 's'), TD(1, 'D'), TD('NaT', 's'))
313
+ check(TD('NaT', 's'), TD(1, 'ms'), TD('NaT', 'ms'))
314
+ # Cannot sub days to months
315
+ with self.assertRaises((TypeError, TypingError)):
316
+ f(TD(1, 'M'), TD(1, 'D'))
317
+
318
+ def test_mul(self):
319
+ f = self.jit(mul_usecase)
320
+ def check(a, b, expected):
321
+ self.assertPreciseEqual(f(a, b), expected)
322
+ self.assertPreciseEqual(f(b, a), expected)
323
+
324
+ # non-int64 int * timedelta64
325
+ check(TD(3), np.uint32(2), TD(6))
326
+ # int * timedelta64
327
+ check(TD(3), 2, TD(6))
328
+ check(TD(3, 'ps'), 2, TD(6, 'ps'))
329
+ check(TD('NaT', 'ps'), 2, TD('NaT', 'ps'))
330
+ # float * timedelta64
331
+ check(TD(7), 1.5, TD(10))
332
+ check(TD(-7), 1.5, TD(-10))
333
+ check(TD(7, 'ps'), -1.5, TD(-10, 'ps'))
334
+ check(TD(-7), -1.5, TD(10))
335
+ check(TD('NaT', 'ps'), -1.5, TD('NaT', 'ps'))
336
+ check(TD(7, 'ps'), float('nan'), TD('NaT', 'ps'))
337
+ # wraparound on overflow
338
+ check(TD(2**62, 'ps'), 16, TD(0, 'ps'))
339
+
340
+ def test_div(self):
341
+ div = self.jit(div_usecase)
342
+ floordiv = self.jit(floordiv_usecase)
343
+ def check(a, b, expected):
344
+ self.assertPreciseEqual(div(a, b), expected)
345
+ self.assertPreciseEqual(floordiv(a, b), expected)
346
+
347
+ # timedelta64 / non-int64 int
348
+ check(TD(-3, 'ps'), np.uint32(2), TD(-1, 'ps'))
349
+ # timedelta64 / int
350
+ check(TD(3), 2, TD(1))
351
+ check(TD(-3, 'ps'), 2, TD(-1, 'ps'))
352
+ check(TD('NaT', 'ps'), 2, TD('NaT', 'ps'))
353
+ check(TD(3, 'ps'), 0, TD('NaT', 'ps'))
354
+ check(TD('NaT', 'ps'), 0, TD('NaT', 'ps'))
355
+ # timedelta64 / float
356
+ check(TD(7), 0.5, TD(14))
357
+ check(TD(-7, 'ps'), 1.5, TD(-4, 'ps'))
358
+ check(TD('NaT', 'ps'), 2.5, TD('NaT', 'ps'))
359
+ check(TD(3, 'ps'), 0.0, TD('NaT', 'ps'))
360
+ check(TD('NaT', 'ps'), 0.0, TD('NaT', 'ps'))
361
+ check(TD(3, 'ps'), float('nan'), TD('NaT', 'ps'))
362
+ check(TD('NaT', 'ps'), float('nan'), TD('NaT', 'ps'))
363
+
364
+ def test_homogeneous_div(self):
365
+ div = self.jit(div_usecase)
366
+ def check(a, b, expected):
367
+ self.assertPreciseEqual(div(a, b), expected)
368
+
369
+ # timedelta64 / timedelta64
370
+ check(TD(7), TD(3), 7. / 3.)
371
+ check(TD(7, 'us'), TD(3, 'ms'), 7. / 3000.)
372
+ check(TD(7, 'ms'), TD(3, 'us'), 7000. / 3.)
373
+ check(TD(7), TD(0), float('+inf'))
374
+ check(TD(-7), TD(0), float('-inf'))
375
+ check(TD(0), TD(0), float('nan'))
376
+ # NaTs
377
+ check(TD('nat'), TD(3), float('nan'))
378
+ check(TD(3), TD('nat'), float('nan'))
379
+ check(TD('nat'), TD(0), float('nan'))
380
+ # Cannot div months with days
381
+ with self.assertRaises((TypeError, TypingError)):
382
+ div(TD(1, 'M'), TD(1, 'D'))
383
+
384
+ def test_eq_ne(self):
385
+ eq = self.jit(eq_usecase)
386
+ ne = self.jit(ne_usecase)
387
+ def check(a, b, expected):
388
+ expected_val = expected
389
+ not_expected_val = not expected
390
+
391
+ # all NaT comparisons are False, including NaT==NaT,
392
+ # conversely != is True
393
+ if np.isnat(a) or np.isnat(a):
394
+ expected_val = False
395
+ not_expected_val = True
396
+
397
+ self.assertPreciseEqual(eq(a, b), expected_val)
398
+ self.assertPreciseEqual(eq(b, a), expected_val)
399
+ self.assertPreciseEqual(ne(a, b), not_expected_val)
400
+ self.assertPreciseEqual(ne(b, a), not_expected_val)
401
+
402
+ check(TD(1), TD(2), False)
403
+ check(TD(1), TD(1), True)
404
+ check(TD(1, 's'), TD(2, 's'), False)
405
+ check(TD(1, 's'), TD(1, 's'), True)
406
+ check(TD(2000, 's'), TD(2, 's'), False)
407
+ check(TD(2000, 'ms'), TD(2, 's'), True)
408
+ check(TD(1, 'Y'), TD(12, 'M'), True)
409
+ # NaTs
410
+ check(TD('Nat'), TD('Nat'), True)
411
+ check(TD('Nat', 'ms'), TD('Nat', 's'), True)
412
+ check(TD('Nat'), TD(1), False)
413
+ # Incompatible units => timedeltas compare unequal
414
+ if numpy_version < (1, 25):
415
+ check(TD(1, 'Y'), TD(365, 'D'), False)
416
+ check(TD(1, 'Y'), TD(366, 'D'), False)
417
+ # ... except when both are NaT!
418
+ check(TD('NaT', 'W'), TD('NaT', 'D'), True)
419
+ else:
420
+ # incompatible units raise
421
+ # The exception is different depending on Python mode
422
+ with self.assertRaises((TypeError, TypingError)):
423
+ eq(TD(1, 'Y'), TD(365, 'D'))
424
+ with self.assertRaises((TypeError, TypingError)):
425
+ ne(TD(1, 'Y'), TD(365, 'D'))
426
+
427
+ def test_lt_ge(self):
428
+ lt = self.jit(lt_usecase)
429
+ ge = self.jit(ge_usecase)
430
+ def check(a, b, expected):
431
+ expected_val = expected
432
+ not_expected_val = not expected
433
+
434
+ # since np 1.16 all NaT magnitude comparisons including equality
435
+ # are False (as NaT == NaT is now False)
436
+ if np.isnat(a) or np.isnat(a):
437
+ expected_val = False
438
+ not_expected_val = False
439
+
440
+ self.assertPreciseEqual(lt(a, b), expected_val)
441
+ self.assertPreciseEqual(ge(a, b), not_expected_val)
442
+
443
+ check(TD(1), TD(2), True)
444
+ check(TD(1), TD(1), False)
445
+ check(TD(2), TD(1), False)
446
+ check(TD(1, 's'), TD(2, 's'), True)
447
+ check(TD(1, 's'), TD(1, 's'), False)
448
+ check(TD(2, 's'), TD(1, 's'), False)
449
+ check(TD(1, 'm'), TD(61, 's'), True)
450
+ check(TD(1, 'm'), TD(60, 's'), False)
451
+ # NaTs
452
+ check(TD('Nat'), TD('Nat'), False)
453
+ check(TD('Nat', 'ms'), TD('Nat', 's'), False)
454
+ check(TD('Nat'), TD(-(2**63)+1), True)
455
+ # Incompatible units => exception raised
456
+ with self.assertRaises((TypeError, TypingError)):
457
+ lt(TD(1, 'Y'), TD(365, 'D'))
458
+ with self.assertRaises((TypeError, TypingError)):
459
+ ge(TD(1, 'Y'), TD(365, 'D'))
460
+ # ... even when both are NaT
461
+ with self.assertRaises((TypeError, TypingError)):
462
+ lt(TD('NaT', 'Y'), TD('NaT', 'D'))
463
+ with self.assertRaises((TypeError, TypingError)):
464
+ ge(TD('NaT', 'Y'), TD('NaT', 'D'))
465
+
466
+ def test_le_gt(self):
467
+ le = self.jit(le_usecase)
468
+ gt = self.jit(gt_usecase)
469
+ def check(a, b, expected):
470
+ expected_val = expected
471
+ not_expected_val = not expected
472
+
473
+ # since np 1.16 all NaT magnitude comparisons including equality
474
+ # are False (as NaT == NaT is now False)
475
+ if np.isnat(a) or np.isnat(a):
476
+ expected_val = False
477
+ not_expected_val = False
478
+ self.assertPreciseEqual(le(a, b), expected_val)
479
+ self.assertPreciseEqual(gt(a, b), not_expected_val)
480
+
481
+ check(TD(1), TD(2), True)
482
+ check(TD(1), TD(1), True)
483
+ check(TD(2), TD(1), False)
484
+ check(TD(1, 's'), TD(2, 's'), True)
485
+ check(TD(1, 's'), TD(1, 's'), True)
486
+ check(TD(2, 's'), TD(1, 's'), False)
487
+ check(TD(1, 'm'), TD(61, 's'), True)
488
+ check(TD(1, 'm'), TD(60, 's'), True)
489
+ check(TD(1, 'm'), TD(59, 's'), False)
490
+ # NaTs
491
+ check(TD('Nat'), TD('Nat'), True)
492
+ check(TD('Nat', 'ms'), TD('Nat', 's'), True)
493
+ check(TD('Nat'), TD(-(2**63)+1), True)
494
+ # Incompatible units => exception raised
495
+ with self.assertRaises((TypeError, TypingError)):
496
+ le(TD(1, 'Y'), TD(365, 'D'))
497
+ with self.assertRaises((TypeError, TypingError)):
498
+ gt(TD(1, 'Y'), TD(365, 'D'))
499
+ # ... even when both are NaT
500
+ with self.assertRaises((TypeError, TypingError)):
501
+ le(TD('NaT', 'Y'), TD('NaT', 'D'))
502
+ with self.assertRaises((TypeError, TypingError)):
503
+ gt(TD('NaT', 'Y'), TD('NaT', 'D'))
504
+
505
+ def test_pos(self):
506
+ pos = self.jit(pos_usecase)
507
+ def check(a):
508
+ self.assertPreciseEqual(pos(a), +a)
509
+
510
+ check(TD(3))
511
+ check(TD(-4))
512
+ check(TD(3, 'ms'))
513
+ check(TD(-4, 'ms'))
514
+ check(TD('NaT'))
515
+ check(TD('NaT', 'ms'))
516
+
517
+ def test_neg(self):
518
+ neg = self.jit(neg_usecase)
519
+ def check(a):
520
+ self.assertPreciseEqual(neg(a), -a)
521
+
522
+ check(TD(3))
523
+ check(TD(-4))
524
+ check(TD(3, 'ms'))
525
+ check(TD(-4, 'ms'))
526
+ check(TD('NaT'))
527
+ check(TD('NaT', 'ms'))
528
+
529
+ def test_abs(self):
530
+ f = self.jit(abs_usecase)
531
+ def check(a):
532
+ self.assertPreciseEqual(f(a), abs(a))
533
+
534
+ check(TD(3))
535
+ check(TD(-4))
536
+ check(TD(3, 'ms'))
537
+ check(TD(-4, 'ms'))
538
+ check(TD('NaT'))
539
+ check(TD('NaT', 'ms'))
540
+
541
+ def test_hash(self):
542
+ f = self.jit(hash_usecase)
543
+ def check(a):
544
+ self.assertPreciseEqual(f(a), hash(a))
545
+
546
+ TD_CASES = ((3,), (-4,), (3, 'ms'), (-4, 'ms'), (27, 'D'),
547
+ (2, 'D'), (2, 'W'), (2, 'Y'), (3, 'W'),
548
+ (365, 'D'), (10000, 'D'), (-10000, 'D'),
549
+ ('NaT',), ('NaT', 'ms'), ('NaT', 'D'), (-1,))
550
+ DT_CASES = (('2014',), ('2016',), ('2000',), ('2014-02',),
551
+ ('2014-03',), ('2014-04',), ('2016-02',), ('2000-12-31',),
552
+ ('2014-01-16',), ('2014-01-05',), ('2014-01-07',),
553
+ ('2014-01-06',), ('2014-02-02',), ('2014-02-27',),
554
+ ('2014-02-16',), ('2014-03-01',), ('2000-01-01T01:02:03.002Z',),
555
+ ('2000-01-01T01:02:03Z',), ('NaT',))
556
+
557
+ for case, typ in zip(TD_CASES + DT_CASES,
558
+ (TD,) * len(TD_CASES) + (DT,) * len(TD_CASES)):
559
+ check(typ(*case))
560
+
561
+ def _test_min_max(self, usecase):
562
+ f = self.jit(usecase)
563
+ def check(a, b):
564
+ self.assertPreciseEqual(f(a, b), usecase(a, b))
565
+
566
+ for cases in (
567
+ (TD(0), TD(1), TD(2), TD('NaT')),
568
+ (TD(0, 's'), TD(1, 's'), TD(2, 's'), TD('NaT', 's')),
569
+ ):
570
+ for a, b in itertools.product(cases, cases):
571
+ check(a, b)
572
+
573
+ def test_min(self):
574
+ self._test_min_max(min_usecase)
575
+
576
+ def test_max(self):
577
+ self._test_min_max(max_usecase)
578
+
579
+
580
+ class TestTimedeltaArithmeticNoPython(TestTimedeltaArithmetic):
581
+
582
+ jitargs = dict(nopython=True)
583
+
584
+ def test_int_cast(self):
585
+ f = self.jit(int_cast_usecase)
586
+ def check(a):
587
+ self.assertPreciseEqual(f(a), int(a))
588
+
589
+ for (delta, unit) in ((3, 'ns'), (-4, 'ns'), (30000, 'ns'),
590
+ (-40000000, 'ns'), (1, 'Y')):
591
+ check(TD(delta, unit).astype('timedelta64[ns]'))
592
+
593
+ for time in ('2014', '2016', '2000', '2014-02', '2014-03', '2014-04',
594
+ '2016-02', '2000-12-31', '2014-01-16', '2014-01-05',
595
+ '2014-01-07', '2014-01-06', '2014-02-02', '2014-02-27',
596
+ '2014-02-16', '2014-03-01', '2000-01-01T01:02:03.002Z',
597
+ '2000-01-01T01:02:03Z'):
598
+ check(DT(time).astype('datetime64[ns]'))
599
+
600
+ with self.assertRaises(TypingError, msg=('Only datetime64[ns] can be ' +
601
+ 'converted, but got ' +
602
+ 'datetime64[y]')):
603
+ f(DT('2014'))
604
+
605
+
606
+ class TestDatetimeArithmetic(TestCase):
607
+
608
+ jitargs = dict(forceobj=True)
609
+
610
+ def jit(self, pyfunc):
611
+ return jit(**self.jitargs)(pyfunc)
612
+
613
+ @contextlib.contextmanager
614
+ def silence_numpy_warnings(self):
615
+ # Numpy can raise warnings when combining e.g. a generic timedelta64
616
+ # with a non-generic datetime64.
617
+ with warnings.catch_warnings():
618
+ warnings.filterwarnings('ignore',
619
+ message='Implicitly casting between incompatible kinds',
620
+ category=DeprecationWarning)
621
+ yield
622
+
623
+ def test_add_sub_timedelta(self):
624
+ """
625
+ Test `datetime64 + timedelta64` and `datetime64 - timedelta64`.
626
+ """
627
+ add = self.jit(add_usecase)
628
+ sub = self.jit(sub_usecase)
629
+ def check(a, b, expected):
630
+ with self.silence_numpy_warnings():
631
+ self.assertPreciseEqual(add(a, b), expected, (a, b))
632
+ self.assertPreciseEqual(add(b, a), expected, (a, b))
633
+ self.assertPreciseEqual(sub(a, -b), expected, (a, b))
634
+ # Did we get it right?
635
+ self.assertPreciseEqual(a + b, expected)
636
+
637
+ # Y + ...
638
+ check(DT('2014'), TD(2, 'Y'), DT('2016'))
639
+ check(DT('2014'), TD(2, 'M'), DT('2014-03'))
640
+ check(DT('2014'), TD(3, 'W'), DT('2014-01-16', 'W'))
641
+ check(DT('2014'), TD(4, 'D'), DT('2014-01-05'))
642
+ check(DT('2000'), TD(365, 'D'), DT('2000-12-31'))
643
+ # M + ...
644
+ check(DT('2014-02'), TD(2, 'Y'), DT('2016-02'))
645
+ check(DT('2014-02'), TD(2, 'M'), DT('2014-04'))
646
+ check(DT('2014-02'), TD(2, 'D'), DT('2014-02-03'))
647
+ # W + ...
648
+ check(DT('2014-01-07', 'W'), TD(2, 'W'), DT('2014-01-16', 'W'))
649
+ # D + ...
650
+ check(DT('2014-02-02'), TD(27, 'D'), DT('2014-03-01'))
651
+ check(DT('2012-02-02'), TD(27, 'D'), DT('2012-02-29'))
652
+ check(DT('2012-02-02'), TD(2, 'W'), DT('2012-02-16'))
653
+ # s + ...
654
+ check(DT('2000-01-01T01:02:03Z'), TD(2, 'h'), DT('2000-01-01T03:02:03Z'))
655
+ check(DT('2000-01-01T01:02:03Z'), TD(2, 'ms'), DT('2000-01-01T01:02:03.002Z'))
656
+ # More thorough checking with leap years and faraway years
657
+ for dt_str in ('600', '601', '604', '801',
658
+ '1900', '1904', '2200', '2300', '2304',
659
+ '2400', '6001'):
660
+ for dt_suffix in ('', '-01', '-12'):
661
+ dt = DT(dt_str + dt_suffix)
662
+ for td in [TD(2, 'D'), TD(2, 'W'),
663
+ TD(100, 'D'), TD(10000, 'D'),
664
+ TD(-100, 'D'), TD(-10000, 'D'),
665
+ TD(100, 'W'), TD(10000, 'W'),
666
+ TD(-100, 'W'), TD(-10000, 'W'),
667
+ TD(100, 'M'), TD(10000, 'M'),
668
+ TD(-100, 'M'), TD(-10000, 'M')]:
669
+ self.assertEqual(add(dt, td), dt + td, (dt, td))
670
+ self.assertEqual(add(td, dt), dt + td, (dt, td))
671
+ self.assertEqual(sub(dt, -td), dt + td, (dt, td))
672
+
673
+ # NaTs
674
+ check(DT('NaT'), TD(2), DT('NaT'))
675
+ check(DT('NaT', 's'), TD(2, 'h'), DT('NaT', 's'))
676
+ check(DT('NaT', 's'), TD(2, 'ms'), DT('NaT', 'ms'))
677
+ check(DT('2014'), TD('NaT', 'W'), DT('NaT', 'W'))
678
+ check(DT('2014-01-01'), TD('NaT', 'W'), DT('NaT', 'D'))
679
+ check(DT('NaT', 's'), TD('NaT', 'ms'), DT('NaT', 'ms'))
680
+
681
+ # Cannot add datetime days and timedelta months or years
682
+ for f in (add, sub):
683
+ with self.assertRaises((TypeError, TypingError)):
684
+ f(DT(1, '2014-01-01'), TD(1, 'Y'))
685
+ with self.assertRaises((TypeError, TypingError)):
686
+ f(DT(1, '2014-01-01'), TD(1, 'M'))
687
+
688
+ def datetime_samples(self):
689
+ dt_years = ['600', '601', '604', '1968', '1969', '1973',
690
+ '2000', '2004', '2005', '2100', '2400', '2401']
691
+ dt_suffixes = ['', '-01', '-12', '-02-28', '-12-31',
692
+ '-01-05T12:30:56Z', '-01-05T12:30:56.008Z']
693
+ dts = [DT(a + b) for (a, b) in itertools.product(dt_years, dt_suffixes)]
694
+ dts += [DT(s, 'W') for s in dt_years]
695
+ return dts
696
+
697
+ def test_datetime_difference(self):
698
+ """
699
+ Test `datetime64 - datetime64`.
700
+ """
701
+ sub = self.jit(sub_usecase)
702
+ def check(a, b, expected=None):
703
+ with self.silence_numpy_warnings():
704
+ self.assertPreciseEqual(sub(a, b), a - b, (a, b))
705
+ self.assertPreciseEqual(sub(b, a), b - a, (a, b))
706
+ # Did we get it right?
707
+ self.assertPreciseEqual(a - b, expected)
708
+
709
+ check(DT('2014'), DT('2017'), TD(-3, 'Y'))
710
+ check(DT('2014-02'), DT('2017-01'), TD(-35, 'M'))
711
+ check(DT('2014-02-28'), DT('2015-03-01'), TD(-366, 'D'))
712
+ # NaTs
713
+ check(DT('NaT', 'M'), DT('2000'), TD('NaT', 'M'))
714
+ check(DT('NaT', 'M'), DT('2000-01-01'), TD('NaT', 'D'))
715
+ check(DT('NaT'), DT('NaT'), TD('NaT'))
716
+ # Test many more values
717
+ with self.silence_numpy_warnings():
718
+ dts = self.datetime_samples()
719
+ for a, b in itertools.product(dts, dts):
720
+ if (not npdatetime_helpers.same_kind(value_unit(a), value_unit(b))):
721
+ continue
722
+ self.assertPreciseEqual(sub(a, b), a - b, (a, b))
723
+
724
+ def test_comparisons(self):
725
+ # Test all datetime comparisons all at once
726
+ eq = self.jit(eq_usecase)
727
+ ne = self.jit(ne_usecase)
728
+ lt = self.jit(lt_usecase)
729
+ le = self.jit(le_usecase)
730
+ gt = self.jit(gt_usecase)
731
+ ge = self.jit(ge_usecase)
732
+
733
+ def check_eq(a, b, expected):
734
+ expected_val = expected
735
+ not_expected_val = not expected
736
+
737
+ # since np 1.16 all NaT comparisons bar != are False, including
738
+ # NaT==NaT
739
+ if np.isnat(a) or np.isnat(b):
740
+ expected_val = False
741
+ not_expected_val = True
742
+ self.assertFalse(le(a, b), (a, b))
743
+ self.assertFalse(ge(a, b), (a, b))
744
+ self.assertFalse(le(b, a), (a, b))
745
+ self.assertFalse(ge(b, a), (a, b))
746
+ self.assertFalse(lt(a, b), (a, b))
747
+ self.assertFalse(gt(a, b), (a, b))
748
+ self.assertFalse(lt(b, a), (a, b))
749
+ self.assertFalse(gt(b, a), (a, b))
750
+
751
+ with self.silence_numpy_warnings():
752
+ self.assertPreciseEqual(eq(a, b), expected_val, (a, b, expected))
753
+ self.assertPreciseEqual(eq(b, a), expected_val, (a, b, expected))
754
+ self.assertPreciseEqual(ne(a, b), not_expected_val, (a, b, expected))
755
+ self.assertPreciseEqual(ne(b, a), not_expected_val, (a, b, expected))
756
+ if expected_val:
757
+ # If equal, then equal-ordered comparisons are true
758
+ self.assertTrue(le(a, b), (a, b))
759
+ self.assertTrue(ge(a, b), (a, b))
760
+ self.assertTrue(le(b, a), (a, b))
761
+ self.assertTrue(ge(b, a), (a, b))
762
+ # and strictly ordered comparisons are false
763
+ self.assertFalse(lt(a, b), (a, b))
764
+ self.assertFalse(gt(a, b), (a, b))
765
+ self.assertFalse(lt(b, a), (a, b))
766
+ self.assertFalse(gt(b, a), (a, b))
767
+ # Did we get it right?
768
+ self.assertPreciseEqual(a == b, expected_val)
769
+
770
+ def check_lt(a, b, expected):
771
+ expected_val = expected
772
+ not_expected_val = not expected
773
+
774
+ # since np 1.16 all NaT magnitude comparisons including equality
775
+ # are False (as NaT == NaT is now False)
776
+ if np.isnat(a) or np.isnat(b):
777
+ expected_val = False
778
+ not_expected_val = False
779
+
780
+ with self.silence_numpy_warnings():
781
+ lt = self.jit(lt_usecase)
782
+ self.assertPreciseEqual(lt(a, b), expected_val, (a, b, expected))
783
+ self.assertPreciseEqual(gt(b, a), expected_val, (a, b, expected))
784
+ self.assertPreciseEqual(ge(a, b), not_expected_val, (a, b, expected))
785
+ self.assertPreciseEqual(le(b, a), not_expected_val, (a, b, expected))
786
+ if expected_val:
787
+ # If true, then values are not equal
788
+ check_eq(a, b, False)
789
+ # Did we get it right?
790
+ self.assertPreciseEqual(a < b, expected_val)
791
+
792
+ check_eq(DT('2014'), DT('2017'), False)
793
+ check_eq(DT('2014'), DT('2014-01'), True)
794
+ check_eq(DT('2014'), DT('2014-01-01'), True)
795
+ check_eq(DT('2014'), DT('2014-01-01', 'W'), True)
796
+ check_eq(DT('2014-01'), DT('2014-01-01', 'W'), True)
797
+ # Yes, it's not transitive
798
+ check_eq(DT('2014-01-01'), DT('2014-01-01', 'W'), False)
799
+ check_eq(DT('2014-01-02'), DT('2014-01-06', 'W'), True)
800
+ # with times
801
+ check_eq(DT('2014-01-01T00:01:00Z', 's'),
802
+ DT('2014-01-01T00:01Z', 'm'), True)
803
+ check_eq(DT('2014-01-01T00:01:01Z', 's'),
804
+ DT('2014-01-01T00:01Z', 'm'), False)
805
+ # NaTs
806
+ check_lt(DT('NaT', 'Y'), DT('2017'), True)
807
+ check_eq(DT('NaT'), DT('NaT'), True)
808
+
809
+ # Check comparison between various units
810
+ dts = self.datetime_samples()
811
+ for a in dts:
812
+ # Take a number of smaller units
813
+ a_unit = a.dtype.str.split('[')[1][:-1]
814
+ i = all_units.index(a_unit)
815
+ units = all_units[i:i+6]
816
+ for unit in units:
817
+ # Force conversion
818
+ b = a.astype('M8[%s]' % unit)
819
+ if (not npdatetime_helpers.same_kind(value_unit(a),
820
+ value_unit(b))):
821
+ continue
822
+ check_eq(a, b, True)
823
+ check_lt(a, b + np.timedelta64(1, unit), True)
824
+ check_lt(b - np.timedelta64(1, unit), a, True)
825
+
826
+ def _test_min_max(self, usecase):
827
+ f = self.jit(usecase)
828
+ def check(a, b):
829
+ self.assertPreciseEqual(f(a, b), usecase(a, b))
830
+
831
+ for cases in (
832
+ (DT(0, 'ns'), DT(1, 'ns'), DT(2, 'ns'), DT('NaT', 'ns')),
833
+ (DT(0, 's'), DT(1, 's'), DT(2, 's'), DT('NaT', 's')),
834
+ ):
835
+ for a, b in itertools.product(cases, cases):
836
+ check(a, b)
837
+
838
+ def test_min(self):
839
+ self._test_min_max(min_usecase)
840
+
841
+ def test_max(self):
842
+ self._test_min_max(max_usecase)
843
+
844
+ class TestDatetimeArithmeticNoPython(TestDatetimeArithmetic):
845
+
846
+ jitargs = dict(nopython=True)
847
+
848
+
849
+ class TestMetadataScalingFactor(TestCase):
850
+ """
851
+ Tests than non-1 scaling factors are not supported in datetime64
852
+ and timedelta64 dtypes.
853
+ """
854
+
855
+ def test_datetime(self, jitargs={'forceobj':True}):
856
+ eq = jit(**jitargs)(eq_usecase)
857
+ self.assertTrue(eq(DT('2014', '10Y'), DT('2010')))
858
+
859
+ def test_datetime_npm(self):
860
+ with self.assertTypingError():
861
+ self.test_datetime(jitargs={'nopython':True})
862
+
863
+ def test_timedelta(self, jitargs={'forceobj':True}):
864
+ eq = jit(**jitargs)(eq_usecase)
865
+ self.assertTrue(eq(TD(2, '10Y'), TD(20, 'Y')))
866
+
867
+ def test_timedelta_npm(self):
868
+ with self.assertTypingError():
869
+ self.test_timedelta(jitargs={'nopython':True})
870
+
871
+
872
+ class TestDatetimeDeltaOps(TestCase):
873
+ def test_div(self):
874
+ """
875
+ Test the division of a timedelta by numeric types
876
+ """
877
+ def arr_div(a, b):
878
+ return a / b
879
+
880
+ py_func = arr_div
881
+ cfunc = njit(arr_div)
882
+ test_cases = [
883
+ (np.ones(3, TIMEDELTA_M), np.ones(3, TIMEDELTA_M)),
884
+ (np.ones(3, TIMEDELTA_M), np.ones(3, TIMEDELTA_Y)),
885
+ (np.ones(3, TIMEDELTA_Y), np.ones(3, TIMEDELTA_M)),
886
+ (np.ones(3, TIMEDELTA_Y), np.ones(3, TIMEDELTA_Y)),
887
+ (np.ones(3, TIMEDELTA_M), 1),
888
+ (np.ones(3, TIMEDELTA_M), np.ones(3, np.int64)),
889
+ (np.ones(3, TIMEDELTA_M), np.ones(3, np.float64)),
890
+ ]
891
+ for a, b in test_cases:
892
+ self.assertTrue(np.array_equal(py_func(a, b), cfunc(a, b)))
893
+
894
+
895
+ class TestDatetimeArrayOps(TestCase):
896
+
897
+ def _test_td_add_or_sub(self, operation, parallel):
898
+ """
899
+ Test the addition/subtraction of a datetime array with a timedelta type
900
+ """
901
+ def impl(a, b):
902
+ return operation(a, b)
903
+
904
+ arr_one = np.array([
905
+ np.datetime64("2011-01-01"),
906
+ np.datetime64("1971-02-02"),
907
+ np.datetime64("2021-03-03"),
908
+ np.datetime64("2004-12-07"),
909
+ ], dtype="datetime64[ns]")
910
+ arr_two = np.array([
911
+ np.datetime64("2011-01-01"),
912
+ np.datetime64("1971-02-02"),
913
+ np.datetime64("2021-03-03"),
914
+ np.datetime64("2004-12-07"),
915
+ ], dtype="datetime64[D]")
916
+ py_func = impl
917
+ cfunc = njit(parallel=parallel)(impl)
918
+ test_cases = [
919
+ (arr_one, np.timedelta64(1000)),
920
+ (arr_two, np.timedelta64(1000)),
921
+ (arr_one, np.timedelta64(-54557)),
922
+ (arr_two, np.timedelta64(-54557)),
923
+ ]
924
+ # np.add is commutative so test the reversed order
925
+ if operation is np.add:
926
+ test_cases.extend([
927
+ (np.timedelta64(1000), arr_one),
928
+ (np.timedelta64(1000), arr_two),
929
+ (np.timedelta64(-54557), arr_one),
930
+ (np.timedelta64(-54557), arr_two),
931
+ ])
932
+ for a, b in test_cases:
933
+ self.assertTrue(np.array_equal(py_func(a, b), cfunc(a, b)))
934
+
935
+ def test_add_td(self):
936
+ self._test_td_add_or_sub(np.add, False)
937
+
938
+ @skip_parfors_unsupported
939
+ def test_add_td_parallel(self):
940
+ self._test_td_add_or_sub(np.add, True)
941
+
942
+ def test_sub_td(self):
943
+ self._test_td_add_or_sub(np.subtract, False)
944
+
945
+ @skip_parfors_unsupported
946
+ def test_sub_td_parallel(self):
947
+ self._test_td_add_or_sub(np.subtract, True)
948
+
949
+ def _test_add_sub_td_no_match(self, operation):
950
+ """
951
+ Tests that attempting to add/sub a datetime64 and timedelta64
952
+ with types that cannot be cast raises a reasonable exception.
953
+ """
954
+ @njit
955
+ def impl(a, b):
956
+ return operation(a, b)
957
+
958
+ fname = operation.__name__
959
+ expected = re.escape((f"ufunc '{fname}' is not supported between "
960
+ "datetime64[ns] and timedelta64[M]"))
961
+ with self.assertRaisesRegex((TypingError, TypeError), expected):
962
+ impl(
963
+ np.array([np.datetime64("2011-01-01"),],
964
+ dtype="datetime64[ns]"),
965
+ np.timedelta64(1000,'M')
966
+ )
967
+
968
+ def test_add_td_no_match(self):
969
+ self._test_add_sub_td_no_match(np.add)
970
+
971
+ def test_sub_td_no_match(self):
972
+ self._test_add_sub_td_no_match(np.subtract)
973
+
974
+ def _get_testcases(self):
975
+ test_cases = [
976
+ np.array([
977
+ DT(0, "ns"),
978
+ DT(1, "ns"),
979
+ DT(2, "ns"),
980
+ DT(3, "ns"),
981
+ ]),
982
+ np.array([
983
+ DT("2011-01-01", "ns"),
984
+ DT("1971-02-02", "ns"),
985
+ DT("1900-01-01", "ns"),
986
+ DT("2021-03-03", "ns"),
987
+ DT("2004-12-07", "ns"),
988
+ ]),
989
+ np.array([
990
+ DT("2011-01-01", "D"),
991
+ DT("1971-02-02", "D"),
992
+ DT("1900-01-01", "D"),
993
+ DT("2021-03-03", "D"),
994
+ DT("2004-12-07", "D"),
995
+ ]),
996
+ np.array([
997
+ DT("2011-01-01", "ns"),
998
+ DT("1971-02-02", "ns"),
999
+ DT("1900-01-01", "ns"),
1000
+ DT("2021-03-03", "ns"),
1001
+ DT("2004-12-07", "ns"),
1002
+ DT("NaT", "ns"),
1003
+ ]),
1004
+ np.array([
1005
+ DT("NaT", "ns"),
1006
+ DT("2011-01-01", "ns"),
1007
+ DT("1971-02-02", "ns"),
1008
+ DT("1900-01-01", "ns"),
1009
+ DT("2021-03-03", "ns"),
1010
+ DT("2004-12-07", "ns"),
1011
+ ]),
1012
+ np.array([
1013
+ DT("1971-02-02", "ns"),
1014
+ DT("NaT", "ns"),
1015
+ ]),
1016
+ np.array([
1017
+ DT("NaT", "ns"),
1018
+ DT("NaT", "ns"),
1019
+ DT("NaT", "ns"),
1020
+ ]),
1021
+ np.array([
1022
+ TD(1, "ns"),
1023
+ TD(2, "ns"),
1024
+ TD(3, "ns"),
1025
+ TD(4, "ns"),
1026
+ ]),
1027
+ np.array([
1028
+ TD(1, "D"),
1029
+ TD(2, "D"),
1030
+ TD(3, "D"),
1031
+ TD(4, "D"),
1032
+ ]),
1033
+ np.array([
1034
+ TD("NaT", "ns"),
1035
+ TD(1, "ns"),
1036
+ TD(2, "ns"),
1037
+ TD(3, "ns"),
1038
+ TD(4, "ns"),
1039
+ ]),
1040
+ np.array([
1041
+ TD(1, "ns"),
1042
+ TD(2, "ns"),
1043
+ TD(3, "ns"),
1044
+ TD(4, "ns"),
1045
+ TD("NaT", "ns"),
1046
+ ]),
1047
+ np.array([
1048
+ TD("NaT", "ns"),
1049
+ ]),
1050
+ np.array([
1051
+ TD("NaT", "ns"),
1052
+ TD("NaT", "ns"),
1053
+ TD("NaT", "ns"),
1054
+ ]),
1055
+ ]
1056
+ return test_cases
1057
+
1058
+ def _test_min_max(self, operation, parallel, method):
1059
+ if method:
1060
+ if operation is np.min:
1061
+ def impl(arr):
1062
+ return arr.min()
1063
+ else:
1064
+ def impl(arr):
1065
+ return arr.max()
1066
+ else:
1067
+ def impl(arr):
1068
+ return operation(arr)
1069
+
1070
+ py_func = impl
1071
+ cfunc = njit(parallel=parallel)(impl)
1072
+
1073
+ test_cases = self._get_testcases()
1074
+ for arr in test_cases:
1075
+ py_res = py_func(arr)
1076
+ c_res = cfunc(arr)
1077
+ if np.isnat(py_res) or np.isnat(c_res):
1078
+ self.assertTrue(np.isnat(py_res))
1079
+ self.assertTrue(np.isnat(c_res))
1080
+ else:
1081
+ self.assertEqual(py_res, c_res)
1082
+
1083
+ def test_min_func(self):
1084
+ self._test_min_max(min, False, False)
1085
+
1086
+ def test_np_min_func(self):
1087
+ self._test_min_max(np.min, False, False)
1088
+
1089
+ def test_min_method(self):
1090
+ self._test_min_max(np.min, False, True)
1091
+
1092
+ def test_max_func(self):
1093
+ self._test_min_max(max, False, False)
1094
+
1095
+ def test_np_max_func(self):
1096
+ self._test_min_max(np.max, False, False)
1097
+
1098
+ def test_max_method(self):
1099
+ self._test_min_max(np.max, False, True)
1100
+
1101
+ @skip_parfors_unsupported
1102
+ def test_min_func_parallel(self):
1103
+ self._test_min_max(np.min, True, False)
1104
+
1105
+ @skip_parfors_unsupported
1106
+ def test_min_method_parallel(self):
1107
+ self._test_min_max(np.min, True, True)
1108
+
1109
+ @skip_parfors_unsupported
1110
+ def test_max_func_parallel(self):
1111
+ self._test_min_max(np.max, True, False)
1112
+
1113
+ @skip_parfors_unsupported
1114
+ def test_max_method_parallel(self):
1115
+ self._test_min_max(np.max, True, True)
1116
+
1117
+ def test_searchsorted_datetime(self):
1118
+ from .test_np_functions import (
1119
+ searchsorted, searchsorted_left, searchsorted_right,
1120
+ )
1121
+ pyfunc_list = [searchsorted, searchsorted_left, searchsorted_right]
1122
+ cfunc_list = [jit(fn) for fn in pyfunc_list]
1123
+
1124
+ def check(pyfunc, cfunc, a, v):
1125
+ expected = pyfunc(a, v)
1126
+ got = cfunc(a, v)
1127
+ self.assertPreciseEqual(expected, got)
1128
+
1129
+ cases = self._get_testcases()
1130
+ for pyfunc, cfunc in zip(pyfunc_list, cfunc_list):
1131
+ for arr in cases:
1132
+ arr = np.sort(arr)
1133
+ for n in range(1, min(3, arr.size) + 1):
1134
+ idx = np.random.randint(0, arr.size, n)
1135
+ vs = arr[idx]
1136
+ if n == 1:
1137
+ [v] = vs
1138
+ check(pyfunc, cfunc, arr, v)
1139
+ check(pyfunc, cfunc, arr, vs)
1140
+
1141
+
1142
+
1143
+ class TestDatetimeTypeOps(TestCase):
1144
+ def test_isinstance_datetime(self):
1145
+ @njit
1146
+ def is_complex(a):
1147
+ return isinstance(a, complex)
1148
+ @njit
1149
+ def is_datetime(a):
1150
+ return isinstance(a, np.datetime64)
1151
+ @njit
1152
+ def is_timedelta(a):
1153
+ return isinstance(a, np.timedelta64)
1154
+
1155
+ dt_a = np.datetime64(1, 'ns')
1156
+ dt_b = np.datetime64(2, 'ns')
1157
+ td_c = dt_b - dt_a
1158
+
1159
+ def check(jit_func, x):
1160
+ with self.subTest(f'{jit_func.__name__}({type(x).__name__})'):
1161
+ got = jit_func(x)
1162
+ expect = jit_func.py_func(x)
1163
+ self.assertEqual(got, expect)
1164
+
1165
+ fns = [
1166
+ is_complex,
1167
+ is_datetime,
1168
+ is_timedelta,
1169
+ ]
1170
+ args = [
1171
+ dt_a,
1172
+ dt_b,
1173
+ td_c,
1174
+ ]
1175
+ for fn, arg in itertools.product(fns, args):
1176
+ check(fn, arg)
1177
+
1178
+
1179
+ if __name__ == '__main__':
1180
+ unittest.main()
lib/python3.10/site-packages/numba/tests/test_nrt.py ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import platform
4
+ import sys
5
+ import re
6
+
7
+ import numpy as np
8
+
9
+ from numba import njit
10
+ from numba.core import types
11
+ from numba.core.runtime import (
12
+ rtsys,
13
+ nrtopt,
14
+ _nrt_python,
15
+ nrt,
16
+ )
17
+ from numba.core.extending import intrinsic, include_path
18
+ from numba.core.typing import signature
19
+ from numba.core.imputils import impl_ret_untracked
20
+ from llvmlite import ir
21
+ import llvmlite.binding as llvm
22
+ from numba.core.unsafe.nrt import NRT_get_api
23
+
24
+ from numba.tests.support import (EnableNRTStatsMixin, TestCase, temp_directory,
25
+ import_dynamic, skip_if_32bit,
26
+ skip_unless_cffi, run_in_subprocess)
27
+ from numba.core.registry import cpu_target
28
+ import unittest
29
+
30
+
31
+ linux_only = unittest.skipIf(not sys.platform.startswith('linux'),
32
+ 'linux only test')
33
+ x86_only = unittest.skipIf(platform.machine() not in ('i386', 'x86_64'),
34
+ 'x86 only test')
35
+
36
+
37
+ class Dummy(object):
38
+ alive = 0
39
+
40
+ def __init__(self):
41
+ type(self).alive += 1
42
+
43
+ def __del__(self):
44
+ type(self).alive -= 1
45
+
46
+
47
+ class TestNrtMemInfoNotInitialized(unittest.TestCase):
48
+ """
49
+ Unit test for checking the use of the NRT fails if the
50
+ initialization sequence has not been run.
51
+ """
52
+ _numba_parallel_test_ = False
53
+
54
+ def test_init_fail(self):
55
+ methods = {'library': (),
56
+ 'meminfo_new': ((), ()),
57
+ 'meminfo_alloc': ((),),
58
+ }
59
+
60
+ for meth, args in methods.items():
61
+ try:
62
+ with self.assertRaises(RuntimeError) as raises:
63
+ rtsys._init = False
64
+ fn = getattr(rtsys, meth)
65
+ fn(*args)
66
+
67
+ msg = "Runtime must be initialized before use."
68
+ self.assertIn(msg, str(raises.exception))
69
+ finally:
70
+ rtsys._init = True
71
+
72
+
73
+ class TestNrtMemInfo(unittest.TestCase):
74
+ """
75
+ Unit test for core MemInfo functionality
76
+ """
77
+
78
+ def setUp(self):
79
+ # Reset the Dummy class
80
+ Dummy.alive = 0
81
+ # initialize the NRT (in case the tests are run in isolation)
82
+ rtsys.initialize(cpu_target.target_context)
83
+ super(TestNrtMemInfo, self).setUp()
84
+
85
+ def test_meminfo_refct_1(self):
86
+ d = Dummy()
87
+ self.assertEqual(Dummy.alive, 1)
88
+ addr = 0xdeadcafe # some made up location
89
+
90
+ mi = rtsys.meminfo_new(addr, d)
91
+ self.assertEqual(mi.refcount, 1)
92
+ del d
93
+ self.assertEqual(Dummy.alive, 1)
94
+ mi.acquire()
95
+ self.assertEqual(mi.refcount, 2)
96
+ self.assertEqual(Dummy.alive, 1)
97
+ mi.release()
98
+ self.assertEqual(mi.refcount, 1)
99
+ del mi
100
+ self.assertEqual(Dummy.alive, 0)
101
+
102
+ def test_meminfo_refct_2(self):
103
+ d = Dummy()
104
+ self.assertEqual(Dummy.alive, 1)
105
+ addr = 0xdeadcafe # some made up location
106
+
107
+ mi = rtsys.meminfo_new(addr, d)
108
+ self.assertEqual(mi.refcount, 1)
109
+ del d
110
+ self.assertEqual(Dummy.alive, 1)
111
+ for ct in range(100):
112
+ mi.acquire()
113
+ self.assertEqual(mi.refcount, 1 + 100)
114
+ self.assertEqual(Dummy.alive, 1)
115
+ for _ in range(100):
116
+ mi.release()
117
+ self.assertEqual(mi.refcount, 1)
118
+ del mi
119
+ self.assertEqual(Dummy.alive, 0)
120
+
121
+ def test_fake_memoryview(self):
122
+ d = Dummy()
123
+ self.assertEqual(Dummy.alive, 1)
124
+ addr = 0xdeadcafe # some made up location
125
+
126
+ mi = rtsys.meminfo_new(addr, d)
127
+ self.assertEqual(mi.refcount, 1)
128
+ mview = memoryview(mi)
129
+ self.assertEqual(mi.refcount, 1)
130
+ self.assertEqual(addr, mi.data)
131
+ self.assertFalse(mview.readonly)
132
+ self.assertIs(mi, mview.obj)
133
+ self.assertTrue(mview.c_contiguous)
134
+ self.assertEqual(mview.itemsize, 1)
135
+ self.assertEqual(mview.ndim, 1)
136
+ del d
137
+ del mi
138
+
139
+ self.assertEqual(Dummy.alive, 1)
140
+ del mview
141
+ self.assertEqual(Dummy.alive, 0)
142
+
143
+ def test_memoryview(self):
144
+ from ctypes import c_uint32, c_void_p, POINTER, cast
145
+
146
+ dtype = np.dtype(np.uint32)
147
+ bytesize = dtype.itemsize * 10
148
+ mi = rtsys.meminfo_alloc(bytesize, safe=True)
149
+ addr = mi.data
150
+ c_arr = cast(c_void_p(mi.data), POINTER(c_uint32 * 10))
151
+ # Check 0xCB-filling
152
+ for i in range(10):
153
+ self.assertEqual(c_arr.contents[i], 0xcbcbcbcb)
154
+
155
+ # Init array with ctypes
156
+ for i in range(10):
157
+ c_arr.contents[i] = i + 1
158
+ mview = memoryview(mi)
159
+ self.assertEqual(mview.nbytes, bytesize)
160
+ self.assertFalse(mview.readonly)
161
+ self.assertIs(mi, mview.obj)
162
+ self.assertTrue(mview.c_contiguous)
163
+ self.assertEqual(mview.itemsize, 1)
164
+ self.assertEqual(mview.ndim, 1)
165
+ del mi
166
+ arr = np.ndarray(dtype=dtype, shape=mview.nbytes // dtype.itemsize,
167
+ buffer=mview)
168
+ del mview
169
+ # Modify array with NumPy
170
+ np.testing.assert_equal(np.arange(arr.size) + 1, arr)
171
+
172
+ arr += 1
173
+
174
+ # Check value reflected in ctypes
175
+ for i in range(10):
176
+ self.assertEqual(c_arr.contents[i], i + 2)
177
+
178
+ self.assertEqual(arr.ctypes.data, addr)
179
+ del arr
180
+ # At this point the memory is zero filled
181
+ # We can't check this deterministically because the memory could be
182
+ # consumed by another thread.
183
+
184
+ def test_buffer(self):
185
+ from ctypes import c_uint32, c_void_p, POINTER, cast
186
+
187
+ dtype = np.dtype(np.uint32)
188
+ bytesize = dtype.itemsize * 10
189
+ mi = rtsys.meminfo_alloc(bytesize, safe=True)
190
+ self.assertEqual(mi.refcount, 1)
191
+ addr = mi.data
192
+ c_arr = cast(c_void_p(addr), POINTER(c_uint32 * 10))
193
+ # Check 0xCB-filling
194
+ for i in range(10):
195
+ self.assertEqual(c_arr.contents[i], 0xcbcbcbcb)
196
+
197
+ # Init array with ctypes
198
+ for i in range(10):
199
+ c_arr.contents[i] = i + 1
200
+
201
+ arr = np.ndarray(dtype=dtype, shape=bytesize // dtype.itemsize,
202
+ buffer=mi)
203
+ self.assertEqual(mi.refcount, 1)
204
+ del mi
205
+ # Modify array with NumPy
206
+ np.testing.assert_equal(np.arange(arr.size) + 1, arr)
207
+
208
+ arr += 1
209
+
210
+ # Check value reflected in ctypes
211
+ for i in range(10):
212
+ self.assertEqual(c_arr.contents[i], i + 2)
213
+
214
+ self.assertEqual(arr.ctypes.data, addr)
215
+ del arr
216
+ # At this point the memory is zero filled
217
+ # We can't check this deterministically because the memory could be
218
+ # consumed by another thread.
219
+
220
+ @skip_if_32bit
221
+ def test_allocate_invalid_size(self):
222
+ # Checks that attempting to allocate too big a region fails gracefully.
223
+ size = types.size_t.maxval // 8 // 2
224
+ for pred in (True, False):
225
+ with self.assertRaises(MemoryError) as raises:
226
+ rtsys.meminfo_alloc(size, safe=pred)
227
+ self.assertIn(f"Requested allocation of {size} bytes failed.",
228
+ str(raises.exception))
229
+
230
+ def test_allocate_negative_size(self):
231
+ # Checks that attempting to allocate negative number of bytes fails
232
+ # gracefully.
233
+ size = -10
234
+ for pred in (True, False):
235
+ with self.assertRaises(ValueError) as raises:
236
+ rtsys.meminfo_alloc(size, safe=pred)
237
+ msg = f"Cannot allocate a negative number of bytes: {size}."
238
+ self.assertIn(msg, str(raises.exception))
239
+
240
+
241
+ class TestTracemalloc(unittest.TestCase):
242
+ """
243
+ Test NRT-allocated memory can be tracked by tracemalloc.
244
+ """
245
+
246
+ def measure_memory_diff(self, func):
247
+ try:
248
+ import tracemalloc
249
+ except ImportError:
250
+ self.skipTest("tracemalloc not available")
251
+ tracemalloc.start()
252
+ try:
253
+ before = tracemalloc.take_snapshot()
254
+ # Keep the result and only delete it after taking a snapshot
255
+ res = func()
256
+ after = tracemalloc.take_snapshot()
257
+ del res
258
+ return after.compare_to(before, 'lineno')
259
+ finally:
260
+ tracemalloc.stop()
261
+
262
+ def test_snapshot(self):
263
+ N = 1000000
264
+ dtype = np.int8
265
+
266
+ @njit
267
+ def alloc_nrt_memory():
268
+ """
269
+ Allocate and return a large array.
270
+ """
271
+ return np.empty(N, dtype)
272
+
273
+ def keep_memory():
274
+ return alloc_nrt_memory()
275
+
276
+ def release_memory():
277
+ alloc_nrt_memory()
278
+
279
+ alloc_lineno = keep_memory.__code__.co_firstlineno + 1
280
+
281
+ # Warmup JIT
282
+ alloc_nrt_memory()
283
+
284
+ # The large NRT-allocated array should appear topmost in the diff
285
+ diff = self.measure_memory_diff(keep_memory)
286
+ stat = diff[0]
287
+ # There is a slight overhead, so the allocated size won't exactly be N
288
+ self.assertGreaterEqual(stat.size, N)
289
+ self.assertLess(stat.size, N * 1.015,
290
+ msg=("Unexpected allocation overhead encountered. "
291
+ "May be due to difference in CPython "
292
+ "builds or running under coverage"))
293
+ frame = stat.traceback[0]
294
+ self.assertEqual(os.path.basename(frame.filename), "test_nrt.py")
295
+ self.assertEqual(frame.lineno, alloc_lineno)
296
+
297
+ # If NRT memory is released before taking a snapshot, it shouldn't
298
+ # appear.
299
+ diff = self.measure_memory_diff(release_memory)
300
+ stat = diff[0]
301
+ # Something else appears, but nothing the magnitude of N
302
+ self.assertLess(stat.size, N * 0.01)
303
+
304
+
305
+ class TestNRTIssue(TestCase):
306
+ def test_issue_with_refct_op_pruning(self):
307
+ """
308
+ GitHub Issue #1244 https://github.com/numba/numba/issues/1244
309
+ """
310
+ @njit
311
+ def calculate_2D_vector_mag(vector):
312
+ x, y = vector
313
+
314
+ return math.sqrt(x ** 2 + y ** 2)
315
+
316
+ @njit
317
+ def normalize_2D_vector(vector):
318
+ normalized_vector = np.empty(2, dtype=np.float64)
319
+
320
+ mag = calculate_2D_vector_mag(vector)
321
+ x, y = vector
322
+
323
+ normalized_vector[0] = x / mag
324
+ normalized_vector[1] = y / mag
325
+
326
+ return normalized_vector
327
+
328
+ @njit
329
+ def normalize_vectors(num_vectors, vectors):
330
+ normalized_vectors = np.empty((num_vectors, 2), dtype=np.float64)
331
+
332
+ for i in range(num_vectors):
333
+ vector = vectors[i]
334
+
335
+ normalized_vector = normalize_2D_vector(vector)
336
+
337
+ normalized_vectors[i, 0] = normalized_vector[0]
338
+ normalized_vectors[i, 1] = normalized_vector[1]
339
+
340
+ return normalized_vectors
341
+
342
+ num_vectors = 10
343
+ test_vectors = np.random.random((num_vectors, 2))
344
+ got = normalize_vectors(num_vectors, test_vectors)
345
+ expected = normalize_vectors.py_func(num_vectors, test_vectors)
346
+
347
+ np.testing.assert_almost_equal(expected, got)
348
+
349
+ def test_incref_after_cast(self):
350
+ # Issue #1427: when casting a value before returning it, the
351
+ # cast result should be incref'ed, not the original value.
352
+ def f():
353
+ return 0.0, np.zeros(1, dtype=np.int32)
354
+
355
+ # Note the return type isn't the same as the tuple type above:
356
+ # the first element is a complex rather than a float.
357
+ cfunc = njit((types.Tuple((types.complex128,
358
+ types.Array(types.int32, 1, 'C') )))())(f)
359
+ z, arr = cfunc()
360
+ self.assertPreciseEqual(z, 0j)
361
+ self.assertPreciseEqual(arr, np.zeros(1, dtype=np.int32))
362
+
363
+ def test_refct_pruning_issue_1511(self):
364
+ @njit
365
+ def f():
366
+ a = np.ones(10, dtype=np.float64)
367
+ b = np.ones(10, dtype=np.float64)
368
+ return a, b[:]
369
+
370
+ a, b = f()
371
+ np.testing.assert_equal(a, b)
372
+ np.testing.assert_equal(a, np.ones(10, dtype=np.float64))
373
+
374
+ def test_refct_pruning_issue_1526(self):
375
+ @njit
376
+ def udt(image, x, y):
377
+ next_loc = np.where(image == 1)
378
+
379
+ if len(next_loc[0]) == 0:
380
+ y_offset = 1
381
+ x_offset = 1
382
+ else:
383
+ y_offset = next_loc[0][0]
384
+ x_offset = next_loc[1][0]
385
+
386
+ next_loc_x = (x - 1) + x_offset
387
+ next_loc_y = (y - 1) + y_offset
388
+
389
+ return next_loc_x, next_loc_y
390
+
391
+ a = np.array([[1, 0, 1, 0, 1, 0, 0, 1, 0, 0]])
392
+ expect = udt.py_func(a, 1, 6)
393
+ got = udt(a, 1, 6)
394
+
395
+ self.assertEqual(expect, got)
396
+
397
+ @TestCase.run_test_in_subprocess
398
+ def test_no_nrt_on_njit_decoration(self):
399
+ # Checks that the NRT is not initialized/compiled as a result of
400
+ # decorating a function with `@njit`.
401
+ from numba import njit
402
+
403
+ # check the NRT is not initialized.
404
+ self.assertFalse(rtsys._init)
405
+
406
+ # decorate
407
+ @njit
408
+ def foo():
409
+ return 123
410
+
411
+ # check the NRT is still not initialized
412
+ self.assertFalse(rtsys._init)
413
+
414
+ # execute
415
+ self.assertEqual(foo(), foo.py_func())
416
+
417
+ # check the NRT is still now initialized as execution has definitely
418
+ # occurred.
419
+ self.assertTrue(rtsys._init)
420
+
421
+
422
+ class TestRefCtPruning(unittest.TestCase):
423
+
424
+ sample_llvm_ir = '''
425
+ define i32 @"MyFunction"(i8** noalias nocapture %retptr, { i8*, i32 }** noalias nocapture %excinfo, i8* noalias nocapture readnone %env, double %arg.vt.0, double %arg.vt.1, double %arg.vt.2, double %arg.vt.3, double %arg.bounds.0, double %arg.bounds.1, double %arg.bounds.2, double %arg.bounds.3, i8* %arg.xs.0, i8* nocapture readnone %arg.xs.1, i64 %arg.xs.2, i64 %arg.xs.3, double* nocapture readonly %arg.xs.4, i64 %arg.xs.5.0, i64 %arg.xs.6.0, i8* %arg.ys.0, i8* nocapture readnone %arg.ys.1, i64 %arg.ys.2, i64 %arg.ys.3, double* nocapture readonly %arg.ys.4, i64 %arg.ys.5.0, i64 %arg.ys.6.0, i8* %arg.aggs_and_cols.0.0, i8* nocapture readnone %arg.aggs_and_cols.0.1, i64 %arg.aggs_and_cols.0.2, i64 %arg.aggs_and_cols.0.3, i32* nocapture %arg.aggs_and_cols.0.4, i64 %arg.aggs_and_cols.0.5.0, i64 %arg.aggs_and_cols.0.5.1, i64 %arg.aggs_and_cols.0.6.0, i64 %arg.aggs_and_cols.0.6.1) local_unnamed_addr {
426
+ entry:
427
+ tail call void @NRT_incref(i8* %arg.xs.0)
428
+ tail call void @NRT_incref(i8* %arg.ys.0)
429
+ tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0)
430
+ %.251 = icmp sgt i64 %arg.xs.5.0, 0
431
+ br i1 %.251, label %B42.preheader, label %B160
432
+
433
+ B42.preheader: ; preds = %entry
434
+ %0 = add i64 %arg.xs.5.0, 1
435
+ br label %B42
436
+
437
+ B42: ; preds = %B40.backedge, %B42.preheader
438
+ %lsr.iv3 = phi i64 [ %lsr.iv.next, %B40.backedge ], [ %0, %B42.preheader ]
439
+ %lsr.iv1 = phi double* [ %scevgep2, %B40.backedge ], [ %arg.xs.4, %B42.preheader ]
440
+ %lsr.iv = phi double* [ %scevgep, %B40.backedge ], [ %arg.ys.4, %B42.preheader ]
441
+ %.381 = load double, double* %lsr.iv1, align 8
442
+ %.420 = load double, double* %lsr.iv, align 8
443
+ %.458 = fcmp ole double %.381, %arg.bounds.1
444
+ %not..432 = fcmp oge double %.381, %arg.bounds.0
445
+ %"$phi82.1.1" = and i1 %.458, %not..432
446
+ br i1 %"$phi82.1.1", label %B84, label %B40.backedge
447
+
448
+ B84: ; preds = %B42
449
+ %.513 = fcmp ole double %.420, %arg.bounds.3
450
+ %not..487 = fcmp oge double %.420, %arg.bounds.2
451
+ %"$phi106.1.1" = and i1 %.513, %not..487
452
+ br i1 %"$phi106.1.1", label %B108.endif.endif.endif, label %B40.backedge
453
+
454
+ B160: ; preds = %B40.backedge, %entry
455
+ tail call void @NRT_decref(i8* %arg.ys.0)
456
+ tail call void @NRT_decref(i8* %arg.xs.0)
457
+ tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0)
458
+ store i8* null, i8** %retptr, align 8
459
+ ret i32 0
460
+
461
+ B108.endif.endif.endif: ; preds = %B84
462
+ %.575 = fmul double %.381, %arg.vt.0
463
+ %.583 = fadd double %.575, %arg.vt.1
464
+ %.590 = fptosi double %.583 to i64
465
+ %.630 = fmul double %.420, %arg.vt.2
466
+ %.638 = fadd double %.630, %arg.vt.3
467
+ %.645 = fptosi double %.638 to i64
468
+ tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) ; GONE 1
469
+ tail call void @NRT_decref(i8* null) ; GONE 2
470
+ tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 3
471
+ %.62.i.i = icmp slt i64 %.645, 0
472
+ %.63.i.i = select i1 %.62.i.i, i64 %arg.aggs_and_cols.0.5.0, i64 0
473
+ %.64.i.i = add i64 %.63.i.i, %.645
474
+ %.65.i.i = icmp slt i64 %.590, 0
475
+ %.66.i.i = select i1 %.65.i.i, i64 %arg.aggs_and_cols.0.5.1, i64 0
476
+ %.67.i.i = add i64 %.66.i.i, %.590
477
+ %.84.i.i = mul i64 %.64.i.i, %arg.aggs_and_cols.0.5.1
478
+ %.87.i.i = add i64 %.67.i.i, %.84.i.i
479
+ %.88.i.i = getelementptr i32, i32* %arg.aggs_and_cols.0.4, i64 %.87.i.i
480
+ %.89.i.i = load i32, i32* %.88.i.i, align 4, !noalias !3
481
+ %.99.i.i = add i32 %.89.i.i, 1
482
+ store i32 %.99.i.i, i32* %.88.i.i, align 4, !noalias !3
483
+ tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 4
484
+ tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) ; GONE 5
485
+ br label %B40.backedge
486
+
487
+ B40.backedge: ; preds = %B108.endif.endif.endif, %B84, %B42
488
+ %scevgep = getelementptr double, double* %lsr.iv, i64 1
489
+ %scevgep2 = getelementptr double, double* %lsr.iv1, i64 1
490
+ %lsr.iv.next = add i64 %lsr.iv3, -1
491
+ %.294 = icmp sgt i64 %lsr.iv.next, 1
492
+ br i1 %.294, label %B42, label %B160
493
+ }
494
+ ''' # noqa
495
+
496
+ def test_refct_pruning_op_recognize(self):
497
+ input_ir = self.sample_llvm_ir
498
+ input_lines = list(input_ir.splitlines())
499
+ before_increfs = [ln for ln in input_lines if 'NRT_incref' in ln]
500
+ before_decrefs = [ln for ln in input_lines if 'NRT_decref' in ln]
501
+
502
+ # prune
503
+ output_ir = nrtopt._remove_redundant_nrt_refct(input_ir)
504
+ output_lines = list(output_ir.splitlines())
505
+ after_increfs = [ln for ln in output_lines if 'NRT_incref' in ln]
506
+ after_decrefs = [ln for ln in output_lines if 'NRT_decref' in ln]
507
+
508
+ # check
509
+ self.assertNotEqual(before_increfs, after_increfs)
510
+ self.assertNotEqual(before_decrefs, after_decrefs)
511
+
512
+ pruned_increfs = set(before_increfs) - set(after_increfs)
513
+ pruned_decrefs = set(before_decrefs) - set(after_decrefs)
514
+
515
+ # the symm difference == or-combined
516
+ combined = pruned_increfs | pruned_decrefs
517
+ self.assertEqual(combined, pruned_increfs ^ pruned_decrefs)
518
+ pruned_lines = '\n'.join(combined)
519
+
520
+ # all GONE lines are pruned
521
+ for i in [1, 2, 3, 4, 5]:
522
+ gone = '; GONE {}'.format(i)
523
+ self.assertIn(gone, pruned_lines)
524
+ # no other lines
525
+ self.assertEqual(len(list(pruned_lines.splitlines())), len(combined))
526
+
527
+ @unittest.skip("Pass removed as it was buggy. Re-enable when fixed.")
528
+ def test_refct_pruning_with_branches(self):
529
+ '''testcase from #2350'''
530
+ @njit
531
+ def _append_non_na(x, y, agg, field):
532
+ if not np.isnan(field):
533
+ agg[y, x] += 1
534
+
535
+ @njit
536
+ def _append(x, y, agg, field):
537
+ if not np.isnan(field):
538
+ if np.isnan(agg[y, x]):
539
+ agg[y, x] = field
540
+ else:
541
+ agg[y, x] += field
542
+
543
+ @njit
544
+ def append(x, y, agg, field):
545
+ _append_non_na(x, y, agg, field)
546
+ _append(x, y, agg, field)
547
+
548
+ # Disable python wrapper to avoid detecting necessary
549
+ # refcount inside it
550
+ @njit(no_cpython_wrapper=True)
551
+ def extend(arr, field):
552
+ for i in range(arr.shape[0]):
553
+ for j in range(arr.shape[1]):
554
+ append(j, i, arr, field)
555
+
556
+ # Compile
557
+ extend.compile("(f4[:,::1], f4)")
558
+
559
+ # Test there are no reference count operations
560
+ llvmir = str(extend.inspect_llvm(extend.signatures[0]))
561
+ refops = list(re.finditer(r'(NRT_incref|NRT_decref)\([^\)]+\)', llvmir))
562
+ self.assertEqual(len(refops), 0)
563
+
564
+ @linux_only
565
+ @x86_only
566
+ def test_inline_asm(self):
567
+ """The InlineAsm class from llvmlite.ir has no 'name' attr the refcount
568
+ pruning pass should be tolerant to this"""
569
+ llvm.initialize()
570
+ llvm.initialize_native_target()
571
+ llvm.initialize_native_asmprinter()
572
+ llvm.initialize_native_asmparser()
573
+
574
+ @intrinsic
575
+ def bar(tyctx, x, y):
576
+ def codegen(cgctx, builder, sig, args):
577
+ (arg_0, arg_1) = args
578
+ fty = ir.FunctionType(ir.IntType(32), [ir.IntType(32),
579
+ ir.IntType(32)])
580
+ mul = builder.asm(fty, "mov $2, $0; imul $1, $0", "=&r,r,r",
581
+ (arg_0, arg_1), name="asm_mul",
582
+ side_effect=False)
583
+ return impl_ret_untracked(cgctx, builder, sig.return_type, mul)
584
+ return signature(types.int32, types.int32, types.int32), codegen
585
+
586
+ @njit(['int32(int32)'])
587
+ def foo(x):
588
+ x += 1
589
+ z = bar(x, 2)
590
+ return z
591
+
592
+ self.assertEqual(foo(10), 22) # expect (10 + 1) * 2 = 22
593
+
594
+
595
+ @skip_unless_cffi
596
+ class TestNrtExternalCFFI(EnableNRTStatsMixin, TestCase):
597
+ """Testing the use of externally compiled C code that use NRT
598
+ """
599
+ def setUp(self):
600
+ # initialize the NRT (in case the tests are run in isolation)
601
+ cpu_target.target_context
602
+ super(TestNrtExternalCFFI, self).setUp()
603
+
604
+ def compile_cffi_module(self, name, source, cdef):
605
+ from cffi import FFI
606
+
607
+ ffi = FFI()
608
+ ffi.set_source(name, source, include_dirs=[include_path()])
609
+ ffi.cdef(cdef)
610
+ tmpdir = temp_directory("cffi_test_{}".format(name))
611
+ ffi.compile(tmpdir=tmpdir)
612
+ sys.path.append(tmpdir)
613
+ try:
614
+ mod = import_dynamic(name)
615
+ finally:
616
+ sys.path.remove(tmpdir)
617
+
618
+ return ffi, mod
619
+
620
+ def get_nrt_api_table(self):
621
+ from cffi import FFI
622
+
623
+ ffi = FFI()
624
+ nrt_get_api = ffi.cast("void* (*)()", _nrt_python.c_helpers['get_api'])
625
+ table = nrt_get_api()
626
+ return table
627
+
628
+ def test_manage_memory(self):
629
+ name = "{}_test_manage_memory".format(self.__class__.__name__)
630
+ source = r"""
631
+ #include <stdio.h>
632
+ #include "numba/core/runtime/nrt_external.h"
633
+
634
+ int status = 0;
635
+
636
+ void my_dtor(void *ptr) {
637
+ free(ptr);
638
+ status = 0xdead;
639
+ }
640
+
641
+ NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt) {
642
+ void * data = malloc(10);
643
+ NRT_MemInfo *mi = nrt->manage_memory(data, my_dtor);
644
+ nrt->acquire(mi);
645
+ nrt->release(mi);
646
+ status = 0xa110c;
647
+ return mi;
648
+ }
649
+ """
650
+ cdef = """
651
+ void* test_nrt_api(void *nrt);
652
+ extern int status;
653
+ """
654
+
655
+ ffi, mod = self.compile_cffi_module(name, source, cdef)
656
+ # Init status is 0
657
+ self.assertEqual(mod.lib.status, 0)
658
+ table = self.get_nrt_api_table()
659
+ out = mod.lib.test_nrt_api(table)
660
+ # status is now 0xa110c
661
+ self.assertEqual(mod.lib.status, 0xa110c)
662
+ mi_addr = int(ffi.cast("size_t", out))
663
+ mi = nrt.MemInfo(mi_addr)
664
+ self.assertEqual(mi.refcount, 1)
665
+ del mi # force deallocation on mi
666
+ # status is now 0xdead
667
+ self.assertEqual(mod.lib.status, 0xdead)
668
+
669
+ def test_allocate(self):
670
+ name = "{}_test_allocate".format(self.__class__.__name__)
671
+ source = r"""
672
+ #include <stdio.h>
673
+ #include "numba/core/runtime/nrt_external.h"
674
+
675
+ NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt, size_t n) {
676
+ size_t *data = NULL;
677
+ NRT_MemInfo *mi = nrt->allocate(n);
678
+ data = nrt->get_data(mi);
679
+ data[0] = 0xded;
680
+ data[1] = 0xabc;
681
+ data[2] = 0xdef;
682
+ return mi;
683
+ }
684
+ """
685
+ cdef = "void* test_nrt_api(void *nrt, size_t n);"
686
+ ffi, mod = self.compile_cffi_module(name, source, cdef)
687
+
688
+ table = self.get_nrt_api_table()
689
+
690
+ numbytes = 3 * np.dtype(np.intp).itemsize
691
+ out = mod.lib.test_nrt_api(table, numbytes)
692
+
693
+ mi_addr = int(ffi.cast("size_t", out))
694
+ mi = nrt.MemInfo(mi_addr)
695
+ self.assertEqual(mi.refcount, 1)
696
+
697
+ buffer = ffi.buffer(ffi.cast("char [{}]".format(numbytes), mi.data))
698
+ arr = np.ndarray(shape=(3,), dtype=np.intp, buffer=buffer)
699
+ np.testing.assert_equal(arr, [0xded, 0xabc, 0xdef])
700
+
701
+ def test_get_api(self):
702
+ from cffi import FFI
703
+
704
+ @njit
705
+ def test_nrt_api():
706
+ return NRT_get_api()
707
+
708
+ ffi = FFI()
709
+ expect = int(ffi.cast('size_t', self.get_nrt_api_table()))
710
+ got = test_nrt_api()
711
+ self.assertEqual(expect, got)
712
+
713
+
714
+ class TestNrtStatistics(TestCase):
715
+
716
+ def setUp(self):
717
+ # Store the current stats state
718
+ self.__stats_state = _nrt_python.memsys_stats_enabled()
719
+
720
+ def tearDown(self):
721
+ # Set stats state back to whatever it was before the test ran
722
+ if self.__stats_state:
723
+ _nrt_python.memsys_enable_stats()
724
+ else:
725
+ _nrt_python.memsys_disable_stats()
726
+
727
+ def test_stats_env_var_explicit_on(self):
728
+ # Checks that explicitly turning the stats on via the env var works.
729
+ src = """if 1:
730
+ from numba import njit
731
+ import numpy as np
732
+ from numba.core.runtime import rtsys, _nrt_python
733
+ from numba.core.registry import cpu_target
734
+
735
+ @njit
736
+ def foo():
737
+ return np.arange(10)[0]
738
+
739
+ # initialize the NRT before use
740
+ rtsys.initialize(cpu_target.target_context)
741
+ assert _nrt_python.memsys_stats_enabled()
742
+ orig_stats = rtsys.get_allocation_stats()
743
+ foo()
744
+ new_stats = rtsys.get_allocation_stats()
745
+ total_alloc = new_stats.alloc - orig_stats.alloc
746
+ total_free = new_stats.free - orig_stats.free
747
+ total_mi_alloc = new_stats.mi_alloc - orig_stats.mi_alloc
748
+ total_mi_free = new_stats.mi_free - orig_stats.mi_free
749
+
750
+ expected = 1
751
+ assert total_alloc == expected
752
+ assert total_free == expected
753
+ assert total_mi_alloc == expected
754
+ assert total_mi_free == expected
755
+ """
756
+ # Check env var explicitly being set works
757
+ env = os.environ.copy()
758
+ env['NUMBA_NRT_STATS'] = "1"
759
+ run_in_subprocess(src, env=env)
760
+
761
+ def check_env_var_off(self, env):
762
+
763
+ src = """if 1:
764
+ from numba import njit
765
+ import numpy as np
766
+ from numba.core.runtime import rtsys, _nrt_python
767
+
768
+ @njit
769
+ def foo():
770
+ return np.arange(10)[0]
771
+
772
+ assert _nrt_python.memsys_stats_enabled() == False
773
+ try:
774
+ rtsys.get_allocation_stats()
775
+ except RuntimeError as e:
776
+ assert "NRT stats are disabled." in str(e)
777
+ """
778
+ run_in_subprocess(src, env=env)
779
+
780
+ def test_stats_env_var_explicit_off(self):
781
+ # Checks that explicitly turning the stats off via the env var works.
782
+ env = os.environ.copy()
783
+ env['NUMBA_NRT_STATS'] = "0"
784
+ self.check_env_var_off(env)
785
+
786
+ def test_stats_env_var_default_off(self):
787
+ # Checks that the env var not being set is the same as "off", i.e.
788
+ # default for Numba is off.
789
+ env = os.environ.copy()
790
+ env.pop('NUMBA_NRT_STATS', None)
791
+ self.check_env_var_off(env)
792
+
793
+ def test_stats_status_toggle(self):
794
+
795
+ @njit
796
+ def foo():
797
+ tmp = np.ones(3)
798
+ return np.arange(5 * tmp[0])
799
+
800
+ # Switch on stats
801
+ _nrt_python.memsys_enable_stats()
802
+ # check the stats are on
803
+ self.assertTrue(_nrt_python.memsys_stats_enabled())
804
+
805
+ for i in range(2):
806
+ # capture the stats state
807
+ stats_1 = rtsys.get_allocation_stats()
808
+ # Switch off stats
809
+ _nrt_python.memsys_disable_stats()
810
+ # check the stats are off
811
+ self.assertFalse(_nrt_python.memsys_stats_enabled())
812
+ # run something that would move the counters were they enabled
813
+ foo()
814
+ # Switch on stats
815
+ _nrt_python.memsys_enable_stats()
816
+ # check the stats are on
817
+ self.assertTrue(_nrt_python.memsys_stats_enabled())
818
+ # capture the stats state (should not have changed)
819
+ stats_2 = rtsys.get_allocation_stats()
820
+ # run something that will move the counters
821
+ foo()
822
+ # capture the stats state (should have changed)
823
+ stats_3 = rtsys.get_allocation_stats()
824
+ # check stats_1 == stats_2
825
+ self.assertEqual(stats_1, stats_2)
826
+ # check stats_2 < stats_3
827
+ self.assertLess(stats_2, stats_3)
828
+
829
+ def test_rtsys_stats_query_raises_exception_when_disabled(self):
830
+ # Checks that the standard rtsys.get_allocation_stats() query raises
831
+ # when stats counters are turned off.
832
+
833
+ _nrt_python.memsys_disable_stats()
834
+ self.assertFalse(_nrt_python.memsys_stats_enabled())
835
+
836
+ with self.assertRaises(RuntimeError) as raises:
837
+ rtsys.get_allocation_stats()
838
+
839
+ self.assertIn("NRT stats are disabled.", str(raises.exception))
840
+
841
+ def test_nrt_explicit_stats_query_raises_exception_when_disabled(self):
842
+ # Checks the various memsys_get_stats functions raise if queried when
843
+ # the stats counters are disabled.
844
+ method_variations = ('alloc', 'free', 'mi_alloc', 'mi_free')
845
+ for meth in method_variations:
846
+ stats_func = getattr(_nrt_python, f'memsys_get_stats_{meth}')
847
+ with self.subTest(stats_func=stats_func):
848
+ # Turn stats off
849
+ _nrt_python.memsys_disable_stats()
850
+ self.assertFalse(_nrt_python.memsys_stats_enabled())
851
+ with self.assertRaises(RuntimeError) as raises:
852
+ stats_func()
853
+ self.assertIn("NRT stats are disabled.", str(raises.exception))
854
+
855
+
856
+ if __name__ == '__main__':
857
+ unittest.main()