Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +3 -0
- lib/python3.10/site-packages/av/container/output.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/av/container/streams.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/av/data/stream.cpython-310-x86_64-linux-gnu.so +3 -0
- lib/python3.10/site-packages/numba/tests/compile_with_pycc.py +134 -0
- lib/python3.10/site-packages/numba/tests/error_usecases.py +6 -0
- lib/python3.10/site-packages/numba/tests/errorhandling_usecases.py +14 -0
- lib/python3.10/site-packages/numba/tests/gdb_support.py +197 -0
- lib/python3.10/site-packages/numba/tests/inlining_usecases.py +69 -0
- lib/python3.10/site-packages/numba/tests/matmul_usecase.py +24 -0
- lib/python3.10/site-packages/numba/tests/orphaned_semaphore_usecase.py +24 -0
- lib/python3.10/site-packages/numba/tests/recursion_usecases.py +228 -0
- lib/python3.10/site-packages/numba/tests/test_array_attr.py +410 -0
- lib/python3.10/site-packages/numba/tests/test_array_iterators.py +555 -0
- lib/python3.10/site-packages/numba/tests/test_buffer_protocol.py +289 -0
- lib/python3.10/site-packages/numba/tests/test_builtins.py +1682 -0
- lib/python3.10/site-packages/numba/tests/test_cffi.py +189 -0
- lib/python3.10/site-packages/numba/tests/test_cgutils.py +152 -0
- lib/python3.10/site-packages/numba/tests/test_cli.py +281 -0
- lib/python3.10/site-packages/numba/tests/test_compiler_flags.py +119 -0
- lib/python3.10/site-packages/numba/tests/test_compiler_lock.py +23 -0
- lib/python3.10/site-packages/numba/tests/test_complex.py +309 -0
- lib/python3.10/site-packages/numba/tests/test_conversion.py +223 -0
- lib/python3.10/site-packages/numba/tests/test_datamodel.py +257 -0
- lib/python3.10/site-packages/numba/tests/test_debuginfo.py +759 -0
- lib/python3.10/site-packages/numba/tests/test_dictimpl.py +656 -0
- lib/python3.10/site-packages/numba/tests/test_dicts.py +233 -0
- lib/python3.10/site-packages/numba/tests/test_dyn_func.py +43 -0
- lib/python3.10/site-packages/numba/tests/test_enums.py +181 -0
- lib/python3.10/site-packages/numba/tests/test_errorhandling.py +469 -0
- lib/python3.10/site-packages/numba/tests/test_errormodels.py +28 -0
- lib/python3.10/site-packages/numba/tests/test_extending.py +2248 -0
- lib/python3.10/site-packages/numba/tests/test_extending_types.py +170 -0
- lib/python3.10/site-packages/numba/tests/test_findlib.py +12 -0
- lib/python3.10/site-packages/numba/tests/test_firstlinefinder.py +114 -0
- lib/python3.10/site-packages/numba/tests/test_flow_control.py +1280 -0
- lib/python3.10/site-packages/numba/tests/test_func_interface.py +43 -0
- lib/python3.10/site-packages/numba/tests/test_func_lifetime.py +164 -0
- lib/python3.10/site-packages/numba/tests/test_generators.py +661 -0
- lib/python3.10/site-packages/numba/tests/test_help.py +92 -0
- lib/python3.10/site-packages/numba/tests/test_interpreter.py +1154 -0
- lib/python3.10/site-packages/numba/tests/test_ir.py +560 -0
- lib/python3.10/site-packages/numba/tests/test_jit_module.py +146 -0
- lib/python3.10/site-packages/numba/tests/test_listobject.py +1652 -0
- lib/python3.10/site-packages/numba/tests/test_literal_dispatch.py +400 -0
- lib/python3.10/site-packages/numba/tests/test_looplifting.py +560 -0
- lib/python3.10/site-packages/numba/tests/test_mangling.py +41 -0
- lib/python3.10/site-packages/numba/tests/test_moved_modules.py +30 -0
- lib/python3.10/site-packages/numba/tests/test_multi3.py +43 -0
- lib/python3.10/site-packages/numba/tests/test_nan.py +37 -0
.gitattributes
CHANGED
|
@@ -86,3 +86,6 @@ lib/python3.10/site-packages/av/dictionary.cpython-310-x86_64-linux-gnu.so filte
|
|
| 86 |
lib/python3.10/site-packages/av/container/core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 87 |
lib/python3.10/site-packages/av/container/pyio.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 88 |
lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
lib/python3.10/site-packages/av/container/core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 87 |
lib/python3.10/site-packages/av/container/pyio.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 88 |
lib/python3.10/site-packages/av/container/input.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
|
lib/python3.10/site-packages/av/container/output.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3119d0482fe49241a5554cd873c307100ac476deaa889b84f41bd286f6b1b959
|
| 3 |
+
size 966769
|
lib/python3.10/site-packages/av/container/streams.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3cfb5c1f6899c522e91d4134d42cae6c02ecc41980ae81b838e8ac80fc121478
|
| 3 |
+
size 835265
|
lib/python3.10/site-packages/av/data/stream.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:236c39dfb44f94888f4273a010a82b8608396a3ebb762ed4001f95d92f89d3a6
|
| 3 |
+
size 363729
|
lib/python3.10/site-packages/numba/tests/compile_with_pycc.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cmath
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from numba import float32
|
| 6 |
+
from numba.types import unicode_type, i8
|
| 7 |
+
from numba.pycc import CC, exportmany, export
|
| 8 |
+
from numba.tests.support import has_blas
|
| 9 |
+
from numba import typed
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
#
|
| 13 |
+
# New API
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
cc = CC('pycc_test_simple')
|
| 17 |
+
cc.use_nrt = False
|
| 18 |
+
|
| 19 |
+
# Note the first signature omits the return type
|
| 20 |
+
@cc.export('multf', (float32, float32))
|
| 21 |
+
@cc.export('multi', 'i4(i4, i4)')
|
| 22 |
+
def mult(a, b):
|
| 23 |
+
return a * b
|
| 24 |
+
|
| 25 |
+
# Test imported C globals such as Py_None, PyExc_ZeroDivisionError
|
| 26 |
+
@cc.export('get_none', 'none()')
|
| 27 |
+
def get_none():
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
@cc.export('div', 'f8(f8, f8)')
|
| 31 |
+
def div(x, y):
|
| 32 |
+
return x / y
|
| 33 |
+
|
| 34 |
+
_two = 2
|
| 35 |
+
|
| 36 |
+
# This one can't be compiled by the legacy API as it doesn't execute
|
| 37 |
+
# the script in a proper module.
|
| 38 |
+
@cc.export('square', 'i8(i8)')
|
| 39 |
+
def square(u):
|
| 40 |
+
return u ** _two
|
| 41 |
+
|
| 42 |
+
# These ones need helperlib
|
| 43 |
+
cc_helperlib = CC('pycc_test_helperlib')
|
| 44 |
+
cc_helperlib.use_nrt = False
|
| 45 |
+
|
| 46 |
+
@cc_helperlib.export('power', 'i8(i8, i8)')
|
| 47 |
+
def power(u, v):
|
| 48 |
+
return u ** v
|
| 49 |
+
|
| 50 |
+
@cc_helperlib.export('sqrt', 'c16(c16)')
|
| 51 |
+
def sqrt(u):
|
| 52 |
+
return cmath.sqrt(u)
|
| 53 |
+
|
| 54 |
+
@cc_helperlib.export('size', 'i8(f8[:])')
|
| 55 |
+
def size(arr):
|
| 56 |
+
return arr.size
|
| 57 |
+
|
| 58 |
+
# Exercise linking to Numpy math functions
|
| 59 |
+
@cc_helperlib.export('np_sqrt', 'f8(f8)')
|
| 60 |
+
def np_sqrt(u):
|
| 61 |
+
return np.sqrt(u)
|
| 62 |
+
|
| 63 |
+
@cc_helperlib.export('spacing', 'f8(f8)')
|
| 64 |
+
def np_spacing(u):
|
| 65 |
+
return np.spacing(u)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# This one clashes with libc random() unless pycc is careful with naming.
|
| 69 |
+
@cc_helperlib.export('random', 'f8(i4)')
|
| 70 |
+
def random_impl(seed):
|
| 71 |
+
if seed != -1:
|
| 72 |
+
np.random.seed(seed)
|
| 73 |
+
return np.random.random()
|
| 74 |
+
|
| 75 |
+
# These ones need NRT
|
| 76 |
+
cc_nrt = CC('pycc_test_nrt')
|
| 77 |
+
|
| 78 |
+
@cc_nrt.export('zero_scalar', 'f8(i4)')
|
| 79 |
+
def zero_scalar(n):
|
| 80 |
+
arr = np.zeros(n)
|
| 81 |
+
return arr[-1]
|
| 82 |
+
|
| 83 |
+
if has_blas:
|
| 84 |
+
# This one also needs BLAS
|
| 85 |
+
@cc_nrt.export('vector_dot', 'f8(i4)')
|
| 86 |
+
def vector_dot(n):
|
| 87 |
+
a = np.linspace(1, n, n)
|
| 88 |
+
return np.dot(a, a)
|
| 89 |
+
|
| 90 |
+
# This one needs an environment
|
| 91 |
+
@cc_nrt.export('zeros', 'f8[:](i4)')
|
| 92 |
+
def zeros(n):
|
| 93 |
+
return np.zeros(n)
|
| 94 |
+
|
| 95 |
+
# requires list dtor, #issue3535
|
| 96 |
+
@cc_nrt.export('np_argsort', 'intp[:](float64[:])')
|
| 97 |
+
def np_argsort(arr):
|
| 98 |
+
return np.argsort(arr)
|
| 99 |
+
|
| 100 |
+
#
|
| 101 |
+
# Legacy API
|
| 102 |
+
#
|
| 103 |
+
|
| 104 |
+
exportmany(['multf f4(f4,f4)', 'multi i4(i4,i4)'])(mult)
|
| 105 |
+
# Needs to link to helperlib to due with complex arguments
|
| 106 |
+
# export('multc c16(c16,c16)')(mult)
|
| 107 |
+
export('mult f8(f8, f8)')(mult)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@cc_nrt.export('dict_usecase', 'intp[:](intp[:])')
|
| 111 |
+
def dict_usecase(arr):
|
| 112 |
+
d = typed.Dict()
|
| 113 |
+
for i in range(arr.size):
|
| 114 |
+
d[i] = arr[i]
|
| 115 |
+
out = np.zeros_like(arr)
|
| 116 |
+
for k, v in d.items():
|
| 117 |
+
out[k] = k * v
|
| 118 |
+
return out
|
| 119 |
+
|
| 120 |
+
# checks for issue #6386
|
| 121 |
+
@cc_nrt.export('internal_str_dict', i8(unicode_type))
|
| 122 |
+
def internal_str_dict(x):
|
| 123 |
+
d = typed.Dict.empty(unicode_type,i8)
|
| 124 |
+
if(x not in d):
|
| 125 |
+
d[x] = len(d)
|
| 126 |
+
return len(d)
|
| 127 |
+
|
| 128 |
+
@cc_nrt.export('hash_str', i8(unicode_type))
|
| 129 |
+
def internal_str_dict(x):
|
| 130 |
+
return hash(x)
|
| 131 |
+
|
| 132 |
+
@cc_nrt.export('hash_literal_str_A', i8())
|
| 133 |
+
def internal_str_dict():
|
| 134 |
+
return hash("A")
|
lib/python3.10/site-packages/numba/tests/error_usecases.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numba as nb
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@nb.jit(nopython=True, parallel=True)
|
| 5 |
+
def foo():
|
| 6 |
+
pass
|
lib/python3.10/site-packages/numba/tests/errorhandling_usecases.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numba import typed, int64
|
| 2 |
+
|
| 3 |
+
# used in TestMiscErrorHandling::test_handling_of_write_to_*_global
|
| 4 |
+
_global_list = [1, 2, 3, 4]
|
| 5 |
+
|
| 6 |
+
_global_dict = typed.Dict.empty(int64, int64)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def global_reflected_write():
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helpers for running gdb related testing"""
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
from numba.core import config
|
| 7 |
+
from numba.misc.gdb_hook import _confirm_gdb
|
| 8 |
+
from numba.misc.numba_gdbinfo import collect_gdbinfo
|
| 9 |
+
|
| 10 |
+
# check if gdb is present and working
|
| 11 |
+
try:
|
| 12 |
+
_confirm_gdb(need_ptrace_attach=False) # The driver launches as `gdb EXE`.
|
| 13 |
+
_HAVE_GDB = True
|
| 14 |
+
_gdb_info = collect_gdbinfo()
|
| 15 |
+
_GDB_HAS_PY3 = _gdb_info.py_ver.startswith('3')
|
| 16 |
+
except Exception:
|
| 17 |
+
_HAVE_GDB = False
|
| 18 |
+
_GDB_HAS_PY3 = False
|
| 19 |
+
|
| 20 |
+
_msg = "functioning gdb with correct ptrace permissions is required"
|
| 21 |
+
needs_gdb = unittest.skipUnless(_HAVE_GDB, _msg)
|
| 22 |
+
|
| 23 |
+
_msg = "gdb with python 3 support needed"
|
| 24 |
+
needs_gdb_py3 = unittest.skipUnless(_GDB_HAS_PY3, _msg)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
import pexpect
|
| 29 |
+
_HAVE_PEXPECT = True
|
| 30 |
+
except ImportError:
|
| 31 |
+
_HAVE_PEXPECT = False
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_msg = "pexpect module needed for test"
|
| 35 |
+
skip_unless_pexpect = unittest.skipUnless(_HAVE_PEXPECT, _msg)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GdbMIDriver(object):
|
| 39 |
+
"""
|
| 40 |
+
Driver class for the GDB machine interface:
|
| 41 |
+
https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html
|
| 42 |
+
"""
|
| 43 |
+
def __init__(self, file_name, debug=False, timeout=120, init_cmds=None):
|
| 44 |
+
if not _HAVE_PEXPECT:
|
| 45 |
+
msg = ("This driver requires the pexpect module. This can be "
|
| 46 |
+
"obtained via:\n\n$ conda install pexpect")
|
| 47 |
+
raise RuntimeError(msg)
|
| 48 |
+
if not _HAVE_GDB:
|
| 49 |
+
msg = ("This driver requires a gdb binary. This can be "
|
| 50 |
+
"obtained via the system package manager.")
|
| 51 |
+
raise RuntimeError(msg)
|
| 52 |
+
self._gdb_binary = config.GDB_BINARY
|
| 53 |
+
self._python = sys.executable
|
| 54 |
+
self._debug = debug
|
| 55 |
+
self._file_name = file_name
|
| 56 |
+
self._timeout = timeout
|
| 57 |
+
self._init_cmds = init_cmds
|
| 58 |
+
self._drive()
|
| 59 |
+
|
| 60 |
+
def _drive(self):
|
| 61 |
+
"""This function sets up the caputured gdb instance"""
|
| 62 |
+
assert os.path.isfile(self._file_name)
|
| 63 |
+
cmd = [self._gdb_binary, '--interpreter', 'mi']
|
| 64 |
+
if self._init_cmds is not None:
|
| 65 |
+
cmd += list(self._init_cmds)
|
| 66 |
+
cmd += ['--args', self._python, self._file_name]
|
| 67 |
+
self._captured = pexpect.spawn(' '.join(cmd))
|
| 68 |
+
if self._debug:
|
| 69 |
+
self._captured.logfile = sys.stdout.buffer
|
| 70 |
+
|
| 71 |
+
def supports_python(self):
|
| 72 |
+
"""Returns True if the underlying gdb implementation has python support
|
| 73 |
+
False otherwise"""
|
| 74 |
+
return "python" in self.list_features()
|
| 75 |
+
|
| 76 |
+
def supports_numpy(self):
|
| 77 |
+
"""Returns True if the underlying gdb implementation has NumPy support
|
| 78 |
+
(and by extension Python support) False otherwise"""
|
| 79 |
+
if not self.supports_python():
|
| 80 |
+
return False
|
| 81 |
+
# Some gdb's have python 2!
|
| 82 |
+
cmd = ('python from __future__ import print_function;'
|
| 83 |
+
'import numpy; print(numpy)')
|
| 84 |
+
self.interpreter_exec('console', cmd)
|
| 85 |
+
return "module \'numpy\' from" in self._captured.before.decode()
|
| 86 |
+
|
| 87 |
+
def _captured_expect(self, expect):
|
| 88 |
+
try:
|
| 89 |
+
self._captured.expect(expect, timeout=self._timeout)
|
| 90 |
+
except pexpect.exceptions.TIMEOUT as e:
|
| 91 |
+
msg = f"Expected value did not arrive: {expect}."
|
| 92 |
+
raise ValueError(msg) from e
|
| 93 |
+
|
| 94 |
+
def assert_output(self, expected):
|
| 95 |
+
"""Asserts that the current output string contains the expected."""
|
| 96 |
+
output = self._captured.after
|
| 97 |
+
decoded = output.decode('utf-8')
|
| 98 |
+
assert expected in decoded, f'decoded={decoded}\nexpected={expected})'
|
| 99 |
+
|
| 100 |
+
def assert_regex_output(self, expected):
|
| 101 |
+
"""Asserts that the current output string contains the expected
|
| 102 |
+
regex."""
|
| 103 |
+
output = self._captured.after
|
| 104 |
+
decoded = output.decode('utf-8')
|
| 105 |
+
done_str = decoded.splitlines()[0]
|
| 106 |
+
found = re.match(expected, done_str)
|
| 107 |
+
assert found, f'decoded={decoded}\nexpected={expected})'
|
| 108 |
+
|
| 109 |
+
def _run_command(self, command, expect=''):
|
| 110 |
+
self._captured.sendline(command)
|
| 111 |
+
self._captured_expect(expect)
|
| 112 |
+
|
| 113 |
+
def run(self):
|
| 114 |
+
"""gdb command ~= 'run'"""
|
| 115 |
+
self._run_command('-exec-run', expect=r'\^running.*\r\n')
|
| 116 |
+
|
| 117 |
+
def cont(self):
|
| 118 |
+
"""gdb command ~= 'continue'"""
|
| 119 |
+
self._run_command('-exec-continue', expect=r'\^running.*\r\n')
|
| 120 |
+
|
| 121 |
+
def quit(self):
|
| 122 |
+
"""gdb command ~= 'quit'"""
|
| 123 |
+
self._run_command('-gdb-exit', expect=r'-gdb-exit')
|
| 124 |
+
self._captured.terminate()
|
| 125 |
+
|
| 126 |
+
def next(self):
|
| 127 |
+
"""gdb command ~= 'next'"""
|
| 128 |
+
self._run_command('-exec-next', expect=r'\*stopped,.*\r\n')
|
| 129 |
+
|
| 130 |
+
def step(self):
|
| 131 |
+
"""gdb command ~= 'step'"""
|
| 132 |
+
self._run_command('-exec-step', expect=r'\*stopped,.*\r\n')
|
| 133 |
+
|
| 134 |
+
def set_breakpoint(self, line=None, symbol=None, condition=None):
|
| 135 |
+
"""gdb command ~= 'break'"""
|
| 136 |
+
if line is not None and symbol is not None:
|
| 137 |
+
raise ValueError("Can only supply one of line or symbol")
|
| 138 |
+
bp = '-break-insert '
|
| 139 |
+
if condition is not None:
|
| 140 |
+
bp += f'-c "{condition}" '
|
| 141 |
+
if line is not None:
|
| 142 |
+
assert isinstance(line, int)
|
| 143 |
+
bp += f'-f {self._file_name}:{line} '
|
| 144 |
+
if symbol is not None:
|
| 145 |
+
assert isinstance(symbol, str)
|
| 146 |
+
bp += f'-f {symbol} '
|
| 147 |
+
self._run_command(bp, expect=r'\^done')
|
| 148 |
+
|
| 149 |
+
def check_hit_breakpoint(self, number=None, line=None):
|
| 150 |
+
"""Checks that a breakpoint has been hit"""
|
| 151 |
+
self._captured_expect(r'\*stopped,.*\r\n')
|
| 152 |
+
self.assert_output('*stopped,reason="breakpoint-hit",')
|
| 153 |
+
if number is not None:
|
| 154 |
+
assert isinstance(number, int)
|
| 155 |
+
self.assert_output(f'bkptno="{number}"')
|
| 156 |
+
if line is not None:
|
| 157 |
+
assert isinstance(line, int)
|
| 158 |
+
self.assert_output(f'line="{line}"')
|
| 159 |
+
|
| 160 |
+
def stack_list_arguments(self, print_values=1, low_frame=0, high_frame=0):
|
| 161 |
+
"""gdb command ~= 'info args'"""
|
| 162 |
+
for x in (print_values, low_frame, high_frame):
|
| 163 |
+
assert isinstance(x, int) and x in (0, 1, 2)
|
| 164 |
+
cmd = f'-stack-list-arguments {print_values} {low_frame} {high_frame}'
|
| 165 |
+
self._run_command(cmd, expect=r'\^done,.*\r\n')
|
| 166 |
+
|
| 167 |
+
def stack_list_variables(self, print_values=1):
|
| 168 |
+
"""gdb command ~= 'info locals'"""
|
| 169 |
+
assert isinstance(print_values, int) and print_values in (0, 1, 2)
|
| 170 |
+
cmd = f'-stack-list-variables {print_values}'
|
| 171 |
+
self._run_command(cmd, expect=r'\^done,.*\r\n')
|
| 172 |
+
|
| 173 |
+
def interpreter_exec(self, interpreter=None, command=None):
|
| 174 |
+
"""gdb command ~= 'interpreter-exec'"""
|
| 175 |
+
if interpreter is None:
|
| 176 |
+
raise ValueError("interpreter cannot be None")
|
| 177 |
+
if command is None:
|
| 178 |
+
raise ValueError("command cannot be None")
|
| 179 |
+
cmd = f'-interpreter-exec {interpreter} "{command}"'
|
| 180 |
+
self._run_command(cmd, expect=r'\^(done|error).*\r\n') # NOTE no `,`
|
| 181 |
+
|
| 182 |
+
def _list_features_raw(self):
|
| 183 |
+
cmd = '-list-features'
|
| 184 |
+
self._run_command(cmd, expect=r'\^done,.*\r\n')
|
| 185 |
+
|
| 186 |
+
def list_features(self):
|
| 187 |
+
"""No equivalent gdb command? Returns a list of supported gdb
|
| 188 |
+
features.
|
| 189 |
+
"""
|
| 190 |
+
self._list_features_raw()
|
| 191 |
+
output = self._captured.after
|
| 192 |
+
decoded = output.decode('utf-8')
|
| 193 |
+
m = re.match('.*features=\\[(.*)\\].*', decoded)
|
| 194 |
+
assert m is not None, "No match found for features string"
|
| 195 |
+
g = m.groups()
|
| 196 |
+
assert len(g) == 1, "Invalid number of match groups found"
|
| 197 |
+
return g[0].replace('"', '').split(',')
|
lib/python3.10/site-packages/numba/tests/inlining_usecases.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Test cases for inlining IR from another module """
|
| 2 |
+
from numba import jit, njit
|
| 3 |
+
from numba.core import types
|
| 4 |
+
from numba.core.extending import overload
|
| 5 |
+
|
| 6 |
+
_GLOBAL1 = 100
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@njit(inline='always')
|
| 10 |
+
def bar():
|
| 11 |
+
return _GLOBAL1 + 10
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def baz_factory(a):
|
| 15 |
+
b = 17 + a
|
| 16 |
+
|
| 17 |
+
@njit(inline='always')
|
| 18 |
+
def baz():
|
| 19 |
+
return _GLOBAL1 + a - b
|
| 20 |
+
return baz
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def baz():
|
| 24 |
+
return _GLOBAL1 + 10
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@overload(baz, inline='always')
|
| 28 |
+
def baz_ol():
|
| 29 |
+
def impl():
|
| 30 |
+
return _GLOBAL1 + 10
|
| 31 |
+
return impl
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def bop_factory(a):
|
| 35 |
+
b = 17 + a
|
| 36 |
+
|
| 37 |
+
def bop():
|
| 38 |
+
return _GLOBAL1 + a - b
|
| 39 |
+
|
| 40 |
+
@overload(bop, inline='always')
|
| 41 |
+
def baz():
|
| 42 |
+
def impl():
|
| 43 |
+
return _GLOBAL1 + a - b
|
| 44 |
+
return impl
|
| 45 |
+
|
| 46 |
+
return bop
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@jit((types.int32,), nopython=True)
|
| 50 |
+
def inner(a):
|
| 51 |
+
return a + 1
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@jit((types.int32,), nopython=True)
|
| 55 |
+
def more(a):
|
| 56 |
+
return inner(inner(a))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def outer_simple(a):
|
| 60 |
+
return inner(a) * 2
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def outer_multiple(a):
|
| 64 |
+
return inner(a) * more(a)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@njit
|
| 68 |
+
def __dummy__():
|
| 69 |
+
return
|
lib/python3.10/site-packages/numba/tests/matmul_usecase.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Use cases for testing matmul (@)
|
| 2 |
+
"""
|
| 3 |
+
def matmul_usecase(x, y):
|
| 4 |
+
return x @ y
|
| 5 |
+
|
| 6 |
+
def imatmul_usecase(x, y):
|
| 7 |
+
x @= y
|
| 8 |
+
return x
|
| 9 |
+
|
| 10 |
+
class DumbMatrix(object):
|
| 11 |
+
|
| 12 |
+
def __init__(self, value):
|
| 13 |
+
self.value = value
|
| 14 |
+
|
| 15 |
+
def __matmul__(self, other):
|
| 16 |
+
if isinstance(other, DumbMatrix):
|
| 17 |
+
return DumbMatrix(self.value * other.value)
|
| 18 |
+
return NotImplemented
|
| 19 |
+
|
| 20 |
+
def __imatmul__(self, other):
|
| 21 |
+
if isinstance(other, DumbMatrix):
|
| 22 |
+
self.value *= other.value
|
| 23 |
+
return self
|
| 24 |
+
return NotImplemented
|
lib/python3.10/site-packages/numba/tests/orphaned_semaphore_usecase.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# See issue: https://github.com/numba/numba/issues/4348
|
| 2 |
+
# this file must be run in isolation to replicate, test:
|
| 3 |
+
# numba.tests.test_parallel_backend.TestInitSafetyIssues.test_orphaned_semaphore
|
| 4 |
+
# does this to check semaphores are not leaking.
|
| 5 |
+
|
| 6 |
+
import multiprocessing as mp
|
| 7 |
+
|
| 8 |
+
import numba # noqa, deliberately unused, here to test import is safe
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def w():
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main():
|
| 16 |
+
ps = [mp.Process(target=w) for _ in range(4)]
|
| 17 |
+
[p.start() for p in ps]
|
| 18 |
+
[p.join() for p in ps]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == '__main__':
|
| 22 |
+
p = mp.get_context('spawn').Process(target=main)
|
| 23 |
+
p.start()
|
| 24 |
+
p.join()
|
lib/python3.10/site-packages/numba/tests/recursion_usecases.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Usecases of recursive functions.
|
| 3 |
+
|
| 4 |
+
Some functions are compiled at import time, hence a separate module.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from numba import jit
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@jit("i8(i8)", nopython=True)
|
| 11 |
+
def fib1(n):
|
| 12 |
+
if n < 2:
|
| 13 |
+
return n
|
| 14 |
+
# Note the second call uses a named argument
|
| 15 |
+
return fib1(n - 1) + fib1(n=n - 2)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def make_fib2():
|
| 19 |
+
@jit("i8(i8)", nopython=True)
|
| 20 |
+
def fib2(n):
|
| 21 |
+
if n < 2:
|
| 22 |
+
return n
|
| 23 |
+
return fib2(n - 1) + fib2(n=n - 2)
|
| 24 |
+
|
| 25 |
+
return fib2
|
| 26 |
+
|
| 27 |
+
fib2 = make_fib2()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def make_type_change_self(jit=lambda x: x):
|
| 31 |
+
@jit
|
| 32 |
+
def type_change_self(x, y):
|
| 33 |
+
if x > 1 and y > 0:
|
| 34 |
+
return x + type_change_self(x - y, y)
|
| 35 |
+
else:
|
| 36 |
+
return y
|
| 37 |
+
return type_change_self
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Implicit signature
|
| 41 |
+
@jit(nopython=True)
|
| 42 |
+
def fib3(n):
|
| 43 |
+
if n < 2:
|
| 44 |
+
return n
|
| 45 |
+
return fib3(n - 1) + fib3(n - 2)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Run-away self recursion
|
| 49 |
+
@jit(nopython=True)
|
| 50 |
+
def runaway_self(x):
|
| 51 |
+
return runaway_self(x)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@jit(nopython=True)
|
| 55 |
+
def raise_self(x):
|
| 56 |
+
if x == 1:
|
| 57 |
+
raise ValueError("raise_self")
|
| 58 |
+
elif x > 0:
|
| 59 |
+
return raise_self(x - 1)
|
| 60 |
+
else:
|
| 61 |
+
return 1
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Mutual recursion
|
| 65 |
+
@jit(nopython=True)
|
| 66 |
+
def outer_fac(n):
|
| 67 |
+
if n < 1:
|
| 68 |
+
return 1
|
| 69 |
+
return n * inner_fac(n - 1)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@jit(nopython=True)
|
| 73 |
+
def inner_fac(n):
|
| 74 |
+
if n < 1:
|
| 75 |
+
return 1
|
| 76 |
+
return n * outer_fac(n - 1)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Mutual recursion with different arg names
|
| 80 |
+
def make_mutual2(jit=lambda x: x):
|
| 81 |
+
@jit
|
| 82 |
+
def foo(x):
|
| 83 |
+
if x > 0:
|
| 84 |
+
return 2 * bar(z=1, y=x)
|
| 85 |
+
return 1 + x
|
| 86 |
+
|
| 87 |
+
@jit
|
| 88 |
+
def bar(y, z):
|
| 89 |
+
return foo(x=y - z)
|
| 90 |
+
|
| 91 |
+
return foo, bar
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# Mutual runaway recursion
|
| 95 |
+
|
| 96 |
+
@jit(nopython=True)
|
| 97 |
+
def runaway_mutual(x):
|
| 98 |
+
return runaway_mutual_inner(x)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@jit(nopython=True)
|
| 102 |
+
def runaway_mutual_inner(x):
|
| 103 |
+
return runaway_mutual(x)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# Mutual type changing recursion
|
| 107 |
+
|
| 108 |
+
def make_type_change_mutual(jit=lambda x: x):
|
| 109 |
+
@jit
|
| 110 |
+
def foo(x, y):
|
| 111 |
+
if x > 1 and y > 0:
|
| 112 |
+
# call bar first to exercise partial type inference.
|
| 113 |
+
# typeinferer suspended at the call to bar() and haven't determined
|
| 114 |
+
# the potential return type from the else-branch
|
| 115 |
+
return x + bar(x - y, y)
|
| 116 |
+
else:
|
| 117 |
+
return y
|
| 118 |
+
|
| 119 |
+
@jit
|
| 120 |
+
def bar(x, y):
|
| 121 |
+
if x > 1 and y > 0:
|
| 122 |
+
return x + foo(x - y, y)
|
| 123 |
+
else:
|
| 124 |
+
return y
|
| 125 |
+
|
| 126 |
+
return foo
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# Indirect mutual recursion
|
| 130 |
+
def make_four_level(jit=lambda x: x):
|
| 131 |
+
@jit
|
| 132 |
+
def first(x):
|
| 133 |
+
# The recursing call must have a path that is non-recursing.
|
| 134 |
+
if x > 0:
|
| 135 |
+
return second(x) * 2
|
| 136 |
+
else:
|
| 137 |
+
return 1
|
| 138 |
+
|
| 139 |
+
@jit
|
| 140 |
+
def second(x):
|
| 141 |
+
return third(x) * 3
|
| 142 |
+
|
| 143 |
+
@jit
|
| 144 |
+
def third(x):
|
| 145 |
+
return fourth(x) * 4
|
| 146 |
+
|
| 147 |
+
@jit
|
| 148 |
+
def fourth(x):
|
| 149 |
+
return first(x / 2 - 1)
|
| 150 |
+
|
| 151 |
+
return first
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def make_inner_error(jit=lambda x: x):
|
| 155 |
+
@jit
|
| 156 |
+
def outer(x):
|
| 157 |
+
if x > 0:
|
| 158 |
+
return inner(x)
|
| 159 |
+
|
| 160 |
+
else:
|
| 161 |
+
return 1
|
| 162 |
+
|
| 163 |
+
@jit
|
| 164 |
+
def inner(x):
|
| 165 |
+
if x > 0:
|
| 166 |
+
return outer(x - 1)
|
| 167 |
+
else:
|
| 168 |
+
# this branch is actually never executed
|
| 169 |
+
return error_fun(x)
|
| 170 |
+
|
| 171 |
+
@jit
|
| 172 |
+
def error_fun(x):
|
| 173 |
+
# to trigger an untyped attribute error
|
| 174 |
+
return x.ndim
|
| 175 |
+
|
| 176 |
+
return outer
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def make_raise_mutual(jit=lambda x: x):
|
| 180 |
+
@jit
|
| 181 |
+
def outer(x):
|
| 182 |
+
if x > 0:
|
| 183 |
+
return inner(x)
|
| 184 |
+
else:
|
| 185 |
+
return 1
|
| 186 |
+
|
| 187 |
+
@jit
|
| 188 |
+
def inner(x):
|
| 189 |
+
if x == 1:
|
| 190 |
+
raise ValueError('raise_mutual')
|
| 191 |
+
elif x > 0:
|
| 192 |
+
return outer(x - 1)
|
| 193 |
+
else:
|
| 194 |
+
return 1
|
| 195 |
+
|
| 196 |
+
return outer
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def make_optional_return_case(jit=lambda x: x):
|
| 200 |
+
@jit
|
| 201 |
+
def foo(x):
|
| 202 |
+
if x > 5:
|
| 203 |
+
return x - 1
|
| 204 |
+
else:
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
@jit
|
| 208 |
+
def bar(x):
|
| 209 |
+
out = foo(x)
|
| 210 |
+
if out is None:
|
| 211 |
+
return out
|
| 212 |
+
elif out < 8:
|
| 213 |
+
return out
|
| 214 |
+
else:
|
| 215 |
+
return x * bar(out)
|
| 216 |
+
|
| 217 |
+
return bar
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def make_growing_tuple_case(jit=lambda x: x):
|
| 221 |
+
# From issue #4387
|
| 222 |
+
@jit
|
| 223 |
+
def make_list(n):
|
| 224 |
+
if n <= 0:
|
| 225 |
+
return None
|
| 226 |
+
|
| 227 |
+
return (n, make_list(n - 1))
|
| 228 |
+
return make_list
|
lib/python3.10/site-packages/numba/tests/test_array_attr.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from numba.np.numpy_support import from_dtype
|
| 5 |
+
from numba import njit, typeof
|
| 6 |
+
from numba.core import types
|
| 7 |
+
from numba.tests.support import (TestCase, MemoryLeakMixin,
|
| 8 |
+
skip_parfors_unsupported)
|
| 9 |
+
from numba.core.errors import TypingError
|
| 10 |
+
from numba.experimental import jitclass
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def array_dtype(a):
|
| 14 |
+
return a.dtype
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def use_dtype(a, b):
|
| 18 |
+
return a.view(b.dtype)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def dtype_eq_int64(a):
|
| 22 |
+
return a.dtype == np.dtype('int64')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def array_itemsize(a):
|
| 26 |
+
return a.itemsize
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def array_nbytes(a):
|
| 30 |
+
return a.nbytes
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def array_shape(a, i):
|
| 34 |
+
return a.shape[i]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def array_strides(a, i):
|
| 38 |
+
return a.strides[i]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def array_ndim(a):
|
| 42 |
+
return a.ndim
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def array_size(a):
|
| 46 |
+
return a.size
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def array_flags_contiguous(a):
|
| 50 |
+
return a.flags.contiguous
|
| 51 |
+
|
| 52 |
+
def array_flags_c_contiguous(a):
|
| 53 |
+
return a.flags.c_contiguous
|
| 54 |
+
|
| 55 |
+
def array_flags_f_contiguous(a):
|
| 56 |
+
return a.flags.f_contiguous
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def nested_array_itemsize(a):
|
| 60 |
+
return a.f.itemsize
|
| 61 |
+
|
| 62 |
+
def nested_array_nbytes(a):
|
| 63 |
+
return a.f.nbytes
|
| 64 |
+
|
| 65 |
+
def nested_array_shape(a):
|
| 66 |
+
return a.f.shape
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def nested_array_strides(a):
|
| 70 |
+
return a.f.strides
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def nested_array_ndim(a):
|
| 74 |
+
return a.f.ndim
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def nested_array_size(a):
|
| 78 |
+
return a.f.size
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def size_after_slicing_usecase(buf, i):
|
| 82 |
+
sliced = buf[i]
|
| 83 |
+
# Make sure size attribute is not lost
|
| 84 |
+
return sliced.size
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def array_ctypes_data(arr):
|
| 88 |
+
return arr.ctypes.data
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def array_real(arr):
|
| 92 |
+
return arr.real
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def array_imag(arr):
|
| 96 |
+
return arr.imag
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class TestArrayAttr(MemoryLeakMixin, TestCase):
|
| 100 |
+
|
| 101 |
+
def setUp(self):
|
| 102 |
+
super(TestArrayAttr, self).setUp()
|
| 103 |
+
self.a = np.arange(20, dtype=np.int32).reshape(4, 5)
|
| 104 |
+
|
| 105 |
+
def check_unary(self, pyfunc, arr):
|
| 106 |
+
aryty = typeof(arr)
|
| 107 |
+
cfunc = self.get_cfunc(pyfunc, (aryty,))
|
| 108 |
+
expected = pyfunc(arr)
|
| 109 |
+
self.assertPreciseEqual(cfunc(arr), expected)
|
| 110 |
+
# Retry with forced any layout
|
| 111 |
+
cfunc = self.get_cfunc(pyfunc, (aryty.copy(layout='A'),))
|
| 112 |
+
self.assertPreciseEqual(cfunc(arr), expected)
|
| 113 |
+
|
| 114 |
+
def check_unary_with_arrays(self, pyfunc,):
|
| 115 |
+
self.check_unary(pyfunc, self.a)
|
| 116 |
+
self.check_unary(pyfunc, self.a.T)
|
| 117 |
+
self.check_unary(pyfunc, self.a[::2])
|
| 118 |
+
# 0-d array
|
| 119 |
+
arr = np.array([42]).reshape(())
|
| 120 |
+
self.check_unary(pyfunc, arr)
|
| 121 |
+
# array with an empty dimension
|
| 122 |
+
arr = np.zeros(0)
|
| 123 |
+
self.check_unary(pyfunc, arr)
|
| 124 |
+
|
| 125 |
+
# check with reshape
|
| 126 |
+
self.check_unary(pyfunc, arr.reshape((1, 0, 2)))
|
| 127 |
+
|
| 128 |
+
def get_cfunc(self, pyfunc, argspec):
|
| 129 |
+
return njit(argspec)(pyfunc)
|
| 130 |
+
|
| 131 |
+
def test_shape(self):
|
| 132 |
+
pyfunc = array_shape
|
| 133 |
+
cfunc = self.get_cfunc(pyfunc, (types.int32[:,:], types.int32))
|
| 134 |
+
|
| 135 |
+
for i in range(self.a.ndim):
|
| 136 |
+
self.assertEqual(pyfunc(self.a, i), cfunc(self.a, i))
|
| 137 |
+
|
| 138 |
+
def test_strides(self):
|
| 139 |
+
pyfunc = array_strides
|
| 140 |
+
cfunc = self.get_cfunc(pyfunc, (types.int32[:,:], types.int32))
|
| 141 |
+
|
| 142 |
+
for i in range(self.a.ndim):
|
| 143 |
+
self.assertEqual(pyfunc(self.a, i), cfunc(self.a, i))
|
| 144 |
+
|
| 145 |
+
def test_ndim(self):
|
| 146 |
+
self.check_unary_with_arrays(array_ndim)
|
| 147 |
+
|
| 148 |
+
def test_size(self):
|
| 149 |
+
self.check_unary_with_arrays(array_size)
|
| 150 |
+
|
| 151 |
+
def test_itemsize(self):
|
| 152 |
+
self.check_unary_with_arrays(array_itemsize)
|
| 153 |
+
|
| 154 |
+
def test_nbytes(self):
|
| 155 |
+
self.check_unary_with_arrays(array_nbytes)
|
| 156 |
+
|
| 157 |
+
def test_dtype(self):
|
| 158 |
+
pyfunc = array_dtype
|
| 159 |
+
self.check_unary(pyfunc, self.a)
|
| 160 |
+
dtype = np.dtype([('x', np.int8), ('y', np.int8)])
|
| 161 |
+
arr = np.zeros(4, dtype=dtype)
|
| 162 |
+
self.check_unary(pyfunc, arr)
|
| 163 |
+
|
| 164 |
+
def test_use_dtype(self):
|
| 165 |
+
# Test using the dtype attribute inside the Numba function itself
|
| 166 |
+
b = np.empty(1, dtype=np.int16)
|
| 167 |
+
pyfunc = use_dtype
|
| 168 |
+
cfunc = self.get_cfunc(pyfunc, (typeof(self.a), typeof(b)))
|
| 169 |
+
expected = pyfunc(self.a, b)
|
| 170 |
+
self.assertPreciseEqual(cfunc(self.a, b), expected)
|
| 171 |
+
|
| 172 |
+
def test_dtype_equal(self):
|
| 173 |
+
# Test checking if a dtype is equal to another dtype
|
| 174 |
+
pyfunc = dtype_eq_int64
|
| 175 |
+
self.check_unary(pyfunc, np.empty(1, dtype=np.int16))
|
| 176 |
+
self.check_unary(pyfunc, np.empty(1, dtype=np.int64))
|
| 177 |
+
|
| 178 |
+
def test_flags_contiguous(self):
|
| 179 |
+
self.check_unary_with_arrays(array_flags_contiguous)
|
| 180 |
+
|
| 181 |
+
def test_flags_c_contiguous(self):
|
| 182 |
+
self.check_unary_with_arrays(array_flags_c_contiguous)
|
| 183 |
+
|
| 184 |
+
def test_flags_f_contiguous(self):
|
| 185 |
+
self.check_unary_with_arrays(array_flags_f_contiguous)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class TestNestedArrayAttr(MemoryLeakMixin, unittest.TestCase):
|
| 189 |
+
def setUp(self):
|
| 190 |
+
super(TestNestedArrayAttr, self).setUp()
|
| 191 |
+
dtype = np.dtype([('a', np.int32), ('f', np.int32, (2, 5))])
|
| 192 |
+
self.a = np.recarray(1, dtype)[0]
|
| 193 |
+
self.nbrecord = from_dtype(self.a.dtype)
|
| 194 |
+
|
| 195 |
+
def get_cfunc(self, pyfunc):
|
| 196 |
+
return njit((self.nbrecord,))(pyfunc)
|
| 197 |
+
|
| 198 |
+
def test_shape(self):
|
| 199 |
+
pyfunc = nested_array_shape
|
| 200 |
+
cfunc = self.get_cfunc(pyfunc)
|
| 201 |
+
|
| 202 |
+
self.assertEqual(pyfunc(self.a), cfunc(self.a))
|
| 203 |
+
|
| 204 |
+
def test_strides(self):
|
| 205 |
+
pyfunc = nested_array_strides
|
| 206 |
+
cfunc = self.get_cfunc(pyfunc)
|
| 207 |
+
|
| 208 |
+
self.assertEqual(pyfunc(self.a), cfunc(self.a))
|
| 209 |
+
|
| 210 |
+
def test_ndim(self):
|
| 211 |
+
pyfunc = nested_array_ndim
|
| 212 |
+
cfunc = self.get_cfunc(pyfunc)
|
| 213 |
+
|
| 214 |
+
self.assertEqual(pyfunc(self.a), cfunc(self.a))
|
| 215 |
+
|
| 216 |
+
def test_nbytes(self):
|
| 217 |
+
pyfunc = nested_array_nbytes
|
| 218 |
+
cfunc = self.get_cfunc(pyfunc)
|
| 219 |
+
|
| 220 |
+
self.assertEqual(pyfunc(self.a), cfunc(self.a))
|
| 221 |
+
|
| 222 |
+
def test_size(self):
|
| 223 |
+
pyfunc = nested_array_size
|
| 224 |
+
cfunc = self.get_cfunc(pyfunc)
|
| 225 |
+
|
| 226 |
+
self.assertEqual(pyfunc(self.a), cfunc(self.a))
|
| 227 |
+
|
| 228 |
+
def test_itemsize(self):
|
| 229 |
+
pyfunc = nested_array_itemsize
|
| 230 |
+
cfunc = self.get_cfunc(pyfunc)
|
| 231 |
+
|
| 232 |
+
self.assertEqual(pyfunc(self.a), cfunc(self.a))
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class TestSlicedArrayAttr(MemoryLeakMixin, unittest.TestCase):
|
| 236 |
+
def test_size_after_slicing(self):
|
| 237 |
+
pyfunc = size_after_slicing_usecase
|
| 238 |
+
cfunc = njit(pyfunc)
|
| 239 |
+
arr = np.arange(2 * 5).reshape(2, 5)
|
| 240 |
+
for i in range(arr.shape[0]):
|
| 241 |
+
self.assertEqual(pyfunc(arr, i), cfunc(arr, i))
|
| 242 |
+
arr = np.arange(2 * 5 * 3).reshape(2, 5, 3)
|
| 243 |
+
for i in range(arr.shape[0]):
|
| 244 |
+
self.assertEqual(pyfunc(arr, i), cfunc(arr, i))
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class TestArrayCTypes(MemoryLeakMixin, TestCase):
|
| 248 |
+
|
| 249 |
+
_numba_parallel_test_ = False
|
| 250 |
+
|
| 251 |
+
def test_array_ctypes_data(self):
|
| 252 |
+
pyfunc = array_ctypes_data
|
| 253 |
+
cfunc = njit(pyfunc)
|
| 254 |
+
arr = np.arange(3)
|
| 255 |
+
self.assertEqual(pyfunc(arr), cfunc(arr))
|
| 256 |
+
|
| 257 |
+
@skip_parfors_unsupported
|
| 258 |
+
def test_array_ctypes_ref_error_in_parallel(self):
|
| 259 |
+
# Issue #2887
|
| 260 |
+
from ctypes import CFUNCTYPE, c_void_p, c_int32, c_double, c_bool
|
| 261 |
+
|
| 262 |
+
@CFUNCTYPE(c_bool, c_void_p, c_int32, c_void_p)
|
| 263 |
+
def callback(inptr, size, outptr):
|
| 264 |
+
# A ctypes callback that manipulate the incoming pointers.
|
| 265 |
+
try:
|
| 266 |
+
inbuf = (c_double * size).from_address(inptr)
|
| 267 |
+
outbuf = (c_double * 1).from_address(outptr)
|
| 268 |
+
a = np.ndarray(size, buffer=inbuf, dtype=np.float64)
|
| 269 |
+
b = np.ndarray(1, buffer=outbuf, dtype=np.float64)
|
| 270 |
+
b[0] = (a + a.size)[0]
|
| 271 |
+
return True
|
| 272 |
+
except:
|
| 273 |
+
import traceback
|
| 274 |
+
traceback.print_exception()
|
| 275 |
+
return False
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
# parallel=True is required to reproduce the error.
|
| 279 |
+
@njit(parallel=True)
|
| 280 |
+
def foo(size):
|
| 281 |
+
arr = np.ones(size)
|
| 282 |
+
out = np.empty(1)
|
| 283 |
+
# Exercise array.ctypes
|
| 284 |
+
inct = arr.ctypes
|
| 285 |
+
outct = out.ctypes
|
| 286 |
+
# The reference to `arr` is dead by now
|
| 287 |
+
status = callback(inct.data, size, outct.data)
|
| 288 |
+
return status, out[0]
|
| 289 |
+
|
| 290 |
+
size = 3
|
| 291 |
+
status, got = foo(size)
|
| 292 |
+
self.assertTrue(status)
|
| 293 |
+
self.assertPreciseEqual(got, (np.ones(size) + size)[0])
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class TestRealImagAttr(MemoryLeakMixin, TestCase):
|
| 297 |
+
def check_complex(self, pyfunc):
|
| 298 |
+
cfunc = njit(pyfunc)
|
| 299 |
+
# test 1D
|
| 300 |
+
size = 10
|
| 301 |
+
arr = np.arange(size) + np.arange(size) * 10j
|
| 302 |
+
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
|
| 303 |
+
# test 2D
|
| 304 |
+
arr = arr.reshape(2, 5)
|
| 305 |
+
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
|
| 306 |
+
|
| 307 |
+
def test_complex_real(self):
|
| 308 |
+
self.check_complex(array_real)
|
| 309 |
+
|
| 310 |
+
def test_complex_imag(self):
|
| 311 |
+
self.check_complex(array_imag)
|
| 312 |
+
|
| 313 |
+
def check_number_real(self, dtype):
|
| 314 |
+
pyfunc = array_real
|
| 315 |
+
cfunc = njit(pyfunc)
|
| 316 |
+
# test 1D
|
| 317 |
+
size = 10
|
| 318 |
+
arr = np.arange(size, dtype=dtype)
|
| 319 |
+
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
|
| 320 |
+
# test 2D
|
| 321 |
+
arr = arr.reshape(2, 5)
|
| 322 |
+
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
|
| 323 |
+
# test identity
|
| 324 |
+
self.assertEqual(arr.data, pyfunc(arr).data)
|
| 325 |
+
self.assertEqual(arr.data, cfunc(arr).data)
|
| 326 |
+
# test writable
|
| 327 |
+
real = cfunc(arr)
|
| 328 |
+
self.assertNotEqual(arr[0, 0], 5)
|
| 329 |
+
real[0, 0] = 5
|
| 330 |
+
self.assertEqual(arr[0, 0], 5)
|
| 331 |
+
|
| 332 |
+
def test_number_real(self):
|
| 333 |
+
"""
|
| 334 |
+
Testing .real of non-complex dtypes
|
| 335 |
+
"""
|
| 336 |
+
for dtype in [np.uint8, np.int32, np.float32, np.float64]:
|
| 337 |
+
self.check_number_real(dtype)
|
| 338 |
+
|
| 339 |
+
def check_number_imag(self, dtype):
|
| 340 |
+
pyfunc = array_imag
|
| 341 |
+
cfunc = njit(pyfunc)
|
| 342 |
+
# test 1D
|
| 343 |
+
size = 10
|
| 344 |
+
arr = np.arange(size, dtype=dtype)
|
| 345 |
+
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
|
| 346 |
+
# test 2D
|
| 347 |
+
arr = arr.reshape(2, 5)
|
| 348 |
+
self.assertPreciseEqual(pyfunc(arr), cfunc(arr))
|
| 349 |
+
# test are zeros
|
| 350 |
+
self.assertEqual(cfunc(arr).tolist(), np.zeros_like(arr).tolist())
|
| 351 |
+
# test readonly
|
| 352 |
+
imag = cfunc(arr)
|
| 353 |
+
with self.assertRaises(ValueError) as raises:
|
| 354 |
+
imag[0] = 1
|
| 355 |
+
self.assertEqual('assignment destination is read-only',
|
| 356 |
+
str(raises.exception))
|
| 357 |
+
|
| 358 |
+
def test_number_imag(self):
|
| 359 |
+
"""
|
| 360 |
+
Testing .imag of non-complex dtypes
|
| 361 |
+
"""
|
| 362 |
+
for dtype in [np.uint8, np.int32, np.float32, np.float64]:
|
| 363 |
+
self.check_number_imag(dtype)
|
| 364 |
+
|
| 365 |
+
def test_record_real(self):
|
| 366 |
+
rectyp = np.dtype([('real', np.float32), ('imag', np.complex64)])
|
| 367 |
+
arr = np.zeros(3, dtype=rectyp)
|
| 368 |
+
arr['real'] = np.random.random(arr.size)
|
| 369 |
+
arr['imag'] = np.random.random(arr.size) * 1.3j
|
| 370 |
+
|
| 371 |
+
# check numpy behavior
|
| 372 |
+
# .real is identity
|
| 373 |
+
self.assertIs(array_real(arr), arr)
|
| 374 |
+
# .imag is zero_like
|
| 375 |
+
self.assertEqual(array_imag(arr).tolist(), np.zeros_like(arr).tolist())
|
| 376 |
+
|
| 377 |
+
# check numba behavior
|
| 378 |
+
# it's most likely a user error, anyway
|
| 379 |
+
jit_array_real = njit(array_real)
|
| 380 |
+
jit_array_imag = njit(array_imag)
|
| 381 |
+
|
| 382 |
+
with self.assertRaises(TypingError) as raises:
|
| 383 |
+
jit_array_real(arr)
|
| 384 |
+
self.assertIn("cannot access .real of array of Record",
|
| 385 |
+
str(raises.exception))
|
| 386 |
+
|
| 387 |
+
with self.assertRaises(TypingError) as raises:
|
| 388 |
+
jit_array_imag(arr)
|
| 389 |
+
self.assertIn("cannot access .imag of array of Record",
|
| 390 |
+
str(raises.exception))
|
| 391 |
+
|
| 392 |
+
class TestJitclassFlagsSegfault(MemoryLeakMixin, TestCase):
|
| 393 |
+
"""Regression test for: https://github.com/numba/numba/issues/4775 """
|
| 394 |
+
|
| 395 |
+
def test(self):
|
| 396 |
+
|
| 397 |
+
@jitclass(dict())
|
| 398 |
+
class B(object):
|
| 399 |
+
|
| 400 |
+
def __init__(self):
|
| 401 |
+
pass
|
| 402 |
+
|
| 403 |
+
def foo(self, X):
|
| 404 |
+
X.flags
|
| 405 |
+
|
| 406 |
+
Z = B()
|
| 407 |
+
Z.foo(np.ones(4))
|
| 408 |
+
|
| 409 |
+
if __name__ == '__main__':
|
| 410 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_array_iterators.py
ADDED
|
@@ -0,0 +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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from numba import jit, njit, typeof
|
| 6 |
+
from numba.core import types
|
| 7 |
+
from numba.tests.support import TestCase, MemoryLeakMixin
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def array_iter(arr):
|
| 12 |
+
total = 0
|
| 13 |
+
for i, v in enumerate(arr):
|
| 14 |
+
total += i * v
|
| 15 |
+
return total
|
| 16 |
+
|
| 17 |
+
def array_iter_items(arr):
|
| 18 |
+
return list(iter(arr))
|
| 19 |
+
|
| 20 |
+
def array_view_iter(arr, idx):
|
| 21 |
+
total = 0
|
| 22 |
+
for i, v in enumerate(arr[idx]):
|
| 23 |
+
total += i * v
|
| 24 |
+
return total
|
| 25 |
+
|
| 26 |
+
def array_flat(arr, out):
|
| 27 |
+
for i, v in enumerate(arr.flat):
|
| 28 |
+
out[i] = v
|
| 29 |
+
|
| 30 |
+
def array_flat_getitem(arr, ind):
|
| 31 |
+
return arr.flat[ind]
|
| 32 |
+
|
| 33 |
+
def array_flat_setitem(arr, ind, val):
|
| 34 |
+
arr.flat[ind] = val
|
| 35 |
+
|
| 36 |
+
def array_flat_sum(arr):
|
| 37 |
+
s = 0
|
| 38 |
+
for i, v in enumerate(arr.flat):
|
| 39 |
+
s = s + (i + 1) * v
|
| 40 |
+
return s
|
| 41 |
+
|
| 42 |
+
def array_flat_len(arr):
|
| 43 |
+
return len(arr.flat)
|
| 44 |
+
|
| 45 |
+
def array_ndenumerate_sum(arr):
|
| 46 |
+
s = 0
|
| 47 |
+
for (i, j), v in np.ndenumerate(arr):
|
| 48 |
+
s = s + (i + 1) * (j + 1) * v
|
| 49 |
+
return s
|
| 50 |
+
|
| 51 |
+
def np_ndindex_empty():
|
| 52 |
+
s = 0
|
| 53 |
+
for ind in np.ndindex(()):
|
| 54 |
+
s += s + len(ind) + 1
|
| 55 |
+
return s
|
| 56 |
+
|
| 57 |
+
def np_ndindex(x, y):
|
| 58 |
+
s = 0
|
| 59 |
+
n = 0
|
| 60 |
+
for i, j in np.ndindex(x, y):
|
| 61 |
+
s = s + (i + 1) * (j + 1)
|
| 62 |
+
return s
|
| 63 |
+
|
| 64 |
+
def np_ndindex_array(arr):
|
| 65 |
+
s = 0
|
| 66 |
+
n = 0
|
| 67 |
+
for indices in np.ndindex(arr.shape):
|
| 68 |
+
for i, j in enumerate(indices):
|
| 69 |
+
s = s + (i + 1) * (j + 1)
|
| 70 |
+
return s
|
| 71 |
+
|
| 72 |
+
def np_nditer1(a):
|
| 73 |
+
res = []
|
| 74 |
+
for u in np.nditer(a):
|
| 75 |
+
res.append(u.item())
|
| 76 |
+
return res
|
| 77 |
+
|
| 78 |
+
def np_nditer2(a, b):
|
| 79 |
+
res = []
|
| 80 |
+
for u, v in np.nditer((a, b)):
|
| 81 |
+
res.append((u.item(), v.item()))
|
| 82 |
+
return res
|
| 83 |
+
|
| 84 |
+
def np_nditer3(a, b, c):
|
| 85 |
+
res = []
|
| 86 |
+
for u, v, w in np.nditer((a, b, c)):
|
| 87 |
+
res.append((u.item(), v.item(), w.item()))
|
| 88 |
+
return res
|
| 89 |
+
|
| 90 |
+
def iter_next(arr):
|
| 91 |
+
it = iter(arr)
|
| 92 |
+
it2 = iter(arr)
|
| 93 |
+
return next(it), next(it), next(it2)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
#
|
| 97 |
+
# Test premature free (see issue #2112).
|
| 98 |
+
# The following test allocates an array ``x`` inside the body.
|
| 99 |
+
# The compiler will put a ``del x`` right after the last use of ``x``,
|
| 100 |
+
# which is right after the creation of the array iterator and
|
| 101 |
+
# before the loop is entered. If the iterator does not incref the array,
|
| 102 |
+
# the iterator will be reading garbage data of free'ed memory.
|
| 103 |
+
#
|
| 104 |
+
|
| 105 |
+
def array_flat_premature_free(size):
|
| 106 |
+
x = np.arange(size)
|
| 107 |
+
res = np.zeros_like(x, dtype=np.intp)
|
| 108 |
+
for i, v in enumerate(x.flat):
|
| 109 |
+
res[i] = v
|
| 110 |
+
return res
|
| 111 |
+
|
| 112 |
+
def array_ndenumerate_premature_free(size):
|
| 113 |
+
x = np.arange(size)
|
| 114 |
+
res = np.zeros_like(x, dtype=np.intp)
|
| 115 |
+
for i, v in np.ndenumerate(x):
|
| 116 |
+
res[i] = v
|
| 117 |
+
return res
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TestArrayIterators(MemoryLeakMixin, TestCase):
|
| 121 |
+
"""
|
| 122 |
+
Test array.flat, np.ndenumerate(), etc.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def setUp(self):
|
| 126 |
+
super(TestArrayIterators, self).setUp()
|
| 127 |
+
|
| 128 |
+
def check_array_iter_1d(self, arr):
|
| 129 |
+
pyfunc = array_iter
|
| 130 |
+
cfunc = njit((typeof(arr),))(pyfunc)
|
| 131 |
+
expected = pyfunc(arr)
|
| 132 |
+
self.assertPreciseEqual(cfunc(arr), expected)
|
| 133 |
+
|
| 134 |
+
def check_array_iter_items(self, arr):
|
| 135 |
+
pyfunc = array_iter_items
|
| 136 |
+
cfunc = njit((typeof(arr),))(pyfunc)
|
| 137 |
+
expected = pyfunc(arr)
|
| 138 |
+
self.assertPreciseEqual(cfunc(arr), expected)
|
| 139 |
+
|
| 140 |
+
def check_array_view_iter(self, arr, index):
|
| 141 |
+
pyfunc = array_view_iter
|
| 142 |
+
cfunc = njit((typeof(arr), typeof(index),))(pyfunc)
|
| 143 |
+
expected = pyfunc(arr, index)
|
| 144 |
+
self.assertPreciseEqual(cfunc(arr, index), expected)
|
| 145 |
+
|
| 146 |
+
def check_array_flat(self, arr, arrty=None):
|
| 147 |
+
out = np.zeros(arr.size, dtype=arr.dtype)
|
| 148 |
+
nb_out = out.copy()
|
| 149 |
+
if arrty is None:
|
| 150 |
+
arrty = typeof(arr)
|
| 151 |
+
|
| 152 |
+
cfunc = njit((arrty, typeof(out),))(array_flat)
|
| 153 |
+
|
| 154 |
+
array_flat(arr, out)
|
| 155 |
+
cfunc(arr, nb_out)
|
| 156 |
+
|
| 157 |
+
self.assertPreciseEqual(out, nb_out)
|
| 158 |
+
|
| 159 |
+
def check_array_unary(self, arr, arrty, func):
|
| 160 |
+
cfunc = njit((arrty,))(func)
|
| 161 |
+
self.assertPreciseEqual(cfunc(arr), func(arr))
|
| 162 |
+
|
| 163 |
+
def check_array_ndenumerate_sum(self, arr, arrty):
|
| 164 |
+
self.check_array_unary(arr, arrty, array_ndenumerate_sum)
|
| 165 |
+
|
| 166 |
+
def test_array_iter(self):
|
| 167 |
+
# Test iterating over arrays
|
| 168 |
+
arr = np.arange(6)
|
| 169 |
+
self.check_array_iter_1d(arr)
|
| 170 |
+
self.check_array_iter_items(arr)
|
| 171 |
+
arr = arr[::2]
|
| 172 |
+
self.assertFalse(arr.flags.c_contiguous)
|
| 173 |
+
self.assertFalse(arr.flags.f_contiguous)
|
| 174 |
+
self.check_array_iter_1d(arr)
|
| 175 |
+
self.check_array_iter_items(arr)
|
| 176 |
+
arr = np.bool_([1, 0, 0, 1])
|
| 177 |
+
self.check_array_iter_1d(arr)
|
| 178 |
+
self.check_array_iter_items(arr)
|
| 179 |
+
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 180 |
+
self.check_array_iter_items(arr)
|
| 181 |
+
self.check_array_iter_items(arr.T)
|
| 182 |
+
|
| 183 |
+
def test_array_iter_yielded_order(self):
|
| 184 |
+
# See issue #5692
|
| 185 |
+
@jit(nopython=True)
|
| 186 |
+
def foo(arr):
|
| 187 |
+
t = []
|
| 188 |
+
for y1 in arr:
|
| 189 |
+
for y2 in y1:
|
| 190 |
+
t.append(y2.ravel())
|
| 191 |
+
return t
|
| 192 |
+
|
| 193 |
+
# 'F' ordered
|
| 194 |
+
arr = np.arange(24).reshape((2, 3, 4), order='F')
|
| 195 |
+
expected = foo.py_func(arr)
|
| 196 |
+
got = foo(arr)
|
| 197 |
+
self.assertPreciseEqual(expected, got)
|
| 198 |
+
|
| 199 |
+
# 'A' ordered, outer strided
|
| 200 |
+
arr = np.arange(64).reshape((4, 8, 2), order='F')[::2, :, :]
|
| 201 |
+
expected = foo.py_func(arr)
|
| 202 |
+
got = foo(arr)
|
| 203 |
+
self.assertPreciseEqual(expected, got)
|
| 204 |
+
|
| 205 |
+
# 'A' ordered, middle strided
|
| 206 |
+
arr = np.arange(64).reshape((4, 8, 2), order='F')[:, ::2, :]
|
| 207 |
+
expected = foo.py_func(arr)
|
| 208 |
+
got = foo(arr)
|
| 209 |
+
self.assertPreciseEqual(expected, got)
|
| 210 |
+
|
| 211 |
+
# 'A' ordered, inner strided
|
| 212 |
+
arr = np.arange(64).reshape((4, 8, 2), order='F')[:, :, ::2]
|
| 213 |
+
expected = foo.py_func(arr)
|
| 214 |
+
got = foo(arr)
|
| 215 |
+
self.assertPreciseEqual(expected, got)
|
| 216 |
+
|
| 217 |
+
@jit(nopython=True)
|
| 218 |
+
def flag_check(arr):
|
| 219 |
+
out = []
|
| 220 |
+
for sub in arr:
|
| 221 |
+
out.append((sub, sub.flags.c_contiguous,
|
| 222 |
+
sub.flags.f_contiguous))
|
| 223 |
+
return out
|
| 224 |
+
|
| 225 |
+
arr = np.arange(10).reshape((2, 5), order='F')
|
| 226 |
+
expected = flag_check.py_func(arr)
|
| 227 |
+
got = flag_check(arr)
|
| 228 |
+
|
| 229 |
+
self.assertEqual(len(expected), len(got))
|
| 230 |
+
ex_arr, e_flag_c, e_flag_f = expected[0]
|
| 231 |
+
go_arr, g_flag_c, g_flag_f = got[0]
|
| 232 |
+
np.testing.assert_allclose(ex_arr, go_arr)
|
| 233 |
+
self.assertEqual(e_flag_c, g_flag_c)
|
| 234 |
+
self.assertEqual(e_flag_f, g_flag_f)
|
| 235 |
+
|
| 236 |
+
def test_array_view_iter(self):
|
| 237 |
+
# Test iterating over a 1d view over a 2d array
|
| 238 |
+
arr = np.arange(12).reshape((3, 4))
|
| 239 |
+
self.check_array_view_iter(arr, 1)
|
| 240 |
+
self.check_array_view_iter(arr.T, 1)
|
| 241 |
+
arr = arr[::2]
|
| 242 |
+
self.check_array_view_iter(arr, 1)
|
| 243 |
+
arr = np.bool_([1, 0, 0, 1]).reshape((2, 2))
|
| 244 |
+
self.check_array_view_iter(arr, 1)
|
| 245 |
+
|
| 246 |
+
def test_array_flat_3d(self):
|
| 247 |
+
arr = np.arange(24).reshape(4, 2, 3)
|
| 248 |
+
|
| 249 |
+
arrty = typeof(arr)
|
| 250 |
+
self.assertEqual(arrty.ndim, 3)
|
| 251 |
+
self.assertEqual(arrty.layout, 'C')
|
| 252 |
+
self.assertTrue(arr.flags.c_contiguous)
|
| 253 |
+
# Test with C-contiguous array
|
| 254 |
+
self.check_array_flat(arr)
|
| 255 |
+
# Test with Fortran-contiguous array
|
| 256 |
+
arr = arr.transpose()
|
| 257 |
+
self.assertFalse(arr.flags.c_contiguous)
|
| 258 |
+
self.assertTrue(arr.flags.f_contiguous)
|
| 259 |
+
self.assertEqual(typeof(arr).layout, 'F')
|
| 260 |
+
self.check_array_flat(arr)
|
| 261 |
+
# Test with non-contiguous array
|
| 262 |
+
arr = arr[::2]
|
| 263 |
+
self.assertFalse(arr.flags.c_contiguous)
|
| 264 |
+
self.assertFalse(arr.flags.f_contiguous)
|
| 265 |
+
self.assertEqual(typeof(arr).layout, 'A')
|
| 266 |
+
self.check_array_flat(arr)
|
| 267 |
+
# Boolean array
|
| 268 |
+
arr = np.bool_([1, 0, 0, 1] * 2).reshape((2, 2, 2))
|
| 269 |
+
self.check_array_flat(arr)
|
| 270 |
+
|
| 271 |
+
def test_array_flat_empty(self):
|
| 272 |
+
# Test .flat with various shapes of empty arrays, contiguous
|
| 273 |
+
# and non-contiguous (see issue #846).
|
| 274 |
+
|
| 275 |
+
# Define a local checking function, Numba's `typeof` ends up aliasing
|
| 276 |
+
# 0d C and F ordered arrays, so the check needs to go via the compile
|
| 277 |
+
# result entry point to bypass type checking.
|
| 278 |
+
def check(arr, arrty):
|
| 279 |
+
cfunc = njit((arrty,))(array_flat_sum)
|
| 280 |
+
cres = cfunc.overloads[(arrty,)]
|
| 281 |
+
got = cres.entry_point(arr)
|
| 282 |
+
expected = cfunc.py_func(arr)
|
| 283 |
+
self.assertPreciseEqual(expected, got)
|
| 284 |
+
|
| 285 |
+
arr = np.zeros(0, dtype=np.int32)
|
| 286 |
+
arr = arr.reshape(0, 2)
|
| 287 |
+
arrty = types.Array(types.int32, 2, layout='C')
|
| 288 |
+
check(arr, arrty)
|
| 289 |
+
arrty = types.Array(types.int32, 2, layout='F')
|
| 290 |
+
check(arr, arrty)
|
| 291 |
+
arrty = types.Array(types.int32, 2, layout='A')
|
| 292 |
+
check(arr, arrty)
|
| 293 |
+
arr = arr.reshape(2, 0)
|
| 294 |
+
arrty = types.Array(types.int32, 2, layout='C')
|
| 295 |
+
check(arr, arrty)
|
| 296 |
+
arrty = types.Array(types.int32, 2, layout='F')
|
| 297 |
+
check(arr, arrty)
|
| 298 |
+
arrty = types.Array(types.int32, 2, layout='A')
|
| 299 |
+
check(arr, arrty)
|
| 300 |
+
|
| 301 |
+
def test_array_flat_getitem(self):
|
| 302 |
+
# Test indexing of array.flat object
|
| 303 |
+
pyfunc = array_flat_getitem
|
| 304 |
+
cfunc = njit(pyfunc)
|
| 305 |
+
def check(arr, ind):
|
| 306 |
+
expected = pyfunc(arr, ind)
|
| 307 |
+
self.assertEqual(cfunc(arr, ind), expected)
|
| 308 |
+
|
| 309 |
+
arr = np.arange(24).reshape(4, 2, 3)
|
| 310 |
+
for i in range(arr.size):
|
| 311 |
+
check(arr, i)
|
| 312 |
+
arr = arr.T
|
| 313 |
+
for i in range(arr.size):
|
| 314 |
+
check(arr, i)
|
| 315 |
+
arr = arr[::2]
|
| 316 |
+
for i in range(arr.size):
|
| 317 |
+
check(arr, i)
|
| 318 |
+
arr = np.array([42]).reshape(())
|
| 319 |
+
for i in range(arr.size):
|
| 320 |
+
check(arr, i)
|
| 321 |
+
# Boolean array
|
| 322 |
+
arr = np.bool_([1, 0, 0, 1])
|
| 323 |
+
for i in range(arr.size):
|
| 324 |
+
check(arr, i)
|
| 325 |
+
arr = arr[::2]
|
| 326 |
+
for i in range(arr.size):
|
| 327 |
+
check(arr, i)
|
| 328 |
+
|
| 329 |
+
def test_array_flat_setitem(self):
|
| 330 |
+
# Test indexing of array.flat object
|
| 331 |
+
pyfunc = array_flat_setitem
|
| 332 |
+
cfunc = njit(pyfunc)
|
| 333 |
+
def check(arr, ind):
|
| 334 |
+
# Use np.copy() to keep the layout
|
| 335 |
+
expected = np.copy(arr)
|
| 336 |
+
got = np.copy(arr)
|
| 337 |
+
pyfunc(expected, ind, 123)
|
| 338 |
+
cfunc(got, ind, 123)
|
| 339 |
+
self.assertPreciseEqual(got, expected)
|
| 340 |
+
|
| 341 |
+
arr = np.arange(24).reshape(4, 2, 3)
|
| 342 |
+
for i in range(arr.size):
|
| 343 |
+
check(arr, i)
|
| 344 |
+
arr = arr.T
|
| 345 |
+
for i in range(arr.size):
|
| 346 |
+
check(arr, i)
|
| 347 |
+
arr = arr[::2]
|
| 348 |
+
for i in range(arr.size):
|
| 349 |
+
check(arr, i)
|
| 350 |
+
arr = np.array([42]).reshape(())
|
| 351 |
+
for i in range(arr.size):
|
| 352 |
+
check(arr, i)
|
| 353 |
+
# Boolean array
|
| 354 |
+
arr = np.bool_([1, 0, 0, 1])
|
| 355 |
+
for i in range(arr.size):
|
| 356 |
+
check(arr, i)
|
| 357 |
+
arr = arr[::2]
|
| 358 |
+
for i in range(arr.size):
|
| 359 |
+
check(arr, i)
|
| 360 |
+
|
| 361 |
+
def test_array_flat_len(self):
|
| 362 |
+
# Test len(array.flat)
|
| 363 |
+
pyfunc = array_flat_len
|
| 364 |
+
cfunc = njit(array_flat_len)
|
| 365 |
+
def check(arr):
|
| 366 |
+
expected = pyfunc(arr)
|
| 367 |
+
self.assertPreciseEqual(cfunc(arr), expected)
|
| 368 |
+
|
| 369 |
+
arr = np.arange(24).reshape(4, 2, 3)
|
| 370 |
+
check(arr)
|
| 371 |
+
arr = arr.T
|
| 372 |
+
check(arr)
|
| 373 |
+
arr = arr[::2]
|
| 374 |
+
check(arr)
|
| 375 |
+
arr = np.array([42]).reshape(())
|
| 376 |
+
check(arr)
|
| 377 |
+
|
| 378 |
+
def test_array_flat_premature_free(self):
|
| 379 |
+
cfunc = njit((types.intp,))(array_flat_premature_free)
|
| 380 |
+
expect = array_flat_premature_free(6)
|
| 381 |
+
got = cfunc(6)
|
| 382 |
+
self.assertTrue(got.sum())
|
| 383 |
+
self.assertPreciseEqual(expect, got)
|
| 384 |
+
|
| 385 |
+
def test_array_ndenumerate_2d(self):
|
| 386 |
+
arr = np.arange(12).reshape(4, 3)
|
| 387 |
+
arrty = typeof(arr)
|
| 388 |
+
self.assertEqual(arrty.ndim, 2)
|
| 389 |
+
self.assertEqual(arrty.layout, 'C')
|
| 390 |
+
self.assertTrue(arr.flags.c_contiguous)
|
| 391 |
+
# Test with C-contiguous array
|
| 392 |
+
self.check_array_ndenumerate_sum(arr, arrty)
|
| 393 |
+
# Test with Fortran-contiguous array
|
| 394 |
+
arr = arr.transpose()
|
| 395 |
+
self.assertFalse(arr.flags.c_contiguous)
|
| 396 |
+
self.assertTrue(arr.flags.f_contiguous)
|
| 397 |
+
arrty = typeof(arr)
|
| 398 |
+
self.assertEqual(arrty.layout, 'F')
|
| 399 |
+
self.check_array_ndenumerate_sum(arr, arrty)
|
| 400 |
+
# Test with non-contiguous array
|
| 401 |
+
arr = arr[::2]
|
| 402 |
+
self.assertFalse(arr.flags.c_contiguous)
|
| 403 |
+
self.assertFalse(arr.flags.f_contiguous)
|
| 404 |
+
arrty = typeof(arr)
|
| 405 |
+
self.assertEqual(arrty.layout, 'A')
|
| 406 |
+
self.check_array_ndenumerate_sum(arr, arrty)
|
| 407 |
+
# Boolean array
|
| 408 |
+
arr = np.bool_([1, 0, 0, 1]).reshape((2, 2))
|
| 409 |
+
self.check_array_ndenumerate_sum(arr, typeof(arr))
|
| 410 |
+
|
| 411 |
+
def test_array_ndenumerate_empty(self):
|
| 412 |
+
# Define a local checking function, Numba's `typeof` ends up aliasing
|
| 413 |
+
# 0d C and F ordered arrays, so the check needs to go via the compile
|
| 414 |
+
# result entry point to bypass type checking.
|
| 415 |
+
def check(arr, arrty):
|
| 416 |
+
cfunc = njit((arrty,))(array_ndenumerate_sum)
|
| 417 |
+
cres = cfunc.overloads[(arrty,)]
|
| 418 |
+
got = cres.entry_point(arr)
|
| 419 |
+
expected = cfunc.py_func(arr)
|
| 420 |
+
np.testing.assert_allclose(expected, got)
|
| 421 |
+
|
| 422 |
+
arr = np.zeros(0, dtype=np.int32)
|
| 423 |
+
arr = arr.reshape(0, 2)
|
| 424 |
+
arrty = types.Array(types.int32, 2, layout='C')
|
| 425 |
+
check(arr, arrty)
|
| 426 |
+
arrty = types.Array(types.int32, 2, layout='F')
|
| 427 |
+
check(arr, arrty)
|
| 428 |
+
arrty = types.Array(types.int32, 2, layout='A')
|
| 429 |
+
check(arr, arrty)
|
| 430 |
+
arr = arr.reshape(2, 0)
|
| 431 |
+
arrty = types.Array(types.int32, 2, layout='C')
|
| 432 |
+
check(arr, arrty)
|
| 433 |
+
arrty = types.Array(types.int32, 2, layout='F')
|
| 434 |
+
check(arr, arrty)
|
| 435 |
+
arrty = types.Array(types.int32, 2, layout='A')
|
| 436 |
+
check(arr, arrty)
|
| 437 |
+
|
| 438 |
+
def test_array_ndenumerate_premature_free(self):
|
| 439 |
+
cfunc = njit((types.intp,))(array_ndenumerate_premature_free)
|
| 440 |
+
expect = array_ndenumerate_premature_free(6)
|
| 441 |
+
got = cfunc(6)
|
| 442 |
+
self.assertTrue(got.sum())
|
| 443 |
+
self.assertPreciseEqual(expect, got)
|
| 444 |
+
|
| 445 |
+
def test_np_ndindex(self):
|
| 446 |
+
func = np_ndindex
|
| 447 |
+
cfunc = njit((types.int32, types.int32,))(func)
|
| 448 |
+
self.assertPreciseEqual(cfunc(3, 4), func(3, 4))
|
| 449 |
+
self.assertPreciseEqual(cfunc(3, 0), func(3, 0))
|
| 450 |
+
self.assertPreciseEqual(cfunc(0, 3), func(0, 3))
|
| 451 |
+
self.assertPreciseEqual(cfunc(0, 0), func(0, 0))
|
| 452 |
+
|
| 453 |
+
def test_np_ndindex_array(self):
|
| 454 |
+
func = np_ndindex_array
|
| 455 |
+
arr = np.arange(12, dtype=np.int32) + 10
|
| 456 |
+
self.check_array_unary(arr, typeof(arr), func)
|
| 457 |
+
arr = arr.reshape((4, 3))
|
| 458 |
+
self.check_array_unary(arr, typeof(arr), func)
|
| 459 |
+
arr = arr.reshape((2, 2, 3))
|
| 460 |
+
self.check_array_unary(arr, typeof(arr), func)
|
| 461 |
+
|
| 462 |
+
def test_np_ndindex_empty(self):
|
| 463 |
+
func = np_ndindex_empty
|
| 464 |
+
cfunc = njit((),)(func)
|
| 465 |
+
self.assertPreciseEqual(cfunc(), func())
|
| 466 |
+
|
| 467 |
+
def test_iter_next(self):
|
| 468 |
+
# This also checks memory management with iter() and next()
|
| 469 |
+
func = iter_next
|
| 470 |
+
arr = np.arange(12, dtype=np.int32) + 10
|
| 471 |
+
self.check_array_unary(arr, typeof(arr), func)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
class TestNdIter(MemoryLeakMixin, TestCase):
|
| 475 |
+
"""
|
| 476 |
+
Test np.nditer()
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
def inputs(self):
|
| 480 |
+
# All those inputs are compatible with a (3, 4) main shape
|
| 481 |
+
|
| 482 |
+
# scalars
|
| 483 |
+
yield np.float32(100)
|
| 484 |
+
|
| 485 |
+
# 0-d arrays
|
| 486 |
+
yield np.array(102, dtype=np.int16)
|
| 487 |
+
|
| 488 |
+
# 1-d arrays
|
| 489 |
+
yield np.arange(4).astype(np.complex64)
|
| 490 |
+
yield np.arange(8)[::2]
|
| 491 |
+
|
| 492 |
+
# 2-d arrays
|
| 493 |
+
a = np.arange(12).reshape((3, 4))
|
| 494 |
+
yield a
|
| 495 |
+
yield a.copy(order='F')
|
| 496 |
+
a = np.arange(24).reshape((6, 4))[::2]
|
| 497 |
+
yield a
|
| 498 |
+
|
| 499 |
+
def basic_inputs(self):
|
| 500 |
+
yield np.arange(4).astype(np.complex64)
|
| 501 |
+
yield np.arange(8)[::2]
|
| 502 |
+
a = np.arange(12).reshape((3, 4))
|
| 503 |
+
yield a
|
| 504 |
+
yield a.copy(order='F')
|
| 505 |
+
|
| 506 |
+
def check_result(self, got, expected):
|
| 507 |
+
self.assertEqual(set(got), set(expected), (got, expected))
|
| 508 |
+
|
| 509 |
+
def test_nditer1(self):
|
| 510 |
+
pyfunc = np_nditer1
|
| 511 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 512 |
+
for a in self.inputs():
|
| 513 |
+
expected = pyfunc(a)
|
| 514 |
+
got = cfunc(a)
|
| 515 |
+
self.check_result(got, expected)
|
| 516 |
+
|
| 517 |
+
def test_nditer2(self):
|
| 518 |
+
pyfunc = np_nditer2
|
| 519 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 520 |
+
for a, b in itertools.product(self.inputs(), self.inputs()):
|
| 521 |
+
expected = pyfunc(a, b)
|
| 522 |
+
got = cfunc(a, b)
|
| 523 |
+
self.check_result(got, expected)
|
| 524 |
+
|
| 525 |
+
def test_nditer3(self):
|
| 526 |
+
pyfunc = np_nditer3
|
| 527 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 528 |
+
# Use a restricted set of inputs, to shorten test time
|
| 529 |
+
inputs = self.basic_inputs
|
| 530 |
+
for a, b, c in itertools.product(inputs(), inputs(), inputs()):
|
| 531 |
+
expected = pyfunc(a, b, c)
|
| 532 |
+
got = cfunc(a, b, c)
|
| 533 |
+
self.check_result(got, expected)
|
| 534 |
+
|
| 535 |
+
def test_errors(self):
|
| 536 |
+
# Incompatible shapes
|
| 537 |
+
pyfunc = np_nditer2
|
| 538 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 539 |
+
|
| 540 |
+
self.disable_leak_check()
|
| 541 |
+
|
| 542 |
+
def check_incompatible(a, b):
|
| 543 |
+
with self.assertRaises(ValueError) as raises:
|
| 544 |
+
cfunc(a, b)
|
| 545 |
+
self.assertIn("operands could not be broadcast together",
|
| 546 |
+
str(raises.exception))
|
| 547 |
+
|
| 548 |
+
check_incompatible(np.arange(2), np.arange(3))
|
| 549 |
+
a = np.arange(12).reshape((3, 4))
|
| 550 |
+
b = np.arange(3)
|
| 551 |
+
check_incompatible(a, b)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
if __name__ == '__main__':
|
| 555 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_buffer_protocol.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import array
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from numba import jit
|
| 6 |
+
from numba.tests.support import TestCase, compile_function, MemoryLeakMixin
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@jit(nopython=True)
|
| 11 |
+
def len_usecase(buf):
|
| 12 |
+
return len(buf)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@jit(nopython=True)
|
| 16 |
+
def getitem_usecase(buf, i):
|
| 17 |
+
return buf[i]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@jit(nopython=True)
|
| 21 |
+
def getslice_usecase(buf, i, j):
|
| 22 |
+
s = buf[i:j]
|
| 23 |
+
return s[0] + 2 * s[-1]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@jit(nopython=True)
|
| 27 |
+
def setitem_usecase(buf, i, v):
|
| 28 |
+
buf[i] = v
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@jit(nopython=True)
|
| 32 |
+
def iter_usecase(buf):
|
| 33 |
+
res = 0.0
|
| 34 |
+
for i, x in enumerate(buf):
|
| 35 |
+
res += x
|
| 36 |
+
res *= i + 1
|
| 37 |
+
return res
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def attrgetter(attr):
|
| 41 |
+
code = """def func(x):
|
| 42 |
+
return x.%(attr)s
|
| 43 |
+
""" % locals()
|
| 44 |
+
pyfunc = compile_function("func", code, globals())
|
| 45 |
+
return jit(nopython=True)(pyfunc)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
contiguous_usecase = attrgetter("contiguous")
|
| 49 |
+
c_contiguous_usecase = attrgetter("c_contiguous")
|
| 50 |
+
f_contiguous_usecase = attrgetter("f_contiguous")
|
| 51 |
+
itemsize_usecase = attrgetter("itemsize")
|
| 52 |
+
nbytes_usecase = attrgetter("nbytes")
|
| 53 |
+
ndim_usecase = attrgetter("ndim")
|
| 54 |
+
readonly_usecase = attrgetter("readonly")
|
| 55 |
+
shape_usecase = attrgetter("shape")
|
| 56 |
+
strides_usecase = attrgetter("strides")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class TestBufferProtocol(MemoryLeakMixin, TestCase):
|
| 60 |
+
"""
|
| 61 |
+
Test operations on buffer-providing objects.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def _arrays(self):
|
| 65 |
+
n = 10
|
| 66 |
+
for letter, offset in [
|
| 67 |
+
('b', -3),
|
| 68 |
+
('B', 0),
|
| 69 |
+
('h', -5000),
|
| 70 |
+
('H', 40000),
|
| 71 |
+
('i', -100000),
|
| 72 |
+
('I', 1000000),
|
| 73 |
+
('l', -100000),
|
| 74 |
+
('L', 1000000),
|
| 75 |
+
('q', -2**60),
|
| 76 |
+
('Q', 2**63 + 1),
|
| 77 |
+
('f', 1.5),
|
| 78 |
+
('d', -1.5),
|
| 79 |
+
]:
|
| 80 |
+
yield array.array(letter, [i + offset for i in range(n)])
|
| 81 |
+
|
| 82 |
+
def _memoryviews(self):
|
| 83 |
+
n = 10
|
| 84 |
+
yield memoryview(bytearray(b"abcdefghi"))
|
| 85 |
+
yield memoryview(b"abcdefghi")
|
| 86 |
+
# Different item types
|
| 87 |
+
for dtype, start, stop in [
|
| 88 |
+
('int8', -10, 10),
|
| 89 |
+
('uint8', 0, 10),
|
| 90 |
+
('int16', -5000, 1000),
|
| 91 |
+
('uint16', 40000, 50000),
|
| 92 |
+
('int32', -100000, 100000),
|
| 93 |
+
('uint32', 0, 1000000),
|
| 94 |
+
('int64', -2**60, 10),
|
| 95 |
+
('uint64', 0, 2**64 - 10),
|
| 96 |
+
('float32', 1.5, 3.5),
|
| 97 |
+
('float64', 1.5, 3.5),
|
| 98 |
+
('complex64', -8j, 12 + 5j),
|
| 99 |
+
('complex128', -8j, 12 + 5j),
|
| 100 |
+
]:
|
| 101 |
+
yield memoryview(np.linspace(start, stop, n).astype(dtype))
|
| 102 |
+
# Different layouts
|
| 103 |
+
arr = np.arange(12).reshape((3, 4))
|
| 104 |
+
assert arr.flags.c_contiguous and not arr.flags.f_contiguous
|
| 105 |
+
yield memoryview(arr)
|
| 106 |
+
arr = arr.T
|
| 107 |
+
assert arr.flags.f_contiguous and not arr.flags.c_contiguous
|
| 108 |
+
yield memoryview(arr)
|
| 109 |
+
arr = arr[::2]
|
| 110 |
+
assert not arr.flags.f_contiguous and not arr.flags.c_contiguous
|
| 111 |
+
yield memoryview(arr)
|
| 112 |
+
|
| 113 |
+
def _readonlies(self):
|
| 114 |
+
yield b"xyz"
|
| 115 |
+
yield memoryview(b"abcdefghi")
|
| 116 |
+
arr = np.arange(5)
|
| 117 |
+
arr.setflags(write=False)
|
| 118 |
+
yield memoryview(arr)
|
| 119 |
+
|
| 120 |
+
def _check_unary(self, jitfunc, *args):
|
| 121 |
+
pyfunc = jitfunc.py_func
|
| 122 |
+
self.assertPreciseEqual(jitfunc(*args), pyfunc(*args))
|
| 123 |
+
|
| 124 |
+
def check_len(self, obj):
|
| 125 |
+
self._check_unary(len_usecase, obj)
|
| 126 |
+
|
| 127 |
+
def check_iter(self, obj):
|
| 128 |
+
self._check_unary(iter_usecase, obj)
|
| 129 |
+
|
| 130 |
+
def check_getitem(self, obj):
|
| 131 |
+
# Be careful to index all dimensions, since we don't support
|
| 132 |
+
# partial indexing yet.
|
| 133 |
+
def yield_indices(obj):
|
| 134 |
+
try:
|
| 135 |
+
shape = obj.shape
|
| 136 |
+
except AttributeError:
|
| 137 |
+
shape = len(obj),
|
| 138 |
+
for tup in np.ndindex(shape):
|
| 139 |
+
# Simple 1d buffer-providing objects usually don't support
|
| 140 |
+
# tuple indexing.
|
| 141 |
+
if len(tup) == 1:
|
| 142 |
+
yield tup[0]
|
| 143 |
+
else:
|
| 144 |
+
yield tup
|
| 145 |
+
|
| 146 |
+
for i in yield_indices(obj):
|
| 147 |
+
try:
|
| 148 |
+
expected = obj[i]
|
| 149 |
+
except (NotImplementedError, TypeError):
|
| 150 |
+
if isinstance(obj, memoryview):
|
| 151 |
+
# The memoryview object doesn't support all codes yet,
|
| 152 |
+
# fall back on the underlying object.
|
| 153 |
+
expected = obj.obj[i]
|
| 154 |
+
else:
|
| 155 |
+
raise
|
| 156 |
+
self.assertPreciseEqual(getitem_usecase(obj, i), expected)
|
| 157 |
+
|
| 158 |
+
def check_setitem(self, obj):
|
| 159 |
+
for i in range(len(obj)):
|
| 160 |
+
orig = list(obj)
|
| 161 |
+
val = obj[i] // 2 + 1
|
| 162 |
+
setitem_usecase(obj, i, val)
|
| 163 |
+
self.assertEqual(obj[i], val)
|
| 164 |
+
for j, val in enumerate(orig):
|
| 165 |
+
if j != i:
|
| 166 |
+
self.assertEqual(obj[j], val)
|
| 167 |
+
|
| 168 |
+
def check_getslice(self, obj):
|
| 169 |
+
self._check_unary(getslice_usecase, obj, 1, len(obj) - 1)
|
| 170 |
+
|
| 171 |
+
def test_len(self):
|
| 172 |
+
self.check_len(bytearray(5))
|
| 173 |
+
self.check_len(b"xyz")
|
| 174 |
+
for mem in self._memoryviews():
|
| 175 |
+
self.check_len(mem)
|
| 176 |
+
for arr in self._arrays():
|
| 177 |
+
self.check_len(arr)
|
| 178 |
+
for buf in self._readonlies():
|
| 179 |
+
self.check_getitem(buf)
|
| 180 |
+
|
| 181 |
+
def test_getitem(self):
|
| 182 |
+
self.check_getitem(bytearray(b"abc"))
|
| 183 |
+
self.check_getitem(b"xyz")
|
| 184 |
+
for mem in self._memoryviews():
|
| 185 |
+
self.check_getitem(mem)
|
| 186 |
+
for arr in self._arrays():
|
| 187 |
+
self.check_getitem(arr)
|
| 188 |
+
for buf in self._readonlies():
|
| 189 |
+
self.check_getitem(buf)
|
| 190 |
+
|
| 191 |
+
def test_getslice(self):
|
| 192 |
+
with self.assertTypingError():
|
| 193 |
+
self.check_getslice(bytearray(b"abcde"))
|
| 194 |
+
self.check_getslice(b"xyzuvw")
|
| 195 |
+
self.check_getslice(memoryview(b"xyzuvw"))
|
| 196 |
+
with self.assertTypingError():
|
| 197 |
+
self.check_getslice(array.array('i', range(10)))
|
| 198 |
+
for buf in self._readonlies():
|
| 199 |
+
self.check_getitem(buf)
|
| 200 |
+
|
| 201 |
+
def test_setitem(self):
|
| 202 |
+
self.check_setitem(bytearray(b"abcdefghi"))
|
| 203 |
+
for arr in self._arrays():
|
| 204 |
+
self.check_setitem(arr)
|
| 205 |
+
for mem in self._memoryviews():
|
| 206 |
+
self.check_getitem(mem)
|
| 207 |
+
# Read-only buffers
|
| 208 |
+
for buf in self._readonlies():
|
| 209 |
+
with self.assertTypingError():
|
| 210 |
+
self.check_setitem(buf)
|
| 211 |
+
|
| 212 |
+
def test_iter(self):
|
| 213 |
+
self.check_iter(bytearray(b"abc"))
|
| 214 |
+
self.check_iter(b"xyz")
|
| 215 |
+
self.check_iter(memoryview(b"xyz"))
|
| 216 |
+
for arr in self._arrays():
|
| 217 |
+
self.check_iter(arr)
|
| 218 |
+
for buf in self._readonlies():
|
| 219 |
+
self.check_getitem(buf)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class TestMemoryView(MemoryLeakMixin, TestCase):
|
| 223 |
+
"""
|
| 224 |
+
Test memoryview-specific attributes and operations.
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
def _arrays(self):
|
| 228 |
+
arr = np.arange(12)
|
| 229 |
+
yield arr
|
| 230 |
+
arr = arr.reshape((3, 4))
|
| 231 |
+
yield arr
|
| 232 |
+
yield arr.T
|
| 233 |
+
yield arr[::2]
|
| 234 |
+
arr.setflags(write=False)
|
| 235 |
+
yield arr
|
| 236 |
+
arr = np.zeros(())
|
| 237 |
+
assert arr.ndim == 0
|
| 238 |
+
yield arr
|
| 239 |
+
|
| 240 |
+
def test_ndim(self):
|
| 241 |
+
for arr in self._arrays():
|
| 242 |
+
m = memoryview(arr)
|
| 243 |
+
self.assertPreciseEqual(ndim_usecase(m), arr.ndim)
|
| 244 |
+
|
| 245 |
+
def test_shape(self):
|
| 246 |
+
for arr in self._arrays():
|
| 247 |
+
m = memoryview(arr)
|
| 248 |
+
self.assertPreciseEqual(shape_usecase(m), arr.shape)
|
| 249 |
+
|
| 250 |
+
def test_strides(self):
|
| 251 |
+
for arr in self._arrays():
|
| 252 |
+
m = memoryview(arr)
|
| 253 |
+
self.assertPreciseEqual(strides_usecase(m), arr.strides)
|
| 254 |
+
|
| 255 |
+
def test_itemsize(self):
|
| 256 |
+
for arr in self._arrays():
|
| 257 |
+
m = memoryview(arr)
|
| 258 |
+
self.assertPreciseEqual(itemsize_usecase(m), arr.itemsize)
|
| 259 |
+
|
| 260 |
+
def test_nbytes(self):
|
| 261 |
+
for arr in self._arrays():
|
| 262 |
+
m = memoryview(arr)
|
| 263 |
+
self.assertPreciseEqual(nbytes_usecase(m), arr.size * arr.itemsize)
|
| 264 |
+
|
| 265 |
+
def test_readonly(self):
|
| 266 |
+
for arr in self._arrays():
|
| 267 |
+
m = memoryview(arr)
|
| 268 |
+
self.assertIs(readonly_usecase(m), not arr.flags.writeable)
|
| 269 |
+
m = memoryview(b"xyz")
|
| 270 |
+
self.assertIs(readonly_usecase(m), True)
|
| 271 |
+
m = memoryview(bytearray(b"xyz"))
|
| 272 |
+
self.assertIs(readonly_usecase(m), False)
|
| 273 |
+
|
| 274 |
+
def test_contiguous(self):
|
| 275 |
+
m = memoryview(bytearray(b"xyz"))
|
| 276 |
+
self.assertIs(contiguous_usecase(m), True)
|
| 277 |
+
self.assertIs(c_contiguous_usecase(m), True)
|
| 278 |
+
self.assertIs(f_contiguous_usecase(m), True)
|
| 279 |
+
for arr in self._arrays():
|
| 280 |
+
m = memoryview(arr)
|
| 281 |
+
# Note `arr.flags.contiguous` is wrong (it mimics c_contiguous)
|
| 282 |
+
self.assertIs(contiguous_usecase(m),
|
| 283 |
+
arr.flags.f_contiguous or arr.flags.c_contiguous)
|
| 284 |
+
self.assertIs(c_contiguous_usecase(m), arr.flags.c_contiguous)
|
| 285 |
+
self.assertIs(f_contiguous_usecase(m), arr.flags.f_contiguous)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if __name__ == '__main__':
|
| 289 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_builtins.py
ADDED
|
@@ -0,0 +1,1682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import functools
|
| 3 |
+
import sys
|
| 4 |
+
import operator
|
| 5 |
+
from collections import namedtuple
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
import unittest
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from numba import jit, typeof, njit, typed
|
| 13 |
+
from numba.core import errors, types, config
|
| 14 |
+
from numba.tests.support import (TestCase, tag, ignore_internal_warnings,
|
| 15 |
+
MemoryLeakMixin)
|
| 16 |
+
from numba.core.extending import overload_method, box, register_jitable
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
forceobj_flags = {'forceobj': True}
|
| 20 |
+
|
| 21 |
+
no_pyobj_flags = {'nopython': True, '_nrt': False}
|
| 22 |
+
|
| 23 |
+
nrt_no_pyobj_flags = {'nopython': True}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def abs_usecase(x):
|
| 27 |
+
return abs(x)
|
| 28 |
+
|
| 29 |
+
def all_usecase(x, y):
|
| 30 |
+
if x == None and y == None:
|
| 31 |
+
return all([])
|
| 32 |
+
elif x == None:
|
| 33 |
+
return all([y])
|
| 34 |
+
elif y == None:
|
| 35 |
+
return all([x])
|
| 36 |
+
else:
|
| 37 |
+
return all([x, y])
|
| 38 |
+
|
| 39 |
+
def any_usecase(x, y):
|
| 40 |
+
if x == None and y == None:
|
| 41 |
+
return any([])
|
| 42 |
+
elif x == None:
|
| 43 |
+
return any([y])
|
| 44 |
+
elif y == None:
|
| 45 |
+
return any([x])
|
| 46 |
+
else:
|
| 47 |
+
return any([x, y])
|
| 48 |
+
|
| 49 |
+
def bool_usecase(x):
|
| 50 |
+
return bool(x)
|
| 51 |
+
|
| 52 |
+
def complex_usecase(x, y):
|
| 53 |
+
return complex(x, y)
|
| 54 |
+
|
| 55 |
+
def divmod_usecase(x, y):
|
| 56 |
+
return divmod(x, y)
|
| 57 |
+
|
| 58 |
+
def enumerate_usecase():
|
| 59 |
+
result = 0
|
| 60 |
+
for i, j in enumerate((1., 2.5, 3.)):
|
| 61 |
+
result += i * j
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
def enumerate_start_usecase():
|
| 65 |
+
result = 0
|
| 66 |
+
for i, j in enumerate((1., 2.5, 3.), 42):
|
| 67 |
+
result += i * j
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
def enumerate_invalid_start_usecase():
|
| 71 |
+
result = 0
|
| 72 |
+
for i, j in enumerate((1., 2.5, 3.), 3.14159):
|
| 73 |
+
result += i * j
|
| 74 |
+
return result
|
| 75 |
+
|
| 76 |
+
def filter_usecase(x, filter_func):
|
| 77 |
+
return filter(filter_func, x)
|
| 78 |
+
|
| 79 |
+
def float_usecase(x):
|
| 80 |
+
return float(x)
|
| 81 |
+
|
| 82 |
+
def float_inf_usecase(x):
|
| 83 |
+
d = {
|
| 84 |
+
0: float('inf'),
|
| 85 |
+
1: float('INF'),
|
| 86 |
+
2: float('-inf'),
|
| 87 |
+
3: float('-INF'),
|
| 88 |
+
4: float('\r\nINF\r '),
|
| 89 |
+
5: float(' \r\n\t-INF'),
|
| 90 |
+
6: float('1234.45'),
|
| 91 |
+
7: float('\n-123.4\r'),
|
| 92 |
+
}
|
| 93 |
+
return d.get(x)
|
| 94 |
+
|
| 95 |
+
def format_usecase(x, y):
|
| 96 |
+
return x.format(y)
|
| 97 |
+
|
| 98 |
+
def globals_usecase():
|
| 99 |
+
return globals()
|
| 100 |
+
|
| 101 |
+
# NOTE: hash() is tested in test_hashing
|
| 102 |
+
|
| 103 |
+
def hex_usecase(x):
|
| 104 |
+
return hex(x)
|
| 105 |
+
|
| 106 |
+
def str_usecase(x):
|
| 107 |
+
return str(x)
|
| 108 |
+
|
| 109 |
+
def int_usecase(x, base):
|
| 110 |
+
return int(x, base=base)
|
| 111 |
+
|
| 112 |
+
def iter_next_usecase(x):
|
| 113 |
+
it = iter(x)
|
| 114 |
+
return next(it), next(it)
|
| 115 |
+
|
| 116 |
+
def locals_usecase(x):
|
| 117 |
+
y = 5
|
| 118 |
+
return locals()['y']
|
| 119 |
+
|
| 120 |
+
def long_usecase(x, base):
|
| 121 |
+
return long(x, base=base)
|
| 122 |
+
|
| 123 |
+
def map_usecase(x, map_func):
|
| 124 |
+
return map(map_func, x)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def max_usecase1(x, y):
|
| 128 |
+
return max(x, y)
|
| 129 |
+
|
| 130 |
+
def max_usecase2(x, y):
|
| 131 |
+
return max([x, y])
|
| 132 |
+
|
| 133 |
+
def max_usecase3(x):
|
| 134 |
+
return max(x)
|
| 135 |
+
|
| 136 |
+
def max_usecase4():
|
| 137 |
+
return max(())
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def min_usecase1(x, y):
|
| 141 |
+
return min(x, y)
|
| 142 |
+
|
| 143 |
+
def min_usecase2(x, y):
|
| 144 |
+
return min([x, y])
|
| 145 |
+
|
| 146 |
+
def min_usecase3(x):
|
| 147 |
+
return min(x)
|
| 148 |
+
|
| 149 |
+
def min_usecase4():
|
| 150 |
+
return min(())
|
| 151 |
+
|
| 152 |
+
def oct_usecase(x):
|
| 153 |
+
return oct(x)
|
| 154 |
+
|
| 155 |
+
def reduce_usecase(reduce_func, x):
|
| 156 |
+
return functools.reduce(reduce_func, x)
|
| 157 |
+
|
| 158 |
+
def round_usecase1(x):
|
| 159 |
+
return round(x)
|
| 160 |
+
|
| 161 |
+
def round_usecase2(x, n):
|
| 162 |
+
return round(x, n)
|
| 163 |
+
|
| 164 |
+
def sum_usecase(x):
|
| 165 |
+
return sum(x)
|
| 166 |
+
|
| 167 |
+
def type_unary_usecase(a, b):
|
| 168 |
+
return type(a)(b)
|
| 169 |
+
|
| 170 |
+
def truth_usecase(p):
|
| 171 |
+
return operator.truth(p)
|
| 172 |
+
|
| 173 |
+
def unichr_usecase(x):
|
| 174 |
+
return unichr(x)
|
| 175 |
+
|
| 176 |
+
def zip_usecase():
|
| 177 |
+
result = 0
|
| 178 |
+
for i, j in zip((1, 2, 3), (4.5, 6.7)):
|
| 179 |
+
result += i * j
|
| 180 |
+
return result
|
| 181 |
+
|
| 182 |
+
def zip_0_usecase():
|
| 183 |
+
result = 0
|
| 184 |
+
for i in zip():
|
| 185 |
+
result += 1
|
| 186 |
+
return result
|
| 187 |
+
|
| 188 |
+
def zip_1_usecase():
|
| 189 |
+
result = 0
|
| 190 |
+
for i, in zip((1, 2)):
|
| 191 |
+
result += i
|
| 192 |
+
return result
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def zip_3_usecase():
|
| 196 |
+
result = 0
|
| 197 |
+
for i, j, k in zip((1, 2), (3, 4, 5), (6.7, 8.9)):
|
| 198 |
+
result += i * j * k
|
| 199 |
+
return result
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def zip_first_exhausted():
|
| 203 |
+
iterable = range(7)
|
| 204 |
+
n = 3
|
| 205 |
+
it = iter(iterable)
|
| 206 |
+
# 1st iterator is shorter
|
| 207 |
+
front = list(zip(range(n), it))
|
| 208 |
+
# Make sure that we didn't skip one in `it`
|
| 209 |
+
back = list(it)
|
| 210 |
+
return front, back
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def pow_op_usecase(x, y):
|
| 214 |
+
return x ** y
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def pow_usecase(x, y):
|
| 218 |
+
return pow(x, y)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def sum_usecase(x):
|
| 222 |
+
return sum(x)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def sum_kwarg_usecase(x, start=0):
|
| 226 |
+
ret = sum(x, start)
|
| 227 |
+
return sum(x, start=start), ret
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def isinstance_usecase(a):
|
| 231 |
+
if isinstance(a, (int, float)):
|
| 232 |
+
if isinstance(a, int):
|
| 233 |
+
return a + 1, 'int'
|
| 234 |
+
if isinstance(a, float):
|
| 235 |
+
return a + 2.0, 'float'
|
| 236 |
+
elif isinstance(a, str):
|
| 237 |
+
return a + ", world!", 'str'
|
| 238 |
+
elif isinstance(a, complex):
|
| 239 |
+
return a.imag, 'complex'
|
| 240 |
+
elif isinstance(a, (tuple, list)):
|
| 241 |
+
if isinstance(a, tuple):
|
| 242 |
+
return 'tuple'
|
| 243 |
+
else:
|
| 244 |
+
return 'list'
|
| 245 |
+
elif isinstance(a, set):
|
| 246 |
+
return 'set'
|
| 247 |
+
elif isinstance(a, bytes):
|
| 248 |
+
return 'bytes'
|
| 249 |
+
return 'no match'
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def isinstance_dict():
|
| 253 |
+
a = {1: 2, 3: 4}
|
| 254 |
+
b = {'a': 10, 'b': np.zeros(3)}
|
| 255 |
+
if isinstance(a, dict) and isinstance(b, dict):
|
| 256 |
+
return 'dict'
|
| 257 |
+
else:
|
| 258 |
+
return 'not dict'
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def isinstance_usecase_numba_types(a):
|
| 262 |
+
if isinstance(a, typed.List):
|
| 263 |
+
return 'typed list'
|
| 264 |
+
elif isinstance(a, (types.int32, types.int64)):
|
| 265 |
+
if isinstance(a, types.int32):
|
| 266 |
+
return 'int32'
|
| 267 |
+
else:
|
| 268 |
+
return 'int64'
|
| 269 |
+
elif isinstance(a, (types.float32, types.float64)):
|
| 270 |
+
if isinstance(a, types.float32):
|
| 271 |
+
return 'float32'
|
| 272 |
+
elif isinstance(a, types.float64):
|
| 273 |
+
return 'float64'
|
| 274 |
+
elif isinstance(a, typed.Dict):
|
| 275 |
+
return 'typed dict'
|
| 276 |
+
else:
|
| 277 |
+
return 'no match'
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def isinstance_usecase_numba_types_2():
|
| 281 |
+
# some types cannot be passed as argument to njit functions
|
| 282 |
+
a = b'hello'
|
| 283 |
+
b = range(1, 2)
|
| 284 |
+
c = dict()
|
| 285 |
+
c[2] = 3
|
| 286 |
+
if isinstance(a, bytes) and \
|
| 287 |
+
isinstance(b, range) and \
|
| 288 |
+
isinstance(c, dict):
|
| 289 |
+
return True
|
| 290 |
+
return False
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def invalid_isinstance_usecase(x):
|
| 294 |
+
if isinstance(x, ('foo',)):
|
| 295 |
+
return 'true branch'
|
| 296 |
+
else:
|
| 297 |
+
return 'false branch'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def isinstance_usecase_invalid_type(x):
|
| 301 |
+
# this should be a valid call when x := float
|
| 302 |
+
if isinstance(x, (float, 'not a type')):
|
| 303 |
+
return True
|
| 304 |
+
else:
|
| 305 |
+
return False
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def invalid_isinstance_usecase_phi_nopropagate(x):
|
| 309 |
+
if x > 4:
|
| 310 |
+
z = 10
|
| 311 |
+
else:
|
| 312 |
+
z = 'a'
|
| 313 |
+
if isinstance(z, int):
|
| 314 |
+
return True
|
| 315 |
+
else:
|
| 316 |
+
return False
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def invalid_isinstance_usecase_phi_nopropagate2(a):
|
| 320 |
+
# Numba issue #9125
|
| 321 |
+
x = 0
|
| 322 |
+
if isinstance(a, int):
|
| 323 |
+
a = (a, a)
|
| 324 |
+
|
| 325 |
+
for i in range(len(a)):
|
| 326 |
+
x += i
|
| 327 |
+
return x
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def invalid_isinstance_optional_usecase(x):
|
| 331 |
+
if x > 4:
|
| 332 |
+
z = 10
|
| 333 |
+
else:
|
| 334 |
+
z = None
|
| 335 |
+
if isinstance(z, int):
|
| 336 |
+
return True
|
| 337 |
+
else:
|
| 338 |
+
return False
|
| 339 |
+
|
| 340 |
+
def invalid_isinstance_unsupported_type_usecase():
|
| 341 |
+
ntpl = namedtuple('ntpl', ['a', 'b'])
|
| 342 |
+
inst = ntpl(1, 2)
|
| 343 |
+
def impl(x):
|
| 344 |
+
return isinstance(inst, ntpl)
|
| 345 |
+
return impl
|
| 346 |
+
|
| 347 |
+
class TestBuiltins(TestCase):
|
| 348 |
+
|
| 349 |
+
def run_nullary_func(self, pyfunc, flags):
|
| 350 |
+
cfunc = jit((), **flags)(pyfunc)
|
| 351 |
+
expected = pyfunc()
|
| 352 |
+
self.assertPreciseEqual(cfunc(), expected)
|
| 353 |
+
|
| 354 |
+
def test_abs(self, flags=forceobj_flags):
|
| 355 |
+
pyfunc = abs_usecase
|
| 356 |
+
|
| 357 |
+
cfunc = jit((types.int32,), **flags)(pyfunc)
|
| 358 |
+
for x in [-1, 0, 1]:
|
| 359 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 360 |
+
|
| 361 |
+
cfunc = jit((types.float32,), **flags)(pyfunc)
|
| 362 |
+
for x in [-1.1, 0.0, 1.1]:
|
| 363 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single')
|
| 364 |
+
|
| 365 |
+
complex_values = [-1.1 + 0.5j, 0.0 + 0j, 1.1 + 3j,
|
| 366 |
+
float('inf') + 1j * float('nan'),
|
| 367 |
+
float('nan') - 1j * float('inf')]
|
| 368 |
+
cfunc = jit((types.complex64,), **flags)(pyfunc)
|
| 369 |
+
for x in complex_values:
|
| 370 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single')
|
| 371 |
+
cfunc = jit((types.complex128,), **flags)(pyfunc)
|
| 372 |
+
for x in complex_values:
|
| 373 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 374 |
+
|
| 375 |
+
for unsigned_type in types.unsigned_domain:
|
| 376 |
+
unsigned_values = [0, 10, 2, 2 ** unsigned_type.bitwidth - 1]
|
| 377 |
+
cfunc = jit((unsigned_type,), **flags)(pyfunc)
|
| 378 |
+
for x in unsigned_values:
|
| 379 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 380 |
+
|
| 381 |
+
def test_abs_npm(self):
|
| 382 |
+
self.test_abs(flags=no_pyobj_flags)
|
| 383 |
+
|
| 384 |
+
def test_all(self, flags=forceobj_flags):
|
| 385 |
+
pyfunc = all_usecase
|
| 386 |
+
|
| 387 |
+
cfunc = jit((types.int32,types.int32), **flags)(pyfunc)
|
| 388 |
+
x_operands = [-1, 0, 1, None]
|
| 389 |
+
y_operands = [-1, 0, 1, None]
|
| 390 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 391 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 392 |
+
|
| 393 |
+
def test_all_npm(self):
|
| 394 |
+
with self.assertTypingError():
|
| 395 |
+
self.test_all(flags=no_pyobj_flags)
|
| 396 |
+
|
| 397 |
+
def test_any(self, flags=forceobj_flags):
|
| 398 |
+
pyfunc = any_usecase
|
| 399 |
+
|
| 400 |
+
cfunc = jit((types.int32,types.int32), **flags)(pyfunc)
|
| 401 |
+
x_operands = [-1, 0, 1, None]
|
| 402 |
+
y_operands = [-1, 0, 1, None]
|
| 403 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 404 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 405 |
+
|
| 406 |
+
def test_any_npm(self):
|
| 407 |
+
with self.assertTypingError():
|
| 408 |
+
self.test_any(flags=no_pyobj_flags)
|
| 409 |
+
|
| 410 |
+
def test_bool(self, flags=forceobj_flags):
|
| 411 |
+
pyfunc = bool_usecase
|
| 412 |
+
|
| 413 |
+
cfunc = jit((types.int32,), **flags)(pyfunc)
|
| 414 |
+
for x in [-1, 0, 1]:
|
| 415 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 416 |
+
cfunc = jit((types.float64,), **flags)(pyfunc)
|
| 417 |
+
for x in [0.0, -0.0, 1.5, float('inf'), float('nan')]:
|
| 418 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 419 |
+
cfunc = jit((types.complex128,), **flags)(pyfunc)
|
| 420 |
+
for x in [complex(0, float('inf')), complex(0, float('nan'))]:
|
| 421 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 422 |
+
|
| 423 |
+
def test_bool_npm(self):
|
| 424 |
+
self.test_bool(flags=no_pyobj_flags)
|
| 425 |
+
|
| 426 |
+
def test_bool_nonnumber(self, flags=forceobj_flags):
|
| 427 |
+
pyfunc = bool_usecase
|
| 428 |
+
|
| 429 |
+
cfunc = jit((types.string,), **flags)(pyfunc)
|
| 430 |
+
for x in ['x', '']:
|
| 431 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 432 |
+
|
| 433 |
+
cfunc = jit((types.Dummy('list'),), **flags)(pyfunc)
|
| 434 |
+
for x in [[1], []]:
|
| 435 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 436 |
+
|
| 437 |
+
def test_bool_nonnumber_npm(self):
|
| 438 |
+
with self.assertTypingError():
|
| 439 |
+
self.test_bool_nonnumber(flags=no_pyobj_flags)
|
| 440 |
+
|
| 441 |
+
def test_complex(self, flags=forceobj_flags):
|
| 442 |
+
pyfunc = complex_usecase
|
| 443 |
+
|
| 444 |
+
cfunc = jit((types.int32, types.int32), **flags)(pyfunc)
|
| 445 |
+
|
| 446 |
+
x_operands = [-1, 0, 1]
|
| 447 |
+
y_operands = [-1, 0, 1]
|
| 448 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 449 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 450 |
+
|
| 451 |
+
def test_complex_npm(self):
|
| 452 |
+
self.test_complex(flags=no_pyobj_flags)
|
| 453 |
+
|
| 454 |
+
def test_divmod_ints(self, flags=forceobj_flags):
|
| 455 |
+
pyfunc = divmod_usecase
|
| 456 |
+
|
| 457 |
+
cfunc = jit((types.int64, types.int64), **flags)(pyfunc)
|
| 458 |
+
|
| 459 |
+
def truncate_result(x, bits=64):
|
| 460 |
+
# Remove any extraneous bits (since Numba will return
|
| 461 |
+
# a 64-bit result by definition)
|
| 462 |
+
if x >= 0:
|
| 463 |
+
x &= (1 << (bits - 1)) - 1
|
| 464 |
+
return x
|
| 465 |
+
|
| 466 |
+
denominators = [1, 3, 7, 15, -1, -3, -7, -15, 2**63 - 1, -2**63]
|
| 467 |
+
numerators = denominators + [0]
|
| 468 |
+
for x, y, in itertools.product(numerators, denominators):
|
| 469 |
+
expected_quot, expected_rem = pyfunc(x, y)
|
| 470 |
+
quot, rem = cfunc(x, y)
|
| 471 |
+
f = truncate_result
|
| 472 |
+
self.assertPreciseEqual((f(quot), f(rem)),
|
| 473 |
+
(f(expected_quot), f(expected_rem)))
|
| 474 |
+
|
| 475 |
+
for x in numerators:
|
| 476 |
+
with self.assertRaises(ZeroDivisionError):
|
| 477 |
+
cfunc(x, 0)
|
| 478 |
+
|
| 479 |
+
def test_divmod_ints_npm(self):
|
| 480 |
+
self.test_divmod_ints(flags=no_pyobj_flags)
|
| 481 |
+
|
| 482 |
+
def test_divmod_floats(self, flags=forceobj_flags):
|
| 483 |
+
pyfunc = divmod_usecase
|
| 484 |
+
|
| 485 |
+
cfunc = jit((types.float64, types.float64), **flags)(pyfunc)
|
| 486 |
+
|
| 487 |
+
denominators = [1., 3.5, 1e100, -2., -7.5, -1e101,
|
| 488 |
+
np.inf, -np.inf, np.nan]
|
| 489 |
+
numerators = denominators + [-0.0, 0.0]
|
| 490 |
+
for x, y, in itertools.product(numerators, denominators):
|
| 491 |
+
expected_quot, expected_rem = pyfunc(x, y)
|
| 492 |
+
quot, rem = cfunc(x, y)
|
| 493 |
+
self.assertPreciseEqual((quot, rem), (expected_quot, expected_rem))
|
| 494 |
+
|
| 495 |
+
for x in numerators:
|
| 496 |
+
with self.assertRaises(ZeroDivisionError):
|
| 497 |
+
cfunc(x, 0.0)
|
| 498 |
+
|
| 499 |
+
def test_divmod_floats_npm(self):
|
| 500 |
+
self.test_divmod_floats(flags=no_pyobj_flags)
|
| 501 |
+
|
| 502 |
+
def test_enumerate(self, flags=forceobj_flags):
|
| 503 |
+
self.run_nullary_func(enumerate_usecase, flags)
|
| 504 |
+
|
| 505 |
+
def test_enumerate_npm(self):
|
| 506 |
+
self.test_enumerate(flags=no_pyobj_flags)
|
| 507 |
+
|
| 508 |
+
def test_enumerate_start(self, flags=forceobj_flags):
|
| 509 |
+
self.run_nullary_func(enumerate_start_usecase, flags)
|
| 510 |
+
|
| 511 |
+
def test_enumerate_start_npm(self):
|
| 512 |
+
self.test_enumerate_start(flags=no_pyobj_flags)
|
| 513 |
+
|
| 514 |
+
def test_enumerate_start_invalid_start_type(self):
|
| 515 |
+
pyfunc = enumerate_invalid_start_usecase
|
| 516 |
+
|
| 517 |
+
cfunc = jit((), **forceobj_flags)(pyfunc)
|
| 518 |
+
|
| 519 |
+
with self.assertRaises(TypeError) as raises:
|
| 520 |
+
cfunc()
|
| 521 |
+
|
| 522 |
+
msg = "'float' object cannot be interpreted as an integer"
|
| 523 |
+
self.assertIn(msg, str(raises.exception))
|
| 524 |
+
|
| 525 |
+
def test_enumerate_start_invalid_start_type_npm(self):
|
| 526 |
+
pyfunc = enumerate_invalid_start_usecase
|
| 527 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 528 |
+
jit((), **no_pyobj_flags)(pyfunc)
|
| 529 |
+
msg = "Only integers supported as start value in enumerate"
|
| 530 |
+
self.assertIn(msg, str(raises.exception))
|
| 531 |
+
|
| 532 |
+
def test_filter(self, flags=forceobj_flags):
|
| 533 |
+
pyfunc = filter_usecase
|
| 534 |
+
argtys = (types.Dummy('list'), types.Dummy('function_ptr'))
|
| 535 |
+
cfunc = jit(argtys, **flags)(pyfunc)
|
| 536 |
+
|
| 537 |
+
filter_func = lambda x: x % 2
|
| 538 |
+
x = [0, 1, 2, 3, 4]
|
| 539 |
+
self.assertSequenceEqual(list(cfunc(x, filter_func)),
|
| 540 |
+
list(pyfunc(x, filter_func)))
|
| 541 |
+
|
| 542 |
+
def test_filter_npm(self):
|
| 543 |
+
with self.assertTypingError():
|
| 544 |
+
self.test_filter(flags=no_pyobj_flags)
|
| 545 |
+
|
| 546 |
+
def test_float(self, flags=forceobj_flags):
|
| 547 |
+
pyfunc = float_usecase
|
| 548 |
+
|
| 549 |
+
cfunc = jit((types.int32,), **flags)(pyfunc)
|
| 550 |
+
for x in [-1, 0, 1]:
|
| 551 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 552 |
+
|
| 553 |
+
cfunc = jit((types.float32,), **flags)(pyfunc)
|
| 554 |
+
for x in [-1.1, 0.0, 1.1]:
|
| 555 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x), prec='single')
|
| 556 |
+
|
| 557 |
+
cfunc = jit((types.string,), **flags)(pyfunc)
|
| 558 |
+
for x in ['-1.1', '0.0', '1.1', 'inf', '-inf', 'INF', '-INF']:
|
| 559 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 560 |
+
|
| 561 |
+
def test_float_npm(self):
|
| 562 |
+
with self.assertTypingError():
|
| 563 |
+
self.test_float(flags=no_pyobj_flags)
|
| 564 |
+
|
| 565 |
+
def test_float_string_literal(self):
|
| 566 |
+
pyfunc = float_inf_usecase
|
| 567 |
+
cfunc = njit(pyfunc)
|
| 568 |
+
for x in range(8):
|
| 569 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 570 |
+
|
| 571 |
+
def test_format(self, flags=forceobj_flags):
|
| 572 |
+
pyfunc = format_usecase
|
| 573 |
+
|
| 574 |
+
cfunc = jit((types.string, types.int32,), **flags)(pyfunc)
|
| 575 |
+
x = '{0}'
|
| 576 |
+
for y in [-1, 0, 1]:
|
| 577 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 578 |
+
|
| 579 |
+
cfunc = jit((types.string, types.float32,), **flags)(pyfunc)
|
| 580 |
+
x = '{0}'
|
| 581 |
+
for y in [-1.1, 0.0, 1.1]:
|
| 582 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 583 |
+
|
| 584 |
+
cfunc = jit((types.string, types.string,), **flags)(pyfunc)
|
| 585 |
+
x = '{0}'
|
| 586 |
+
for y in ['a', 'b', 'c']:
|
| 587 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 588 |
+
|
| 589 |
+
def test_format_npm(self):
|
| 590 |
+
with self.assertTypingError():
|
| 591 |
+
self.test_format(flags=no_pyobj_flags)
|
| 592 |
+
|
| 593 |
+
def test_globals(self, flags=forceobj_flags):
|
| 594 |
+
pyfunc = globals_usecase
|
| 595 |
+
cfunc = jit((), **flags)(pyfunc)
|
| 596 |
+
g = cfunc()
|
| 597 |
+
self.assertIs(g, globals())
|
| 598 |
+
|
| 599 |
+
def test_globals_npm(self):
|
| 600 |
+
with self.assertTypingError():
|
| 601 |
+
self.test_globals(flags=no_pyobj_flags)
|
| 602 |
+
|
| 603 |
+
def test_globals_jit(self, flags=forceobj_flags):
|
| 604 |
+
# Issue #416: weird behaviour of globals() in combination with
|
| 605 |
+
# the @jit decorator.
|
| 606 |
+
pyfunc = globals_usecase
|
| 607 |
+
jitted = jit(**flags)(pyfunc)
|
| 608 |
+
self.assertIs(jitted(), globals())
|
| 609 |
+
self.assertIs(jitted(), globals())
|
| 610 |
+
|
| 611 |
+
def test_globals_jit_npm(self):
|
| 612 |
+
with self.assertTypingError():
|
| 613 |
+
self.test_globals_jit(nopython=True)
|
| 614 |
+
|
| 615 |
+
def test_hex(self, flags=forceobj_flags):
|
| 616 |
+
pyfunc = hex_usecase
|
| 617 |
+
|
| 618 |
+
cfunc = jit((types.int32,), **flags)(pyfunc)
|
| 619 |
+
for x in [-1, 0, 1]:
|
| 620 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 621 |
+
|
| 622 |
+
def test_hex_npm(self):
|
| 623 |
+
with self.assertTypingError():
|
| 624 |
+
self.test_hex(flags=no_pyobj_flags)
|
| 625 |
+
|
| 626 |
+
def test_int_str(self):
|
| 627 |
+
pyfunc = str_usecase
|
| 628 |
+
|
| 629 |
+
small_inputs = [
|
| 630 |
+
1234,
|
| 631 |
+
1,
|
| 632 |
+
0,
|
| 633 |
+
10,
|
| 634 |
+
1000,
|
| 635 |
+
]
|
| 636 |
+
|
| 637 |
+
large_inputs = [
|
| 638 |
+
123456789,
|
| 639 |
+
2222222,
|
| 640 |
+
1000000,
|
| 641 |
+
~0x0
|
| 642 |
+
]
|
| 643 |
+
|
| 644 |
+
args = [*small_inputs, *large_inputs]
|
| 645 |
+
|
| 646 |
+
typs = [
|
| 647 |
+
types.int8,
|
| 648 |
+
types.int16,
|
| 649 |
+
types.int32,
|
| 650 |
+
types.int64,
|
| 651 |
+
types.uint,
|
| 652 |
+
types.uint8,
|
| 653 |
+
types.uint16,
|
| 654 |
+
types.uint32,
|
| 655 |
+
types.uint64,
|
| 656 |
+
]
|
| 657 |
+
|
| 658 |
+
for typ in typs:
|
| 659 |
+
cfunc = jit((typ,), **nrt_no_pyobj_flags)(pyfunc)
|
| 660 |
+
for v in args:
|
| 661 |
+
tp_info = np.iinfo(typ.key)
|
| 662 |
+
if not (tp_info.min <= v <= tp_info.max):
|
| 663 |
+
continue
|
| 664 |
+
self.assertPreciseEqual(cfunc(typ(v)), pyfunc(typ(v)))
|
| 665 |
+
|
| 666 |
+
if typ.signed:
|
| 667 |
+
self.assertPreciseEqual(cfunc(typ(-v)), pyfunc(typ(-v)))
|
| 668 |
+
|
| 669 |
+
def test_int(self, flags=forceobj_flags):
|
| 670 |
+
pyfunc = int_usecase
|
| 671 |
+
|
| 672 |
+
cfunc = jit((types.string, types.int32,), **flags)(pyfunc)
|
| 673 |
+
|
| 674 |
+
x_operands = ['-1', '0', '1', '10']
|
| 675 |
+
y_operands = [2, 8, 10, 16]
|
| 676 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 677 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 678 |
+
|
| 679 |
+
def test_int_npm(self):
|
| 680 |
+
with self.assertTypingError():
|
| 681 |
+
self.test_int(flags=no_pyobj_flags)
|
| 682 |
+
|
| 683 |
+
def test_iter_next(self, flags=forceobj_flags):
|
| 684 |
+
pyfunc = iter_next_usecase
|
| 685 |
+
cfunc = jit((types.UniTuple(types.int32, 3),), **flags)(pyfunc)
|
| 686 |
+
self.assertPreciseEqual(cfunc((1, 42, 5)), (1, 42))
|
| 687 |
+
|
| 688 |
+
cfunc = jit((types.UniTuple(types.int32, 1),), **flags)(pyfunc)
|
| 689 |
+
with self.assertRaises(StopIteration):
|
| 690 |
+
cfunc((1,))
|
| 691 |
+
|
| 692 |
+
def test_iter_next_npm(self):
|
| 693 |
+
self.test_iter_next(flags=no_pyobj_flags)
|
| 694 |
+
|
| 695 |
+
def test_locals(self, flags=forceobj_flags):
|
| 696 |
+
pyfunc = locals_usecase
|
| 697 |
+
with self.assertRaises(errors.ForbiddenConstruct):
|
| 698 |
+
jit((types.int64,), **flags)(pyfunc)
|
| 699 |
+
|
| 700 |
+
def test_locals_forceobj(self):
|
| 701 |
+
self.test_locals(flags=forceobj_flags)
|
| 702 |
+
|
| 703 |
+
def test_locals_npm(self):
|
| 704 |
+
with self.assertTypingError():
|
| 705 |
+
self.test_locals(flags=no_pyobj_flags)
|
| 706 |
+
|
| 707 |
+
def test_map(self, flags=forceobj_flags):
|
| 708 |
+
pyfunc = map_usecase
|
| 709 |
+
argtys = (types.Dummy('list'), types.Dummy('function_ptr'))
|
| 710 |
+
cfunc = jit(argtys, **flags)(pyfunc)
|
| 711 |
+
|
| 712 |
+
map_func = lambda x: x * 2
|
| 713 |
+
x = [0, 1, 2, 3, 4]
|
| 714 |
+
self.assertSequenceEqual(list(cfunc(x, map_func)),
|
| 715 |
+
list(pyfunc(x, map_func)))
|
| 716 |
+
|
| 717 |
+
def test_map_npm(self):
|
| 718 |
+
with self.assertTypingError():
|
| 719 |
+
self.test_map(flags=no_pyobj_flags)
|
| 720 |
+
|
| 721 |
+
#
|
| 722 |
+
# min() and max()
|
| 723 |
+
#
|
| 724 |
+
|
| 725 |
+
def check_minmax_1(self, pyfunc, flags):
|
| 726 |
+
cfunc = jit((types.int32, types.int32), **flags)(pyfunc)
|
| 727 |
+
|
| 728 |
+
x_operands = [-1, 0, 1]
|
| 729 |
+
y_operands = [-1, 0, 1]
|
| 730 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 731 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 732 |
+
|
| 733 |
+
def test_max_1(self, flags=forceobj_flags):
|
| 734 |
+
"""
|
| 735 |
+
max(*args)
|
| 736 |
+
"""
|
| 737 |
+
self.check_minmax_1(max_usecase1, flags)
|
| 738 |
+
|
| 739 |
+
def test_min_1(self, flags=forceobj_flags):
|
| 740 |
+
"""
|
| 741 |
+
min(*args)
|
| 742 |
+
"""
|
| 743 |
+
self.check_minmax_1(min_usecase1, flags)
|
| 744 |
+
|
| 745 |
+
def test_max_npm_1(self):
|
| 746 |
+
self.test_max_1(flags=no_pyobj_flags)
|
| 747 |
+
|
| 748 |
+
def test_min_npm_1(self):
|
| 749 |
+
self.test_min_1(flags=no_pyobj_flags)
|
| 750 |
+
|
| 751 |
+
def check_minmax_2(self, pyfunc, flags):
|
| 752 |
+
cfunc = jit((types.int32, types.int32), **flags)(pyfunc)
|
| 753 |
+
|
| 754 |
+
x_operands = [-1, 0, 1]
|
| 755 |
+
y_operands = [-1, 0, 1]
|
| 756 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 757 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 758 |
+
|
| 759 |
+
def test_max_2(self, flags=forceobj_flags):
|
| 760 |
+
"""
|
| 761 |
+
max(list)
|
| 762 |
+
"""
|
| 763 |
+
self.check_minmax_2(max_usecase2, flags)
|
| 764 |
+
|
| 765 |
+
def test_min_2(self, flags=forceobj_flags):
|
| 766 |
+
"""
|
| 767 |
+
min(list)
|
| 768 |
+
"""
|
| 769 |
+
self.check_minmax_2(min_usecase2, flags)
|
| 770 |
+
|
| 771 |
+
def test_max_npm_2(self):
|
| 772 |
+
with self.assertTypingError():
|
| 773 |
+
self.test_max_2(flags=no_pyobj_flags)
|
| 774 |
+
|
| 775 |
+
def test_min_npm_2(self):
|
| 776 |
+
with self.assertTypingError():
|
| 777 |
+
self.test_min_2(flags=no_pyobj_flags)
|
| 778 |
+
|
| 779 |
+
def check_minmax_3(self, pyfunc, flags):
|
| 780 |
+
def check(argty):
|
| 781 |
+
cfunc = jit((argty,), **flags)(pyfunc)
|
| 782 |
+
# Check that the algorithm matches Python's with a non-total order
|
| 783 |
+
tup = (1.5, float('nan'), 2.5)
|
| 784 |
+
for val in [tup, tup[::-1]]:
|
| 785 |
+
self.assertPreciseEqual(cfunc(val), pyfunc(val))
|
| 786 |
+
|
| 787 |
+
check(types.UniTuple(types.float64, 3))
|
| 788 |
+
check(types.Tuple((types.float32, types.float64, types.float32)))
|
| 789 |
+
|
| 790 |
+
def test_max_3(self, flags=forceobj_flags):
|
| 791 |
+
"""
|
| 792 |
+
max(tuple)
|
| 793 |
+
"""
|
| 794 |
+
self.check_minmax_3(max_usecase3, flags)
|
| 795 |
+
|
| 796 |
+
def test_min_3(self, flags=forceobj_flags):
|
| 797 |
+
"""
|
| 798 |
+
min(tuple)
|
| 799 |
+
"""
|
| 800 |
+
self.check_minmax_3(min_usecase3, flags)
|
| 801 |
+
|
| 802 |
+
def test_max_npm_3(self):
|
| 803 |
+
self.test_max_3(flags=no_pyobj_flags)
|
| 804 |
+
|
| 805 |
+
def test_min_npm_3(self):
|
| 806 |
+
self.test_min_3(flags=no_pyobj_flags)
|
| 807 |
+
|
| 808 |
+
def check_min_max_invalid_types(self, pyfunc, flags=forceobj_flags):
|
| 809 |
+
cfunc = jit((types.int32, types.Dummy('list'),), **flags)(pyfunc)
|
| 810 |
+
cfunc(1, [1])
|
| 811 |
+
|
| 812 |
+
def test_max_1_invalid_types(self):
|
| 813 |
+
with self.assertRaises(TypeError):
|
| 814 |
+
self.check_min_max_invalid_types(max_usecase1)
|
| 815 |
+
|
| 816 |
+
def test_max_1_invalid_types_npm(self):
|
| 817 |
+
with self.assertTypingError():
|
| 818 |
+
self.check_min_max_invalid_types(max_usecase1, flags=no_pyobj_flags)
|
| 819 |
+
|
| 820 |
+
def test_min_1_invalid_types(self):
|
| 821 |
+
with self.assertRaises(TypeError):
|
| 822 |
+
self.check_min_max_invalid_types(min_usecase1)
|
| 823 |
+
|
| 824 |
+
def test_min_1_invalid_types_npm(self):
|
| 825 |
+
with self.assertTypingError():
|
| 826 |
+
self.check_min_max_invalid_types(min_usecase1, flags=no_pyobj_flags)
|
| 827 |
+
|
| 828 |
+
def check_minmax_bool1(self, pyfunc, flags):
|
| 829 |
+
cfunc = jit((types.bool_, types.bool_), **flags)(pyfunc)
|
| 830 |
+
|
| 831 |
+
operands = (False, True)
|
| 832 |
+
for x, y in itertools.product(operands, operands):
|
| 833 |
+
self.assertPreciseEqual(cfunc(x, y), pyfunc(x, y))
|
| 834 |
+
|
| 835 |
+
def test_max_bool1(self, flags=forceobj_flags):
|
| 836 |
+
# tests max(<booleans>)
|
| 837 |
+
self.check_minmax_bool1(max_usecase1, flags)
|
| 838 |
+
|
| 839 |
+
def test_min_bool1(self, flags=forceobj_flags):
|
| 840 |
+
# tests min(<booleans>)
|
| 841 |
+
self.check_minmax_bool1(min_usecase1, flags)
|
| 842 |
+
|
| 843 |
+
# Test that max(1) and min(1) fail
|
| 844 |
+
|
| 845 |
+
def check_min_max_unary_non_iterable(self, pyfunc, flags=forceobj_flags):
|
| 846 |
+
cfunc = jit((types.int32,), **flags)(pyfunc)
|
| 847 |
+
cfunc(1)
|
| 848 |
+
|
| 849 |
+
def test_max_unary_non_iterable(self):
|
| 850 |
+
with self.assertRaises(TypeError):
|
| 851 |
+
self.check_min_max_unary_non_iterable(max_usecase3)
|
| 852 |
+
|
| 853 |
+
def test_max_unary_non_iterable_npm(self):
|
| 854 |
+
with self.assertTypingError():
|
| 855 |
+
self.check_min_max_unary_non_iterable(max_usecase3)
|
| 856 |
+
|
| 857 |
+
def test_min_unary_non_iterable(self):
|
| 858 |
+
with self.assertRaises(TypeError):
|
| 859 |
+
self.check_min_max_unary_non_iterable(min_usecase3)
|
| 860 |
+
|
| 861 |
+
def test_min_unary_non_iterable_npm(self):
|
| 862 |
+
with self.assertTypingError():
|
| 863 |
+
self.check_min_max_unary_non_iterable(min_usecase3)
|
| 864 |
+
|
| 865 |
+
# Test that max(()) and min(()) fail
|
| 866 |
+
|
| 867 |
+
def check_min_max_empty_tuple(self, pyfunc, func_name):
|
| 868 |
+
with self.assertTypingError() as raises:
|
| 869 |
+
jit((), **no_pyobj_flags)(pyfunc)
|
| 870 |
+
self.assertIn("%s() argument is an empty tuple" % func_name,
|
| 871 |
+
str(raises.exception))
|
| 872 |
+
|
| 873 |
+
def test_max_empty_tuple(self):
|
| 874 |
+
self.check_min_max_empty_tuple(max_usecase4, "max")
|
| 875 |
+
|
| 876 |
+
def test_min_empty_tuple(self):
|
| 877 |
+
self.check_min_max_empty_tuple(min_usecase4, "min")
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def test_oct(self, flags=forceobj_flags):
|
| 881 |
+
pyfunc = oct_usecase
|
| 882 |
+
|
| 883 |
+
cfunc = jit((types.int32,), **flags)(pyfunc)
|
| 884 |
+
for x in [-8, -1, 0, 1, 8]:
|
| 885 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 886 |
+
|
| 887 |
+
def test_oct_npm(self):
|
| 888 |
+
with self.assertTypingError():
|
| 889 |
+
self.test_oct(flags=no_pyobj_flags)
|
| 890 |
+
|
| 891 |
+
def test_reduce(self, flags=forceobj_flags):
|
| 892 |
+
pyfunc = reduce_usecase
|
| 893 |
+
argtys = (types.Dummy('function_ptr'), types.Dummy('list'))
|
| 894 |
+
cfunc = jit(argtys, **flags)(pyfunc)
|
| 895 |
+
|
| 896 |
+
reduce_func = lambda x, y: x + y
|
| 897 |
+
|
| 898 |
+
x = range(10)
|
| 899 |
+
self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x))
|
| 900 |
+
|
| 901 |
+
x = [x + x/10.0 for x in range(10)]
|
| 902 |
+
self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x))
|
| 903 |
+
|
| 904 |
+
x = [complex(x, x) for x in range(10)]
|
| 905 |
+
self.assertPreciseEqual(cfunc(reduce_func, x), pyfunc(reduce_func, x))
|
| 906 |
+
|
| 907 |
+
def test_reduce_npm(self):
|
| 908 |
+
with self.assertTypingError():
|
| 909 |
+
self.test_reduce(flags=no_pyobj_flags)
|
| 910 |
+
|
| 911 |
+
def test_round1(self, flags=forceobj_flags):
|
| 912 |
+
pyfunc = round_usecase1
|
| 913 |
+
|
| 914 |
+
for tp in (types.float64, types.float32):
|
| 915 |
+
cfunc = jit((tp,), **flags)(pyfunc)
|
| 916 |
+
values = [-1.6, -1.5, -1.4, -0.5, 0.0, 0.1, 0.5, 0.6, 1.4, 1.5, 5.0]
|
| 917 |
+
values += [-0.1, -0.0]
|
| 918 |
+
for x in values:
|
| 919 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 920 |
+
|
| 921 |
+
def test_round1_npm(self):
|
| 922 |
+
self.test_round1(flags=no_pyobj_flags)
|
| 923 |
+
|
| 924 |
+
def test_round2(self, flags=forceobj_flags):
|
| 925 |
+
pyfunc = round_usecase2
|
| 926 |
+
|
| 927 |
+
for tp in (types.float64, types.float32):
|
| 928 |
+
prec = 'single' if tp is types.float32 else 'exact'
|
| 929 |
+
cfunc = jit((tp, types.int32), **flags)(pyfunc)
|
| 930 |
+
for x in [0.0, 0.1, 0.125, 0.25, 0.5, 0.75, 1.25,
|
| 931 |
+
1.5, 1.75, 2.25, 2.5, 2.75, 12.5, 15.0, 22.5]:
|
| 932 |
+
for n in (-1, 0, 1, 2):
|
| 933 |
+
self.assertPreciseEqual(cfunc(x, n), pyfunc(x, n),
|
| 934 |
+
prec=prec)
|
| 935 |
+
expected = pyfunc(-x, n)
|
| 936 |
+
self.assertPreciseEqual(cfunc(-x, n), pyfunc(-x, n),
|
| 937 |
+
prec=prec)
|
| 938 |
+
|
| 939 |
+
def test_round2_npm(self):
|
| 940 |
+
self.test_round2(flags=no_pyobj_flags)
|
| 941 |
+
|
| 942 |
+
def test_sum_objmode(self, flags=forceobj_flags):
|
| 943 |
+
pyfunc = sum_usecase
|
| 944 |
+
|
| 945 |
+
cfunc = jit((types.Dummy('list'),), **flags)(pyfunc)
|
| 946 |
+
|
| 947 |
+
x = range(10)
|
| 948 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 949 |
+
|
| 950 |
+
x = [x + x/10.0 for x in range(10)]
|
| 951 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 952 |
+
|
| 953 |
+
x = [complex(x, x) for x in range(10)]
|
| 954 |
+
self.assertPreciseEqual(cfunc(x), pyfunc(x))
|
| 955 |
+
|
| 956 |
+
def test_sum(self):
|
| 957 |
+
# In Python 3.8+ "start" can be specified as a kwarg, so test that too
|
| 958 |
+
sum_default = njit(sum_usecase)
|
| 959 |
+
sum_kwarg = njit(sum_kwarg_usecase)
|
| 960 |
+
|
| 961 |
+
@njit
|
| 962 |
+
def sum_range(sz, start=0):
|
| 963 |
+
tmp = range(sz)
|
| 964 |
+
ret = sum(tmp, start)
|
| 965 |
+
return sum(tmp, start=start), ret
|
| 966 |
+
|
| 967 |
+
ntpl = namedtuple('ntpl', ['a', 'b'])
|
| 968 |
+
|
| 969 |
+
# check call with default kwarg, start=0
|
| 970 |
+
def args():
|
| 971 |
+
yield [*range(10)]
|
| 972 |
+
yield [x + x/10.0 for x in range(10)]
|
| 973 |
+
yield [x * 1j for x in range(10)]
|
| 974 |
+
yield (1, 2, 3)
|
| 975 |
+
yield (1, 2, 3j)
|
| 976 |
+
# uints will likely end up as floats as `start` is signed, so just
|
| 977 |
+
# test mixed signed ints
|
| 978 |
+
yield (np.int64(32), np.int32(2), np.int8(3))
|
| 979 |
+
tl = typed.List(range(5))
|
| 980 |
+
yield tl
|
| 981 |
+
yield np.ones(5)
|
| 982 |
+
yield ntpl(100, 200)
|
| 983 |
+
yield ntpl(100, 200j)
|
| 984 |
+
|
| 985 |
+
for x in args():
|
| 986 |
+
self.assertPreciseEqual(sum_default(x), sum_default.py_func(x))
|
| 987 |
+
|
| 988 |
+
# Check the uint use case, as start is signed, NumPy will end up with
|
| 989 |
+
# a float result whereas Numba will end up with an int (see integer
|
| 990 |
+
# typing NBEP).
|
| 991 |
+
x = (np.uint64(32), np.uint32(2), np.uint8(3))
|
| 992 |
+
self.assertEqual(sum_default(x), sum_default.py_func(x))
|
| 993 |
+
|
| 994 |
+
# check call with changing default kwarg, start
|
| 995 |
+
def args_kws():
|
| 996 |
+
yield [*range(10)], 12
|
| 997 |
+
yield [x + x/10.0 for x in range(10)], 19j
|
| 998 |
+
yield [x * 1j for x in range(10)], -2
|
| 999 |
+
yield (1, 2, 3), 9
|
| 1000 |
+
yield (1, 2, 3j), -0
|
| 1001 |
+
# uints will likely end up as floats as `start` is signed, so just
|
| 1002 |
+
# test mixed signed ints
|
| 1003 |
+
yield (np.int64(32), np.int32(2), np.int8(3)), np.uint32(7)
|
| 1004 |
+
tl = typed.List(range(5))
|
| 1005 |
+
yield tl, 100
|
| 1006 |
+
yield np.ones((5, 5)), 10 * np.ones((5,))
|
| 1007 |
+
yield ntpl(100, 200), -50
|
| 1008 |
+
yield ntpl(100, 200j), 9
|
| 1009 |
+
|
| 1010 |
+
for x, start in args_kws():
|
| 1011 |
+
self.assertPreciseEqual(sum_kwarg(x, start=start),
|
| 1012 |
+
sum_kwarg.py_func(x, start=start))
|
| 1013 |
+
|
| 1014 |
+
# check call with range()
|
| 1015 |
+
for start in range(-3, 4):
|
| 1016 |
+
for sz in range(-3, 4):
|
| 1017 |
+
self.assertPreciseEqual(sum_range(sz, start=start),
|
| 1018 |
+
sum_range.py_func(sz, start=start))
|
| 1019 |
+
|
| 1020 |
+
def test_sum_exceptions(self):
|
| 1021 |
+
sum_default = njit(sum_usecase)
|
| 1022 |
+
sum_kwarg = njit(sum_kwarg_usecase)
|
| 1023 |
+
|
| 1024 |
+
# check start as string/bytes/bytearray is error
|
| 1025 |
+
msg = "sum() can't sum {}"
|
| 1026 |
+
|
| 1027 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1028 |
+
sum_kwarg((1, 2, 3), 'a')
|
| 1029 |
+
|
| 1030 |
+
self.assertIn(msg.format('strings'), str(raises.exception))
|
| 1031 |
+
|
| 1032 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1033 |
+
sum_kwarg((1, 2, 3), b'123')
|
| 1034 |
+
|
| 1035 |
+
self.assertIn(msg.format('bytes'), str(raises.exception))
|
| 1036 |
+
|
| 1037 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1038 |
+
sum_kwarg((1, 2, 3), bytearray(b'123'))
|
| 1039 |
+
|
| 1040 |
+
self.assertIn(msg.format('bytearray'), str(raises.exception))
|
| 1041 |
+
|
| 1042 |
+
# check invalid type has no impl
|
| 1043 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1044 |
+
sum_default('abcd')
|
| 1045 |
+
|
| 1046 |
+
self.assertIn('No implementation', str(raises.exception))
|
| 1047 |
+
|
| 1048 |
+
def test_truth(self):
|
| 1049 |
+
pyfunc = truth_usecase
|
| 1050 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1051 |
+
|
| 1052 |
+
self.assertEqual(pyfunc(True), cfunc(True))
|
| 1053 |
+
self.assertEqual(pyfunc(False), cfunc(False))
|
| 1054 |
+
|
| 1055 |
+
def test_type_unary(self):
|
| 1056 |
+
# Test type(val) and type(val)(other_val)
|
| 1057 |
+
pyfunc = type_unary_usecase
|
| 1058 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1059 |
+
|
| 1060 |
+
def check(*args):
|
| 1061 |
+
expected = pyfunc(*args)
|
| 1062 |
+
self.assertPreciseEqual(cfunc(*args), expected)
|
| 1063 |
+
|
| 1064 |
+
check(1.5, 2)
|
| 1065 |
+
check(1, 2.5)
|
| 1066 |
+
check(1.5j, 2)
|
| 1067 |
+
check(True, 2)
|
| 1068 |
+
check(2.5j, False)
|
| 1069 |
+
|
| 1070 |
+
def test_zip(self, flags=forceobj_flags):
|
| 1071 |
+
self.run_nullary_func(zip_usecase, flags)
|
| 1072 |
+
|
| 1073 |
+
def test_zip_npm(self):
|
| 1074 |
+
self.test_zip(flags=no_pyobj_flags)
|
| 1075 |
+
|
| 1076 |
+
def test_zip_1(self, flags=forceobj_flags):
|
| 1077 |
+
self.run_nullary_func(zip_1_usecase, flags)
|
| 1078 |
+
|
| 1079 |
+
def test_zip_1_npm(self):
|
| 1080 |
+
self.test_zip_1(flags=no_pyobj_flags)
|
| 1081 |
+
|
| 1082 |
+
def test_zip_3(self, flags=forceobj_flags):
|
| 1083 |
+
self.run_nullary_func(zip_3_usecase, flags)
|
| 1084 |
+
|
| 1085 |
+
def test_zip_3_npm(self):
|
| 1086 |
+
self.test_zip_3(flags=no_pyobj_flags)
|
| 1087 |
+
|
| 1088 |
+
def test_zip_0(self, flags=forceobj_flags):
|
| 1089 |
+
self.run_nullary_func(zip_0_usecase, flags)
|
| 1090 |
+
|
| 1091 |
+
def test_zip_0_npm(self):
|
| 1092 |
+
self.test_zip_0(flags=no_pyobj_flags)
|
| 1093 |
+
|
| 1094 |
+
def test_zip_first_exhausted(self, flags=forceobj_flags):
|
| 1095 |
+
"""
|
| 1096 |
+
Test side effect to the input iterators when a left iterator has been
|
| 1097 |
+
exhausted before the ones on the right.
|
| 1098 |
+
"""
|
| 1099 |
+
self.run_nullary_func(zip_first_exhausted, flags)
|
| 1100 |
+
|
| 1101 |
+
def test_zip_first_exhausted_npm(self):
|
| 1102 |
+
self.test_zip_first_exhausted(flags=nrt_no_pyobj_flags)
|
| 1103 |
+
|
| 1104 |
+
def test_pow_op_usecase(self):
|
| 1105 |
+
args = [
|
| 1106 |
+
(2, 3),
|
| 1107 |
+
(2.0, 3),
|
| 1108 |
+
(2, 3.0),
|
| 1109 |
+
(2j, 3.0j),
|
| 1110 |
+
]
|
| 1111 |
+
|
| 1112 |
+
for x, y in args:
|
| 1113 |
+
argtys = (typeof(x), typeof(y))
|
| 1114 |
+
cfunc = jit(argtys, **no_pyobj_flags)(pow_op_usecase)
|
| 1115 |
+
r = cfunc(x, y)
|
| 1116 |
+
self.assertPreciseEqual(r, pow_op_usecase(x, y))
|
| 1117 |
+
|
| 1118 |
+
def test_pow_usecase(self):
|
| 1119 |
+
args = [
|
| 1120 |
+
(2, 3),
|
| 1121 |
+
(2.0, 3),
|
| 1122 |
+
(2, 3.0),
|
| 1123 |
+
(2j, 3.0j),
|
| 1124 |
+
]
|
| 1125 |
+
|
| 1126 |
+
for x, y in args:
|
| 1127 |
+
argtys = (typeof(x), typeof(y))
|
| 1128 |
+
cfunc = jit(argtys, **no_pyobj_flags)(pow_usecase)
|
| 1129 |
+
r = cfunc(x, y)
|
| 1130 |
+
self.assertPreciseEqual(r, pow_usecase(x, y))
|
| 1131 |
+
|
| 1132 |
+
def _check_min_max(self, pyfunc):
|
| 1133 |
+
cfunc = njit()(pyfunc)
|
| 1134 |
+
expected = pyfunc()
|
| 1135 |
+
got = cfunc()
|
| 1136 |
+
self.assertPreciseEqual(expected, got)
|
| 1137 |
+
|
| 1138 |
+
def test_min_max_iterable_input(self):
|
| 1139 |
+
|
| 1140 |
+
@njit
|
| 1141 |
+
def frange(start, stop, step):
|
| 1142 |
+
i = start
|
| 1143 |
+
while i < stop:
|
| 1144 |
+
yield i
|
| 1145 |
+
i += step
|
| 1146 |
+
|
| 1147 |
+
def sample_functions(op):
|
| 1148 |
+
yield lambda: op(range(10))
|
| 1149 |
+
yield lambda: op(range(4, 12))
|
| 1150 |
+
yield lambda: op(range(-4, -15, -1))
|
| 1151 |
+
yield lambda: op([6.6, 5.5, 7.7])
|
| 1152 |
+
yield lambda: op([(3, 4), (1, 2)])
|
| 1153 |
+
yield lambda: op(frange(1.1, 3.3, 0.1))
|
| 1154 |
+
yield lambda: op([np.nan, -np.inf, np.inf, np.nan])
|
| 1155 |
+
yield lambda: op([(3,), (1,), (2,)])
|
| 1156 |
+
|
| 1157 |
+
for fn in sample_functions(op=min):
|
| 1158 |
+
self._check_min_max(fn)
|
| 1159 |
+
|
| 1160 |
+
for fn in sample_functions(op=max):
|
| 1161 |
+
self._check_min_max(fn)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class TestOperatorMixedTypes(TestCase):
|
| 1165 |
+
|
| 1166 |
+
def test_eq_ne(self):
|
| 1167 |
+
for opstr in ('eq', 'ne'):
|
| 1168 |
+
op = getattr(operator, opstr)
|
| 1169 |
+
|
| 1170 |
+
@njit
|
| 1171 |
+
def func(a, b):
|
| 1172 |
+
return op(a, b)
|
| 1173 |
+
|
| 1174 |
+
# all these things should evaluate to being equal or not, all should
|
| 1175 |
+
# survive typing.
|
| 1176 |
+
things = (1, 0, True, False, 1.0, 2.0, 1.1, 1j, None, "", "1")
|
| 1177 |
+
for x, y in itertools.product(things, things):
|
| 1178 |
+
self.assertPreciseEqual(func.py_func(x, y), func(x, y))
|
| 1179 |
+
|
| 1180 |
+
def test_cmp(self):
|
| 1181 |
+
for opstr in ('gt', 'lt', 'ge', 'le', 'eq', 'ne'):
|
| 1182 |
+
op = getattr(operator, opstr)
|
| 1183 |
+
@njit
|
| 1184 |
+
def func(a, b):
|
| 1185 |
+
return op(a, b)
|
| 1186 |
+
|
| 1187 |
+
# numerical things should all be comparable
|
| 1188 |
+
things = (1, 0, True, False, 1.0, 0.0, 1.1)
|
| 1189 |
+
for x, y in itertools.product(things, things):
|
| 1190 |
+
expected = func.py_func(x, y)
|
| 1191 |
+
got = func(x, y)
|
| 1192 |
+
message = ("%s %s %s does not match between Python and Numba"
|
| 1193 |
+
% (x, opstr, y))
|
| 1194 |
+
self.assertEqual(expected, got, message)
|
| 1195 |
+
|
| 1196 |
+
|
| 1197 |
+
class TestIsinstanceBuiltin(TestCase):
|
| 1198 |
+
def test_isinstance(self):
|
| 1199 |
+
pyfunc = isinstance_usecase
|
| 1200 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1201 |
+
|
| 1202 |
+
inputs = (
|
| 1203 |
+
3, # int
|
| 1204 |
+
5.0, # float
|
| 1205 |
+
"Hello", # string
|
| 1206 |
+
b'world', # bytes
|
| 1207 |
+
1j, # complex
|
| 1208 |
+
[1, 2, 3], # list
|
| 1209 |
+
(1, 3, 3, 3), # UniTuple
|
| 1210 |
+
set([1, 2]), # set
|
| 1211 |
+
(1, 'nba', 2), # Heterogeneous Tuple
|
| 1212 |
+
# {'hello': 2}, # dict - doesn't work as input
|
| 1213 |
+
None,
|
| 1214 |
+
)
|
| 1215 |
+
|
| 1216 |
+
for inpt in inputs:
|
| 1217 |
+
expected = pyfunc(inpt)
|
| 1218 |
+
got = cfunc(inpt)
|
| 1219 |
+
self.assertEqual(expected, got)
|
| 1220 |
+
|
| 1221 |
+
def test_isinstance_dict(self):
|
| 1222 |
+
# Tests typed.Dict and LiteralStrKeyDict
|
| 1223 |
+
pyfunc = isinstance_dict
|
| 1224 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1225 |
+
self.assertEqual(pyfunc(), cfunc())
|
| 1226 |
+
|
| 1227 |
+
def test_isinstance_issue9125(self):
|
| 1228 |
+
pyfunc = invalid_isinstance_usecase_phi_nopropagate2
|
| 1229 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1230 |
+
self.assertEqual(pyfunc(3), cfunc(3))
|
| 1231 |
+
|
| 1232 |
+
def test_isinstance_numba_types(self):
|
| 1233 |
+
# This makes use of type aliasing between python scalars and NumPy
|
| 1234 |
+
# scalars, see also test_numba_types()
|
| 1235 |
+
pyfunc = isinstance_usecase_numba_types
|
| 1236 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1237 |
+
|
| 1238 |
+
inputs = (
|
| 1239 |
+
(types.int32(1), 'int32'),
|
| 1240 |
+
(types.int64(2), 'int64'),
|
| 1241 |
+
(types.float32(3.0), 'float32'),
|
| 1242 |
+
(types.float64(4.0), 'float64'),
|
| 1243 |
+
(types.complex64(5j), 'no match'),
|
| 1244 |
+
(typed.List([1, 2]), 'typed list'),
|
| 1245 |
+
(typed.Dict.empty(types.int64, types.int64), 'typed dict')
|
| 1246 |
+
)
|
| 1247 |
+
|
| 1248 |
+
for inpt, expected in inputs:
|
| 1249 |
+
got = cfunc(inpt)
|
| 1250 |
+
self.assertEqual(expected, got)
|
| 1251 |
+
|
| 1252 |
+
def test_isinstance_numba_types_2(self):
|
| 1253 |
+
pyfunc = isinstance_usecase_numba_types_2
|
| 1254 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1255 |
+
self.assertEqual(pyfunc(), cfunc())
|
| 1256 |
+
|
| 1257 |
+
def test_isinstance_invalid_type(self):
|
| 1258 |
+
pyfunc = isinstance_usecase_invalid_type
|
| 1259 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 1260 |
+
|
| 1261 |
+
# valid type
|
| 1262 |
+
self.assertTrue(cfunc(3.4))
|
| 1263 |
+
|
| 1264 |
+
# invalid type
|
| 1265 |
+
msg = 'Cannot infer numba type of python type'
|
| 1266 |
+
|
| 1267 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1268 |
+
cfunc(100)
|
| 1269 |
+
|
| 1270 |
+
self.assertIn(msg, str(raises.exception))
|
| 1271 |
+
|
| 1272 |
+
def test_isinstance_exceptions(self):
|
| 1273 |
+
fns = [
|
| 1274 |
+
(invalid_isinstance_usecase,
|
| 1275 |
+
'Cannot infer numba type of python type'),
|
| 1276 |
+
(invalid_isinstance_usecase_phi_nopropagate,
|
| 1277 |
+
('isinstance() cannot determine the type of variable "z" due to a '
|
| 1278 |
+
'branch.')),
|
| 1279 |
+
(invalid_isinstance_optional_usecase,
|
| 1280 |
+
('isinstance() cannot determine the type of variable "z" due to a '
|
| 1281 |
+
'branch.')),
|
| 1282 |
+
(invalid_isinstance_unsupported_type_usecase(),
|
| 1283 |
+
('isinstance() does not support variables of type "ntpl(')),
|
| 1284 |
+
]
|
| 1285 |
+
|
| 1286 |
+
for fn, msg in fns:
|
| 1287 |
+
fn = njit(fn)
|
| 1288 |
+
|
| 1289 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1290 |
+
fn(100)
|
| 1291 |
+
|
| 1292 |
+
self.assertIn(msg, str(raises.exception))
|
| 1293 |
+
|
| 1294 |
+
def test_combinations(self):
|
| 1295 |
+
# Combinatorically test common classes and instances
|
| 1296 |
+
def gen_w_arg(clazz_type):
|
| 1297 |
+
def impl(x):
|
| 1298 |
+
return isinstance(x, clazz_type)
|
| 1299 |
+
return impl
|
| 1300 |
+
|
| 1301 |
+
clazz_types = (int, float, complex, str, list, tuple, bytes, set, range,
|
| 1302 |
+
np.int8, np.float32,)
|
| 1303 |
+
instances = (1, 2.3, 4j, '5', [6,], (7,), b'8', {9,}, None,
|
| 1304 |
+
(10, 11, 12), (13, 'a', 14j), np.array([15, 16, 17]),
|
| 1305 |
+
np.int8(18), np.float32(19),
|
| 1306 |
+
typed.Dict.empty(types.unicode_type, types.float64),
|
| 1307 |
+
typed.List.empty_list(types.complex128), np.ones(4))
|
| 1308 |
+
|
| 1309 |
+
for ct in clazz_types:
|
| 1310 |
+
fn = njit(gen_w_arg(ct))
|
| 1311 |
+
for x in instances:
|
| 1312 |
+
expected = fn.py_func(x)
|
| 1313 |
+
got = fn(x)
|
| 1314 |
+
self.assertEqual(got, expected)
|
| 1315 |
+
|
| 1316 |
+
def test_numba_types(self):
|
| 1317 |
+
# Check types which are Numba types, this would break without the jit
|
| 1318 |
+
# decorator in all cases except numba.typed containers.
|
| 1319 |
+
def gen_w_arg(clazz_type):
|
| 1320 |
+
def impl():
|
| 1321 |
+
return isinstance(1, clazz_type)
|
| 1322 |
+
return impl
|
| 1323 |
+
|
| 1324 |
+
clazz_types = (types.Integer, types.Float, types.Array,)
|
| 1325 |
+
|
| 1326 |
+
msg = "Numba type classes.*are not supported"
|
| 1327 |
+
for ct in clazz_types:
|
| 1328 |
+
fn = njit(gen_w_arg(ct))
|
| 1329 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1330 |
+
fn()
|
| 1331 |
+
self.assertRegex(str(raises.exception), msg)
|
| 1332 |
+
|
| 1333 |
+
def test_python_numpy_scalar_alias_problem(self):
|
| 1334 |
+
# There's a problem due to Python and NumPy scalars being aliased in the
|
| 1335 |
+
# type system. This is because e.g. int scalar values and NumPy np.intp
|
| 1336 |
+
# type alias to types.intp. This test merely records this fact.
|
| 1337 |
+
|
| 1338 |
+
@njit
|
| 1339 |
+
def foo():
|
| 1340 |
+
return isinstance(np.intp(10), int)
|
| 1341 |
+
|
| 1342 |
+
self.assertEqual(foo(), True)
|
| 1343 |
+
self.assertEqual(foo.py_func(), False)
|
| 1344 |
+
|
| 1345 |
+
@njit
|
| 1346 |
+
def bar():
|
| 1347 |
+
return isinstance(1, np.intp)
|
| 1348 |
+
|
| 1349 |
+
self.assertEqual(bar(), True)
|
| 1350 |
+
self.assertEqual(bar.py_func(), False)
|
| 1351 |
+
|
| 1352 |
+
def test_branch_prune(self):
|
| 1353 |
+
# Check that isinstance branches are pruned allowing otherwise
|
| 1354 |
+
# impossible type specific specialisation.
|
| 1355 |
+
|
| 1356 |
+
@njit
|
| 1357 |
+
def foo(x):
|
| 1358 |
+
if isinstance(x, str):
|
| 1359 |
+
return x + 'some_string'
|
| 1360 |
+
elif isinstance(x, complex):
|
| 1361 |
+
return np.imag(x)
|
| 1362 |
+
elif isinstance(x, tuple):
|
| 1363 |
+
return len(x)
|
| 1364 |
+
else:
|
| 1365 |
+
assert 0
|
| 1366 |
+
|
| 1367 |
+
for x in ('string', 1 + 2j, ('a', 3, 4j)):
|
| 1368 |
+
expected = foo.py_func(x)
|
| 1369 |
+
got = foo(x)
|
| 1370 |
+
self.assertEqual(got, expected)
|
| 1371 |
+
|
| 1372 |
+
def test_branch_prune_and_bind_to_sig(self):
|
| 1373 |
+
# see issue 9795
|
| 1374 |
+
@register_jitable
|
| 1375 |
+
def f(x, y):
|
| 1376 |
+
return x + y
|
| 1377 |
+
|
| 1378 |
+
@njit
|
| 1379 |
+
def call_f(x):
|
| 1380 |
+
if isinstance(x, tuple):
|
| 1381 |
+
return f(*x)
|
| 1382 |
+
else:
|
| 1383 |
+
return f(x)
|
| 1384 |
+
|
| 1385 |
+
# The issue is that without isinstance and branch pruning working
|
| 1386 |
+
# correctly, an attempt will be made to bind the function `f` with
|
| 1387 |
+
# argument `x`. If `x` is a Tuple type, this will fail on the `else`
|
| 1388 |
+
# branch as `f` takes two arguments opposed to one.
|
| 1389 |
+
x = (1, 2)
|
| 1390 |
+
self.assertEqual(call_f(x), call_f.py_func(x))
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
# This should raise as partial type inference and branch pruning will
|
| 1394 |
+
# remove the `f(*x)` branch and just leave `f(x)`, which then won't
|
| 1395 |
+
# bind because `f` takes two arguments and only one is supplied.
|
| 1396 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1397 |
+
call_f(1)
|
| 1398 |
+
|
| 1399 |
+
msg = str(raises.exception)
|
| 1400 |
+
self.assertIn("Cannot bind", msg)
|
| 1401 |
+
self.assertIn("TypeError: missing a required argument: 'y'", msg)
|
| 1402 |
+
|
| 1403 |
+
def test_branch_prune_non_tuples_as_star_arg(self):
|
| 1404 |
+
|
| 1405 |
+
# see issue 9795
|
| 1406 |
+
@register_jitable
|
| 1407 |
+
def f(x, y):
|
| 1408 |
+
return x + y
|
| 1409 |
+
|
| 1410 |
+
@register_jitable
|
| 1411 |
+
def g(x):
|
| 1412 |
+
return x
|
| 1413 |
+
|
| 1414 |
+
@njit
|
| 1415 |
+
def call_f(x):
|
| 1416 |
+
if isinstance(x, tuple):
|
| 1417 |
+
return f(*x)
|
| 1418 |
+
else:
|
| 1419 |
+
return g(x)
|
| 1420 |
+
|
| 1421 |
+
# The issue is that without isinstance and branch pruning working
|
| 1422 |
+
# correctly, an attempt will be made to bind the function `f` with
|
| 1423 |
+
# argument `x`. If `x` is a non-tuple type `*x` will not bind to the
|
| 1424 |
+
# signature of `f`.
|
| 1425 |
+
x = 1
|
| 1426 |
+
self.assertEqual(call_f(x), call_f.py_func(x))
|
| 1427 |
+
|
| 1428 |
+
def test_branch_prune_literal_as_star_arg(self):
|
| 1429 |
+
|
| 1430 |
+
# see issue 9795
|
| 1431 |
+
@register_jitable
|
| 1432 |
+
def f(x, y):
|
| 1433 |
+
return x + y
|
| 1434 |
+
|
| 1435 |
+
@register_jitable
|
| 1436 |
+
def g(x):
|
| 1437 |
+
return x
|
| 1438 |
+
|
| 1439 |
+
one = 1
|
| 1440 |
+
@njit
|
| 1441 |
+
def call_f():
|
| 1442 |
+
x = one
|
| 1443 |
+
if isinstance(x, tuple):
|
| 1444 |
+
return f(*x)
|
| 1445 |
+
else:
|
| 1446 |
+
return g(x)
|
| 1447 |
+
|
| 1448 |
+
# The issue is that without isinstance and branch pruning working
|
| 1449 |
+
# correctly, an attempt will be made to bind the function `f` with
|
| 1450 |
+
# argument `x`. If `x` is a non-tuple const value type `*x` will not
|
| 1451 |
+
# bind to the signature of `f`.
|
| 1452 |
+
self.assertEqual(call_f(), call_f.py_func())
|
| 1453 |
+
|
| 1454 |
+
|
| 1455 |
+
class TestGetattrBuiltin(MemoryLeakMixin, TestCase):
|
| 1456 |
+
# Tests the getattr() builtin
|
| 1457 |
+
|
| 1458 |
+
def test_getattr_func_retty(self):
|
| 1459 |
+
|
| 1460 |
+
@njit
|
| 1461 |
+
def foo(x):
|
| 1462 |
+
attr = getattr(x, '__hash__')
|
| 1463 |
+
return attr()
|
| 1464 |
+
|
| 1465 |
+
for x in (1, 2.34, (5, 6, 7)):
|
| 1466 |
+
self.assertPreciseEqual(foo(x), foo.py_func(x))
|
| 1467 |
+
|
| 1468 |
+
def test_getattr_value_retty(self):
|
| 1469 |
+
|
| 1470 |
+
@njit
|
| 1471 |
+
def foo(x):
|
| 1472 |
+
return getattr(x, 'ndim')
|
| 1473 |
+
|
| 1474 |
+
for x in range(3):
|
| 1475 |
+
tmp = np.empty((1, ) * x)
|
| 1476 |
+
self.assertPreciseEqual(foo(tmp), foo.py_func(tmp))
|
| 1477 |
+
|
| 1478 |
+
def test_getattr_module_obj(self):
|
| 1479 |
+
# Consts on modules work ok
|
| 1480 |
+
|
| 1481 |
+
@njit
|
| 1482 |
+
def foo():
|
| 1483 |
+
return getattr(np, 'pi')
|
| 1484 |
+
|
| 1485 |
+
self.assertPreciseEqual(foo(), foo.py_func())
|
| 1486 |
+
|
| 1487 |
+
def test_getattr_module_obj_not_implemented(self):
|
| 1488 |
+
# Functions on modules do not work at present
|
| 1489 |
+
|
| 1490 |
+
@njit
|
| 1491 |
+
def foo():
|
| 1492 |
+
return getattr(np, 'cos')(1)
|
| 1493 |
+
|
| 1494 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1495 |
+
foo()
|
| 1496 |
+
|
| 1497 |
+
msg = "Returning function objects is not implemented"
|
| 1498 |
+
self.assertIn(msg, str(raises.exception))
|
| 1499 |
+
|
| 1500 |
+
def test_getattr_raises_attribute_error(self):
|
| 1501 |
+
|
| 1502 |
+
invalid_attr = '__not_a_valid_attr__'
|
| 1503 |
+
|
| 1504 |
+
@njit
|
| 1505 |
+
def foo(x):
|
| 1506 |
+
return getattr(x, invalid_attr)
|
| 1507 |
+
|
| 1508 |
+
with self.assertRaises(AttributeError) as raises:
|
| 1509 |
+
foo(1.23)
|
| 1510 |
+
|
| 1511 |
+
self.assertIn(f"'float64' has no attribute '{invalid_attr}'",
|
| 1512 |
+
str(raises.exception))
|
| 1513 |
+
|
| 1514 |
+
def test_getattr_with_default(self):
|
| 1515 |
+
# Checks returning a default works
|
| 1516 |
+
|
| 1517 |
+
@njit
|
| 1518 |
+
def foo(x, default):
|
| 1519 |
+
return getattr(x, '__not_a_valid_attr__', default)
|
| 1520 |
+
|
| 1521 |
+
for x, y in zip((1, 2.34, (5, 6, 7),), (None, 20, 'some_string')):
|
| 1522 |
+
self.assertPreciseEqual(foo(x, y), foo.py_func(x, y))
|
| 1523 |
+
|
| 1524 |
+
def test_getattr_non_literal_str(self):
|
| 1525 |
+
|
| 1526 |
+
@njit
|
| 1527 |
+
def foo(x, nonliteral_str):
|
| 1528 |
+
return getattr(x, nonliteral_str)
|
| 1529 |
+
|
| 1530 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1531 |
+
foo(1, '__hash__')
|
| 1532 |
+
|
| 1533 |
+
msg = "argument 'name' must be a literal string"
|
| 1534 |
+
self.assertIn(msg, str(raises.exception))
|
| 1535 |
+
|
| 1536 |
+
def test_getattr_no_optional_type_generated(self):
|
| 1537 |
+
|
| 1538 |
+
@njit
|
| 1539 |
+
def default_hash():
|
| 1540 |
+
return 12345
|
| 1541 |
+
|
| 1542 |
+
@njit
|
| 1543 |
+
def foo():
|
| 1544 |
+
hash_func = getattr(np.ones(1), "__not_a_valid_attr__",
|
| 1545 |
+
default_hash)
|
| 1546 |
+
return hash_func() # Optionals have no call support
|
| 1547 |
+
|
| 1548 |
+
self.assertPreciseEqual(foo(), foo.py_func())
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
class TestHasattrBuiltin(MemoryLeakMixin, TestCase):
|
| 1552 |
+
# Tests the hasattr() builtin
|
| 1553 |
+
|
| 1554 |
+
def test_hasattr(self):
|
| 1555 |
+
|
| 1556 |
+
@njit
|
| 1557 |
+
def foo(x):
|
| 1558 |
+
return hasattr(x, '__hash__'), hasattr(x, '__not_a_valid_attr__')
|
| 1559 |
+
|
| 1560 |
+
ty = types.int64
|
| 1561 |
+
for x in (1, 2.34, (5, 6, 7), typed.Dict.empty(ty, ty),
|
| 1562 |
+
typed.List.empty_list(ty), np.ones(4), 'ABC'):
|
| 1563 |
+
self.assertPreciseEqual(foo(x), foo.py_func(x))
|
| 1564 |
+
|
| 1565 |
+
def test_hasattr_non_const_attr(self):
|
| 1566 |
+
# This tests that an error is raised in the case that a hasattr() call
|
| 1567 |
+
# is made on an attribute that cannot be resolved as a compile time
|
| 1568 |
+
# constant (there's a phi in the way!).
|
| 1569 |
+
|
| 1570 |
+
@njit
|
| 1571 |
+
def foo(pred):
|
| 1572 |
+
if pred > 3:
|
| 1573 |
+
attr = "__hash__"
|
| 1574 |
+
else:
|
| 1575 |
+
attr = "__str__"
|
| 1576 |
+
|
| 1577 |
+
hasattr(1, attr)
|
| 1578 |
+
|
| 1579 |
+
with self.assertRaises(errors.NumbaTypeError) as raises:
|
| 1580 |
+
foo(6)
|
| 1581 |
+
|
| 1582 |
+
msg = ('hasattr() cannot determine the type of variable '
|
| 1583 |
+
'"attr" due to a branch.')
|
| 1584 |
+
self.assertIn(msg, str(raises.exception))
|
| 1585 |
+
|
| 1586 |
+
|
| 1587 |
+
class TestStrAndReprBuiltin(MemoryLeakMixin, TestCase):
|
| 1588 |
+
|
| 1589 |
+
def test_str_default(self):
|
| 1590 |
+
|
| 1591 |
+
@njit
|
| 1592 |
+
def foo():
|
| 1593 |
+
return str()
|
| 1594 |
+
|
| 1595 |
+
self.assertEqual(foo(), foo.py_func())
|
| 1596 |
+
|
| 1597 |
+
def test_str_object_kwarg(self):
|
| 1598 |
+
|
| 1599 |
+
@njit
|
| 1600 |
+
def foo(x):
|
| 1601 |
+
return str(object=x)
|
| 1602 |
+
|
| 1603 |
+
value = "a string"
|
| 1604 |
+
self.assertEqual(foo(value), foo.py_func(value))
|
| 1605 |
+
|
| 1606 |
+
def test_str_calls_dunder_str(self):
|
| 1607 |
+
|
| 1608 |
+
@njit
|
| 1609 |
+
def foo(x):
|
| 1610 |
+
return str(x)
|
| 1611 |
+
|
| 1612 |
+
Dummy, DummyType = self.make_dummy_type()
|
| 1613 |
+
dummy = Dummy()
|
| 1614 |
+
string_repr = "this is the dummy object str"
|
| 1615 |
+
Dummy.__str__= lambda inst: string_repr
|
| 1616 |
+
|
| 1617 |
+
@overload_method(DummyType, "__str__")
|
| 1618 |
+
def ol_dummy_string(dummy):
|
| 1619 |
+
def impl(dummy):
|
| 1620 |
+
return string_repr
|
| 1621 |
+
return impl
|
| 1622 |
+
|
| 1623 |
+
@overload_method(DummyType, "__repr__")
|
| 1624 |
+
def ol_dummy_repr(dummy):
|
| 1625 |
+
def impl(dummy):
|
| 1626 |
+
return "SHOULD NOT BE CALLED"
|
| 1627 |
+
return impl
|
| 1628 |
+
|
| 1629 |
+
self.assertEqual(foo(dummy), foo.py_func(dummy))
|
| 1630 |
+
|
| 1631 |
+
def test_str_falls_back_to_repr(self):
|
| 1632 |
+
|
| 1633 |
+
@njit
|
| 1634 |
+
def foo(x):
|
| 1635 |
+
return str(x)
|
| 1636 |
+
|
| 1637 |
+
Dummy, DummyType = self.make_dummy_type()
|
| 1638 |
+
dummy = Dummy()
|
| 1639 |
+
string_repr = "this is the dummy object repr"
|
| 1640 |
+
Dummy.__repr__= lambda inst: string_repr
|
| 1641 |
+
|
| 1642 |
+
@overload_method(DummyType, "__repr__")
|
| 1643 |
+
def ol_dummy_repr(dummy):
|
| 1644 |
+
def impl(dummy):
|
| 1645 |
+
return string_repr
|
| 1646 |
+
return impl
|
| 1647 |
+
|
| 1648 |
+
self.assertEqual(foo(dummy), foo.py_func(dummy))
|
| 1649 |
+
|
| 1650 |
+
def test_repr(self):
|
| 1651 |
+
@njit
|
| 1652 |
+
def foo(x):
|
| 1653 |
+
return repr(x), x
|
| 1654 |
+
|
| 1655 |
+
for x in ("abc", False, 123):
|
| 1656 |
+
self.assertEqual(foo(x), foo.py_func(x))
|
| 1657 |
+
|
| 1658 |
+
def test_repr_fallback(self):
|
| 1659 |
+
# checks str/repr fallback, there's no overloaded __str__ or __repr__
|
| 1660 |
+
# for the dummy type so it has to use generic '<object type:(type)>'
|
| 1661 |
+
# string for the `repr` call.
|
| 1662 |
+
|
| 1663 |
+
Dummy, DummyType = self.make_dummy_type()
|
| 1664 |
+
dummy = Dummy()
|
| 1665 |
+
string_repr = f"<object type:{typeof(dummy)}>"
|
| 1666 |
+
Dummy.__repr__= lambda inst: string_repr
|
| 1667 |
+
|
| 1668 |
+
@box(DummyType)
|
| 1669 |
+
def box_dummy(typ, obj, c):
|
| 1670 |
+
clazobj = c.pyapi.unserialize(c.pyapi.serialize_object(Dummy))
|
| 1671 |
+
return c.pyapi.call_function_objargs(clazobj, ())
|
| 1672 |
+
|
| 1673 |
+
@njit
|
| 1674 |
+
def foo(x):
|
| 1675 |
+
return str(x)
|
| 1676 |
+
|
| 1677 |
+
self.assertEqual(foo(dummy), foo.py_func(dummy))
|
| 1678 |
+
|
| 1679 |
+
|
| 1680 |
+
|
| 1681 |
+
if __name__ == '__main__':
|
| 1682 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_cffi.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import array
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
from numba import jit, njit
|
| 5 |
+
import numba.core.typing.cffi_utils as cffi_support
|
| 6 |
+
from numba.core import types, errors
|
| 7 |
+
from numba.tests.support import TestCase, skip_unless_cffi
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
import numba.tests.cffi_usecases as mod
|
| 11 |
+
import unittest
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
enable_pyobj_flags = {'forceobj': True}
|
| 15 |
+
no_pyobj_flags = {'nopython': True}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@skip_unless_cffi
|
| 19 |
+
class TestCFFI(TestCase):
|
| 20 |
+
|
| 21 |
+
# Need to run the tests serially because of race conditions in
|
| 22 |
+
# cffi's OOL mode.
|
| 23 |
+
_numba_parallel_test_ = False
|
| 24 |
+
|
| 25 |
+
def setUp(self):
|
| 26 |
+
mod.init()
|
| 27 |
+
mod.init_ool()
|
| 28 |
+
|
| 29 |
+
def test_type_map(self):
|
| 30 |
+
signature = cffi_support.map_type(mod.ffi.typeof(mod.cffi_sin))
|
| 31 |
+
self.assertEqual(len(signature.args), 1)
|
| 32 |
+
self.assertEqual(signature.args[0], types.double)
|
| 33 |
+
|
| 34 |
+
def _test_function(self, pyfunc, flags=enable_pyobj_flags):
|
| 35 |
+
cfunc = jit((types.double,), **flags)(pyfunc)
|
| 36 |
+
|
| 37 |
+
for x in [-1.2, -1, 0, 0.1, 3.14]:
|
| 38 |
+
self.assertPreciseEqual(pyfunc(x), cfunc(x))
|
| 39 |
+
|
| 40 |
+
def test_sin_function(self):
|
| 41 |
+
self._test_function(mod.use_cffi_sin)
|
| 42 |
+
|
| 43 |
+
def test_bool_function_ool(self):
|
| 44 |
+
pyfunc = mod.use_cffi_boolean_true
|
| 45 |
+
cfunc = njit((),)(pyfunc)
|
| 46 |
+
self.assertEqual(pyfunc(), True)
|
| 47 |
+
self.assertEqual(cfunc(), True)
|
| 48 |
+
|
| 49 |
+
def test_sin_function_npm(self):
|
| 50 |
+
self._test_function(mod.use_cffi_sin, flags=no_pyobj_flags)
|
| 51 |
+
|
| 52 |
+
def test_sin_function_ool(self, flags=enable_pyobj_flags):
|
| 53 |
+
self._test_function(mod.use_cffi_sin_ool)
|
| 54 |
+
|
| 55 |
+
def test_sin_function_npm_ool(self):
|
| 56 |
+
self._test_function(mod.use_cffi_sin_ool, flags=no_pyobj_flags)
|
| 57 |
+
|
| 58 |
+
def test_two_funcs(self):
|
| 59 |
+
# Check that two constant functions don't get mixed up.
|
| 60 |
+
self._test_function(mod.use_two_funcs)
|
| 61 |
+
|
| 62 |
+
def test_two_funcs_ool(self):
|
| 63 |
+
self._test_function(mod.use_two_funcs_ool)
|
| 64 |
+
|
| 65 |
+
def test_function_pointer(self):
|
| 66 |
+
pyfunc = mod.use_func_pointer
|
| 67 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 68 |
+
for (fa, fb, x) in [
|
| 69 |
+
(mod.cffi_sin, mod.cffi_cos, 1.0),
|
| 70 |
+
(mod.cffi_sin, mod.cffi_cos, -1.0),
|
| 71 |
+
(mod.cffi_cos, mod.cffi_sin, 1.0),
|
| 72 |
+
(mod.cffi_cos, mod.cffi_sin, -1.0),
|
| 73 |
+
(mod.cffi_sin_ool, mod.cffi_cos_ool, 1.0),
|
| 74 |
+
(mod.cffi_sin_ool, mod.cffi_cos_ool, -1.0),
|
| 75 |
+
(mod.cffi_cos_ool, mod.cffi_sin_ool, 1.0),
|
| 76 |
+
(mod.cffi_cos_ool, mod.cffi_sin_ool, -1.0),
|
| 77 |
+
(mod.cffi_sin, mod.cffi_cos_ool, 1.0),
|
| 78 |
+
(mod.cffi_sin, mod.cffi_cos_ool, -1.0),
|
| 79 |
+
(mod.cffi_cos, mod.cffi_sin_ool, 1.0),
|
| 80 |
+
(mod.cffi_cos, mod.cffi_sin_ool, -1.0)]:
|
| 81 |
+
expected = pyfunc(fa, fb, x)
|
| 82 |
+
got = cfunc(fa, fb, x)
|
| 83 |
+
self.assertEqual(got, expected)
|
| 84 |
+
# A single specialization was compiled for all calls
|
| 85 |
+
self.assertEqual(len(cfunc.overloads), 1, cfunc.overloads)
|
| 86 |
+
|
| 87 |
+
def test_user_defined_symbols(self):
|
| 88 |
+
pyfunc = mod.use_user_defined_symbols
|
| 89 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 90 |
+
self.assertEqual(pyfunc(), cfunc())
|
| 91 |
+
|
| 92 |
+
def check_vector_sin(self, cfunc, x, y):
|
| 93 |
+
cfunc(x, y)
|
| 94 |
+
np.testing.assert_allclose(y, np.sin(x))
|
| 95 |
+
|
| 96 |
+
def _test_from_buffer_numpy_array(self, pyfunc, dtype):
|
| 97 |
+
x = np.arange(10).astype(dtype)
|
| 98 |
+
y = np.zeros_like(x)
|
| 99 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 100 |
+
self.check_vector_sin(cfunc, x, y)
|
| 101 |
+
|
| 102 |
+
def test_from_buffer_float32(self):
|
| 103 |
+
self._test_from_buffer_numpy_array(mod.vector_sin_float32, np.float32)
|
| 104 |
+
|
| 105 |
+
def test_from_buffer_float64(self):
|
| 106 |
+
self._test_from_buffer_numpy_array(mod.vector_sin_float64, np.float64)
|
| 107 |
+
|
| 108 |
+
def test_from_buffer_struct(self):
|
| 109 |
+
n = 10
|
| 110 |
+
x = np.arange(n) + np.arange(n * 2, n * 3) * 1j
|
| 111 |
+
y = np.zeros(n)
|
| 112 |
+
real_cfunc = jit(nopython=True)(mod.vector_extract_real)
|
| 113 |
+
real_cfunc(x, y)
|
| 114 |
+
np.testing.assert_equal(x.real, y)
|
| 115 |
+
imag_cfunc = jit(nopython=True)(mod.vector_extract_imag)
|
| 116 |
+
imag_cfunc(x, y)
|
| 117 |
+
np.testing.assert_equal(x.imag, y)
|
| 118 |
+
|
| 119 |
+
def test_from_buffer_pyarray(self):
|
| 120 |
+
pyfunc = mod.vector_sin_float32
|
| 121 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 122 |
+
x = array.array("f", range(10))
|
| 123 |
+
y = array.array("f", [0] * len(x))
|
| 124 |
+
self.check_vector_sin(cfunc, x, y)
|
| 125 |
+
|
| 126 |
+
def test_from_buffer_error(self):
|
| 127 |
+
pyfunc = mod.vector_sin_float32
|
| 128 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 129 |
+
# Non-contiguous array
|
| 130 |
+
x = np.arange(10).astype(np.float32)[::2]
|
| 131 |
+
y = np.zeros_like(x)
|
| 132 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 133 |
+
cfunc(x, y)
|
| 134 |
+
self.assertIn("from_buffer() unsupported on non-contiguous buffers",
|
| 135 |
+
str(raises.exception))
|
| 136 |
+
|
| 137 |
+
def test_from_buffer_numpy_multi_array(self):
|
| 138 |
+
c1 = np.array([1, 2], order='C', dtype=np.float32)
|
| 139 |
+
c1_zeros = np.zeros_like(c1)
|
| 140 |
+
c2 = np.array([[1, 2], [3, 4]], order='C', dtype=np.float32)
|
| 141 |
+
c2_zeros = np.zeros_like(c2)
|
| 142 |
+
f1 = np.array([1, 2], order='F', dtype=np.float32)
|
| 143 |
+
f1_zeros = np.zeros_like(f1)
|
| 144 |
+
f2 = np.array([[1, 2], [3, 4]], order='F', dtype=np.float32)
|
| 145 |
+
f2_zeros = np.zeros_like(f2)
|
| 146 |
+
f2_copy = f2.copy('K')
|
| 147 |
+
pyfunc = mod.vector_sin_float32
|
| 148 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 149 |
+
# No exception because of C layout and single dimension
|
| 150 |
+
self.check_vector_sin(cfunc, c1, c1_zeros)
|
| 151 |
+
# No exception because of C layout
|
| 152 |
+
cfunc(c2, c2_zeros)
|
| 153 |
+
sin_c2 = np.sin(c2)
|
| 154 |
+
sin_c2[1] = [0, 0] # Reset to zero, since cfunc only processes one row
|
| 155 |
+
np.testing.assert_allclose(c2_zeros, sin_c2)
|
| 156 |
+
# No exception because of single dimension
|
| 157 |
+
self.check_vector_sin(cfunc, f1, f1_zeros)
|
| 158 |
+
# Exception because multi-dimensional with F layout
|
| 159 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 160 |
+
cfunc(f2, f2_zeros)
|
| 161 |
+
np.testing.assert_allclose(f2, f2_copy)
|
| 162 |
+
self.assertIn("from_buffer() only supports multidimensional arrays with C layout",
|
| 163 |
+
str(raises.exception))
|
| 164 |
+
|
| 165 |
+
def test_indirect_multiple_use(self):
|
| 166 |
+
"""
|
| 167 |
+
Issue #2263
|
| 168 |
+
|
| 169 |
+
Linkage error due to multiple definition of global tracking symbol.
|
| 170 |
+
"""
|
| 171 |
+
my_sin = mod.cffi_sin
|
| 172 |
+
|
| 173 |
+
# Use two jit functions that references `my_sin` to ensure multiple
|
| 174 |
+
# modules
|
| 175 |
+
@jit(nopython=True)
|
| 176 |
+
def inner(x):
|
| 177 |
+
return my_sin(x)
|
| 178 |
+
|
| 179 |
+
@jit(nopython=True)
|
| 180 |
+
def foo(x):
|
| 181 |
+
return inner(x) + my_sin(x + 1)
|
| 182 |
+
|
| 183 |
+
# Error occurs when foo is being compiled
|
| 184 |
+
x = 1.123
|
| 185 |
+
self.assertEqual(foo(x), my_sin(x) + my_sin(x + 1))
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == '__main__':
|
| 189 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_cgutils.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import ctypes
|
| 3 |
+
import struct
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
import llvmlite.ir as ir
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
import unittest
|
| 10 |
+
from numba.core import types, typing, cgutils, cpu
|
| 11 |
+
from numba.core.compiler_lock import global_compiler_lock
|
| 12 |
+
from numba.tests.support import TestCase, run_in_subprocess
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
machine_int = ir.IntType(types.intp.bitwidth)
|
| 16 |
+
|
| 17 |
+
def machine_const(n):
|
| 18 |
+
return ir.Constant(machine_int, n)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class StructureTestCase(TestCase):
|
| 22 |
+
|
| 23 |
+
def setUp(self):
|
| 24 |
+
typing_context = typing.Context()
|
| 25 |
+
self.context = cpu.CPUContext(typing_context)
|
| 26 |
+
|
| 27 |
+
@contextlib.contextmanager
|
| 28 |
+
def compile_function(self, nargs):
|
| 29 |
+
llvm_fnty = ir.FunctionType(machine_int, [machine_int] * nargs)
|
| 30 |
+
ctypes_fnty = ctypes.CFUNCTYPE(ctypes.c_size_t,
|
| 31 |
+
* (ctypes.c_size_t,) * nargs)
|
| 32 |
+
module = self.context.create_module("")
|
| 33 |
+
|
| 34 |
+
function = cgutils.get_or_insert_function(module, llvm_fnty, self.id())
|
| 35 |
+
assert function.is_declaration
|
| 36 |
+
entry_block = function.append_basic_block('entry')
|
| 37 |
+
builder = ir.IRBuilder(entry_block)
|
| 38 |
+
|
| 39 |
+
first = [True]
|
| 40 |
+
|
| 41 |
+
@global_compiler_lock
|
| 42 |
+
def call_func(*args):
|
| 43 |
+
codegen = self.context.codegen()
|
| 44 |
+
library = codegen.create_library("test_module.%s" % self.id())
|
| 45 |
+
library.add_ir_module(module)
|
| 46 |
+
cptr = library.get_pointer_to_function(function.name)
|
| 47 |
+
cfunc = ctypes_fnty(cptr)
|
| 48 |
+
return cfunc(*args)
|
| 49 |
+
|
| 50 |
+
yield self.context, builder, function.args, call_func
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_bytearray_addr(self, ba):
|
| 54 |
+
assert isinstance(ba, bytearray)
|
| 55 |
+
ba_as_string = ctypes.pythonapi.PyByteArray_AsString
|
| 56 |
+
ba_as_string.argtypes = [ctypes.py_object]
|
| 57 |
+
ba_as_string.restype = ctypes.c_void_p
|
| 58 |
+
return ba_as_string(ba)
|
| 59 |
+
|
| 60 |
+
def test_compile_function(self):
|
| 61 |
+
# Simple self-test for compile_function()
|
| 62 |
+
with self.compile_function(2) as (context, builder, args, call):
|
| 63 |
+
res = builder.add(args[0], args[1])
|
| 64 |
+
builder.ret(res)
|
| 65 |
+
self.assertEqual(call(5, -2), 3)
|
| 66 |
+
self.assertEqual(call(4, 2), 6)
|
| 67 |
+
|
| 68 |
+
@contextlib.contextmanager
|
| 69 |
+
def run_struct_access(self, struct_class, buf, offset=0):
|
| 70 |
+
with self.compile_function(1) as (context, builder, args, call):
|
| 71 |
+
inst = struct_class(context, builder)
|
| 72 |
+
sptr = builder.add(args[0], machine_const(offset))
|
| 73 |
+
sptr = builder.inttoptr(sptr, ir.PointerType(inst._type))
|
| 74 |
+
inst = struct_class(context, builder, ref=sptr)
|
| 75 |
+
|
| 76 |
+
yield context, builder, args, inst
|
| 77 |
+
|
| 78 |
+
builder.ret(ir.Constant(machine_int, 0))
|
| 79 |
+
call(self.get_bytearray_addr(buf))
|
| 80 |
+
|
| 81 |
+
@contextlib.contextmanager
|
| 82 |
+
def run_simple_struct_test(self, struct_class, struct_fmt, struct_args):
|
| 83 |
+
# By using a too large buffer and a non-zero offset, we also check
|
| 84 |
+
# that surrounding memory isn't touched.
|
| 85 |
+
buf = bytearray(b'!') * 40
|
| 86 |
+
expected = buf[:]
|
| 87 |
+
offset = 8
|
| 88 |
+
|
| 89 |
+
with self.run_struct_access(struct_class, buf, offset) \
|
| 90 |
+
as (context, builder, args, inst):
|
| 91 |
+
yield context, builder, inst
|
| 92 |
+
|
| 93 |
+
self.assertNotEqual(buf, expected)
|
| 94 |
+
struct.pack_into(struct_fmt, expected, offset, *struct_args)
|
| 95 |
+
self.assertEqual(buf, expected)
|
| 96 |
+
|
| 97 |
+
def test_int_fields(self):
|
| 98 |
+
class S(cgutils.Structure):
|
| 99 |
+
_fields = [('a', types.int32),
|
| 100 |
+
('b', types.uint16)]
|
| 101 |
+
|
| 102 |
+
fmt = "=iH"
|
| 103 |
+
with self.run_simple_struct_test(S, fmt, (0x12345678, 0xABCD)) \
|
| 104 |
+
as (context, builder, inst):
|
| 105 |
+
inst.a = ir.Constant(ir.IntType(32), 0x12345678)
|
| 106 |
+
inst.b = ir.Constant(ir.IntType(16), 0xABCD)
|
| 107 |
+
|
| 108 |
+
def test_float_fields(self):
|
| 109 |
+
class S(cgutils.Structure):
|
| 110 |
+
_fields = [('a', types.float64),
|
| 111 |
+
('b', types.float32)]
|
| 112 |
+
|
| 113 |
+
fmt = "=df"
|
| 114 |
+
with self.run_simple_struct_test(S, fmt, (1.23, 4.56)) \
|
| 115 |
+
as (context, builder, inst):
|
| 116 |
+
inst.a = ir.Constant(ir.DoubleType(), 1.23)
|
| 117 |
+
inst.b = ir.Constant(ir.FloatType(), 4.56)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TestCGContext(TestCase):
|
| 121 |
+
"""Tests for code generation context functionality"""
|
| 122 |
+
|
| 123 |
+
def test_printf(self):
|
| 124 |
+
# Tests the printf() method
|
| 125 |
+
|
| 126 |
+
value = 123456
|
| 127 |
+
|
| 128 |
+
code = f"""if 1:
|
| 129 |
+
from numba import njit, types
|
| 130 |
+
from numba.extending import intrinsic
|
| 131 |
+
|
| 132 |
+
@intrinsic
|
| 133 |
+
def printf(tyctx, int_arg):
|
| 134 |
+
sig = types.void(int_arg)
|
| 135 |
+
def codegen(cgctx, builder, sig, llargs):
|
| 136 |
+
cgctx.printf(builder, \"%d\\n\", *llargs)
|
| 137 |
+
return sig, codegen
|
| 138 |
+
|
| 139 |
+
@njit
|
| 140 |
+
def foo():
|
| 141 |
+
printf({value})
|
| 142 |
+
|
| 143 |
+
foo()
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
out, _ = run_in_subprocess(code)
|
| 147 |
+
self.assertIn(str(value), out.decode())
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == '__main__':
|
| 152 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_cli.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tests for the CLI
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
import threading
|
| 7 |
+
import json
|
| 8 |
+
from subprocess import CompletedProcess
|
| 9 |
+
from tempfile import TemporaryDirectory
|
| 10 |
+
from unittest import mock
|
| 11 |
+
|
| 12 |
+
import unittest
|
| 13 |
+
from numba.tests.support import TestCase, linux_only
|
| 14 |
+
import numba.misc.numba_sysinfo as nsi
|
| 15 |
+
from numba.tests.gdb_support import needs_gdb
|
| 16 |
+
from numba.misc.numba_gdbinfo import collect_gdbinfo
|
| 17 |
+
# Going to mock parts of this in testing
|
| 18 |
+
from numba.misc.numba_gdbinfo import _GDBTestWrapper
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run_cmd(cmdline, env=os.environ, timeout=60):
|
| 22 |
+
popen = subprocess.Popen(cmdline,
|
| 23 |
+
stdout=subprocess.PIPE,
|
| 24 |
+
stderr=subprocess.PIPE,
|
| 25 |
+
env=env)
|
| 26 |
+
|
| 27 |
+
timeout_timer = threading.Timer(timeout, popen.kill)
|
| 28 |
+
try:
|
| 29 |
+
timeout_timer.start()
|
| 30 |
+
out, err = popen.communicate()
|
| 31 |
+
if popen.returncode != 0:
|
| 32 |
+
raise AssertionError(
|
| 33 |
+
"process failed with code %s: stderr follows\n%s\n" %
|
| 34 |
+
(popen.returncode, err.decode()))
|
| 35 |
+
return out.decode(), err.decode()
|
| 36 |
+
finally:
|
| 37 |
+
timeout_timer.cancel()
|
| 38 |
+
return None, None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TestCLI(TestCase):
|
| 42 |
+
|
| 43 |
+
def test_as_module_exit_code(self):
|
| 44 |
+
cmdline = [sys.executable, "-m", "numba"]
|
| 45 |
+
with self.assertRaises(AssertionError) as raises:
|
| 46 |
+
run_cmd(cmdline)
|
| 47 |
+
|
| 48 |
+
self.assertIn("process failed with code 1", str(raises.exception))
|
| 49 |
+
|
| 50 |
+
def test_sysinfo_from_module(self):
|
| 51 |
+
cmdline = [sys.executable, "-m", "numba", "-s"]
|
| 52 |
+
o, _ = run_cmd(cmdline)
|
| 53 |
+
self.assertIn("System info", o)
|
| 54 |
+
|
| 55 |
+
def test_json_sysinfo_from_module(self):
|
| 56 |
+
with TemporaryDirectory() as d:
|
| 57 |
+
path = os.path.join(d, "test_json_sysinfo.json")
|
| 58 |
+
cmdline = [sys.executable, "-m", "numba", "--sys-json", path]
|
| 59 |
+
run_cmd(cmdline)
|
| 60 |
+
with self.subTest(msg=f"{path} exists"):
|
| 61 |
+
self.assertTrue(os.path.exists(path))
|
| 62 |
+
with self.subTest(msg="json load"):
|
| 63 |
+
with open(path, 'r') as f:
|
| 64 |
+
info = json.load(f)
|
| 65 |
+
safe_contents = {
|
| 66 |
+
int: (
|
| 67 |
+
nsi._cpu_count,
|
| 68 |
+
),
|
| 69 |
+
float: (
|
| 70 |
+
nsi._runtime,
|
| 71 |
+
),
|
| 72 |
+
str: (
|
| 73 |
+
nsi._start,
|
| 74 |
+
nsi._start_utc,
|
| 75 |
+
nsi._machine,
|
| 76 |
+
nsi._cpu_name,
|
| 77 |
+
nsi._platform_name,
|
| 78 |
+
nsi._os_name,
|
| 79 |
+
nsi._os_version,
|
| 80 |
+
nsi._python_comp,
|
| 81 |
+
nsi._python_impl,
|
| 82 |
+
nsi._python_version,
|
| 83 |
+
nsi._llvm_version,
|
| 84 |
+
),
|
| 85 |
+
bool: (
|
| 86 |
+
nsi._cu_dev_init,
|
| 87 |
+
nsi._svml_state,
|
| 88 |
+
nsi._svml_loaded,
|
| 89 |
+
nsi._svml_operational,
|
| 90 |
+
nsi._llvm_svml_patched,
|
| 91 |
+
nsi._tbb_thread,
|
| 92 |
+
nsi._openmp_thread,
|
| 93 |
+
nsi._wkq_thread,
|
| 94 |
+
),
|
| 95 |
+
list: (
|
| 96 |
+
nsi._errors,
|
| 97 |
+
nsi._warnings,
|
| 98 |
+
),
|
| 99 |
+
dict: (
|
| 100 |
+
nsi._numba_env_vars,
|
| 101 |
+
),
|
| 102 |
+
}
|
| 103 |
+
for t, keys in safe_contents.items():
|
| 104 |
+
for k in keys:
|
| 105 |
+
with self.subTest(k=k):
|
| 106 |
+
self.assertIsInstance(info[k], t)
|
| 107 |
+
|
| 108 |
+
@needs_gdb
|
| 109 |
+
def test_gdb_status_from_module(self):
|
| 110 |
+
# Check that the `python -m numba -g` works ok
|
| 111 |
+
cmdline = [sys.executable, "-m", "numba", "-g"]
|
| 112 |
+
o, _ = run_cmd(cmdline)
|
| 113 |
+
self.assertIn("GDB info", o)
|
| 114 |
+
# It's not known a priori whether the extension is supported, this just
|
| 115 |
+
# checks that the last logical item in the output is printed.
|
| 116 |
+
self.assertIn("Numba printing extension support", o)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class TestGDBCLIInfo(TestCase):
|
| 120 |
+
|
| 121 |
+
def setUp(self):
|
| 122 |
+
# Mock the entire class, to report valid things,
|
| 123 |
+
# then override bits of it locally to check failures etc.
|
| 124 |
+
|
| 125 |
+
self._patches = []
|
| 126 |
+
|
| 127 |
+
mock_init = lambda self: None
|
| 128 |
+
self._patches.append(mock.patch.object(_GDBTestWrapper, '__init__',
|
| 129 |
+
mock_init))
|
| 130 |
+
|
| 131 |
+
bpath = 'numba.misc.numba_gdbinfo._GDBTestWrapper.gdb_binary'
|
| 132 |
+
self._patches.append(mock.patch(bpath, 'PATH_TO_GDB'))
|
| 133 |
+
|
| 134 |
+
def _patch(fnstr, func):
|
| 135 |
+
self._patches.append(mock.patch.object(_GDBTestWrapper, fnstr,
|
| 136 |
+
func))
|
| 137 |
+
|
| 138 |
+
def mock_check_launch(self):
|
| 139 |
+
return CompletedProcess('COMMAND STRING', 0)
|
| 140 |
+
|
| 141 |
+
_patch('check_launch', mock_check_launch)
|
| 142 |
+
|
| 143 |
+
# NOTE: The Python and NumPy versions are set to something unsupported!
|
| 144 |
+
def mock_check_python(self):
|
| 145 |
+
return CompletedProcess('COMMAND STRING', 0,
|
| 146 |
+
stdout='(3, 2)',
|
| 147 |
+
stderr='')
|
| 148 |
+
|
| 149 |
+
_patch('check_python', mock_check_python)
|
| 150 |
+
|
| 151 |
+
def mock_check_numpy(self):
|
| 152 |
+
return CompletedProcess('COMMAND STRING', 0, stdout='True',
|
| 153 |
+
stderr='')
|
| 154 |
+
|
| 155 |
+
_patch('check_numpy', mock_check_numpy)
|
| 156 |
+
|
| 157 |
+
def mock_check_numpy_version(self):
|
| 158 |
+
return CompletedProcess('COMMAND STRING', 0, stdout='1.15',
|
| 159 |
+
stderr='')
|
| 160 |
+
|
| 161 |
+
_patch('check_numpy_version', mock_check_numpy_version)
|
| 162 |
+
|
| 163 |
+
# start the patching
|
| 164 |
+
for p in self._patches:
|
| 165 |
+
p.start()
|
| 166 |
+
|
| 167 |
+
def tearDown(self):
|
| 168 |
+
# stop the patching
|
| 169 |
+
for p in self._patches:
|
| 170 |
+
p.stop()
|
| 171 |
+
|
| 172 |
+
def test_valid(self):
|
| 173 |
+
collected = collect_gdbinfo()
|
| 174 |
+
self.assertEqual(collected.binary_loc, 'PATH_TO_GDB')
|
| 175 |
+
extp = os.path.exists(os.path.abspath(collected.extension_loc))
|
| 176 |
+
self.assertTrue(extp)
|
| 177 |
+
self.assertEqual(collected.py_ver, '3.2')
|
| 178 |
+
self.assertEqual(collected.np_ver, '1.15')
|
| 179 |
+
self.assertIn('Full', collected.supported)
|
| 180 |
+
|
| 181 |
+
def test_invalid_binary(self):
|
| 182 |
+
|
| 183 |
+
def mock_fn(self):
|
| 184 |
+
return CompletedProcess('INVALID_BINARY', 1)
|
| 185 |
+
|
| 186 |
+
with mock.patch.object(_GDBTestWrapper, 'check_launch', mock_fn):
|
| 187 |
+
info = collect_gdbinfo()
|
| 188 |
+
self.assertIn("Testing gdb binary failed.", info.binary_loc)
|
| 189 |
+
self.assertIn("gdb at 'PATH_TO_GDB' does not appear to work",
|
| 190 |
+
info.binary_loc)
|
| 191 |
+
|
| 192 |
+
def test_no_python(self):
|
| 193 |
+
def mock_fn(self):
|
| 194 |
+
return CompletedProcess('NO PYTHON', 1)
|
| 195 |
+
|
| 196 |
+
with mock.patch.object(_GDBTestWrapper, 'check_python', mock_fn):
|
| 197 |
+
collected = collect_gdbinfo()
|
| 198 |
+
self.assertEqual(collected.py_ver, 'No Python support')
|
| 199 |
+
self.assertEqual(collected.supported, 'None')
|
| 200 |
+
|
| 201 |
+
def test_unparsable_python_version(self):
|
| 202 |
+
def mock_fn(self):
|
| 203 |
+
return CompletedProcess('NO PYTHON', 0, stdout='(NOT A VERSION)')
|
| 204 |
+
|
| 205 |
+
with mock.patch.object(_GDBTestWrapper, 'check_python', mock_fn):
|
| 206 |
+
collected = collect_gdbinfo()
|
| 207 |
+
self.assertEqual(collected.py_ver, 'No Python support')
|
| 208 |
+
|
| 209 |
+
def test_no_numpy(self):
|
| 210 |
+
def mock_fn(self):
|
| 211 |
+
return CompletedProcess('NO NUMPY', 1)
|
| 212 |
+
|
| 213 |
+
with mock.patch.object(_GDBTestWrapper, 'check_numpy', mock_fn):
|
| 214 |
+
collected = collect_gdbinfo()
|
| 215 |
+
self.assertEqual(collected.np_ver, 'No NumPy support')
|
| 216 |
+
self.assertEqual(collected.py_ver, '3.2')
|
| 217 |
+
self.assertIn('Partial', collected.supported)
|
| 218 |
+
|
| 219 |
+
def test_no_numpy_version(self):
|
| 220 |
+
def mock_fn(self):
|
| 221 |
+
return CompletedProcess('NO NUMPY VERSION', 1)
|
| 222 |
+
|
| 223 |
+
with mock.patch.object(_GDBTestWrapper, 'check_numpy_version', mock_fn):
|
| 224 |
+
collected = collect_gdbinfo()
|
| 225 |
+
self.assertEqual(collected.np_ver, 'Unknown')
|
| 226 |
+
|
| 227 |
+
def test_traceback_in_numpy_version(self):
|
| 228 |
+
def mock_fn(self):
|
| 229 |
+
return CompletedProcess('NO NUMPY VERSION', 0,
|
| 230 |
+
stdout='(NOT A VERSION)',
|
| 231 |
+
stderr='Traceback')
|
| 232 |
+
|
| 233 |
+
with mock.patch.object(_GDBTestWrapper, 'check_numpy_version', mock_fn):
|
| 234 |
+
collected = collect_gdbinfo()
|
| 235 |
+
self.assertEqual(collected.np_ver, 'Unknown')
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@linux_only
|
| 239 |
+
class TestGDBCLIInfoBrokenGdbs(TestCase):
|
| 240 |
+
# In these tests, it's necessary to actually run the entry point in an env
|
| 241 |
+
# with the env var set as it's in part testing the processing of the
|
| 242 |
+
# handling of consumption of variables by numba.core.config.
|
| 243 |
+
|
| 244 |
+
def test_cannot_find_gdb_from_name(self):
|
| 245 |
+
# Tests that supplying an invalid gdb binary name is handled ok
|
| 246 |
+
env = os.environ.copy()
|
| 247 |
+
env['NUMBA_GDB_BINARY'] = 'THIS_IS_NOT_A_VALID_GDB_BINARY_NAME'
|
| 248 |
+
cmdline = [sys.executable, "-m", "numba", "-g"]
|
| 249 |
+
stdout, stderr = run_cmd(cmdline, env=env)
|
| 250 |
+
self.assertIn("Testing gdb binary failed", stdout)
|
| 251 |
+
self.assertIn("No such file or directory", stdout)
|
| 252 |
+
self.assertIn("'THIS_IS_NOT_A_VALID_GDB_BINARY_NAME'", stdout)
|
| 253 |
+
|
| 254 |
+
def test_cannot_find_gdb_from_path(self):
|
| 255 |
+
# Tests that an invalid path is handled ok
|
| 256 |
+
env = os.environ.copy()
|
| 257 |
+
with TemporaryDirectory() as d:
|
| 258 |
+
# This wont exist as a path...
|
| 259 |
+
path = os.path.join(d, 'CANNOT_EXIST')
|
| 260 |
+
env['NUMBA_GDB_BINARY'] = path
|
| 261 |
+
cmdline = [sys.executable, "-m", "numba", "-g"]
|
| 262 |
+
stdout, stderr = run_cmd(cmdline, env=env)
|
| 263 |
+
self.assertIn("Testing gdb binary failed", stdout)
|
| 264 |
+
self.assertIn("No such file or directory", stdout)
|
| 265 |
+
self.assertIn(path, stdout)
|
| 266 |
+
|
| 267 |
+
def test_nonsense_gdb_binary(self):
|
| 268 |
+
# Tests that a nonsense binary specified as gdb it picked up ok
|
| 269 |
+
env = os.environ.copy()
|
| 270 |
+
env['NUMBA_GDB_BINARY'] = 'python' # 'python' isn't gdb!
|
| 271 |
+
cmdline = [sys.executable, "-m", "numba", "-g"]
|
| 272 |
+
stdout, stderr = run_cmd(cmdline, env=env)
|
| 273 |
+
self.assertIn("Testing gdb binary failed", stdout)
|
| 274 |
+
# NOTE: should 'python' ever add support for the same flags as the gdb
|
| 275 |
+
# commands used in the information gathering code in `numba_gdbinfo`
|
| 276 |
+
# this test will fail, it's reasonably unlikely.
|
| 277 |
+
self.assertIn("Unknown option", stdout)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
if __name__ == '__main__':
|
| 281 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_compiler_flags.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
from numba import njit
|
| 4 |
+
from numba.core.extending import overload
|
| 5 |
+
from numba.core.targetconfig import ConfigStack
|
| 6 |
+
from numba.core.compiler import Flags, DEFAULT_FLAGS
|
| 7 |
+
from numba.core import types
|
| 8 |
+
from numba.core.funcdesc import default_mangler
|
| 9 |
+
|
| 10 |
+
from numba.tests.support import TestCase, unittest
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestCompilerFlags(TestCase):
|
| 14 |
+
def test_setting_invalid_attribute(self):
|
| 15 |
+
flags = Flags()
|
| 16 |
+
msg = "'Flags' object has no attribute 'this_really_does_not_exist'"
|
| 17 |
+
with self.assertRaisesRegex(AttributeError, msg):
|
| 18 |
+
flags.this_really_does_not_exist = True
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestCompilerFlagCachedOverload(TestCase):
|
| 22 |
+
def test_fastmath_in_overload(self):
|
| 23 |
+
def fastmath_status():
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
@overload(fastmath_status)
|
| 27 |
+
def ov_fastmath_status():
|
| 28 |
+
flags = ConfigStack().top()
|
| 29 |
+
val = "Has fastmath" if flags.fastmath else "No fastmath"
|
| 30 |
+
|
| 31 |
+
def codegen():
|
| 32 |
+
return val
|
| 33 |
+
|
| 34 |
+
return codegen
|
| 35 |
+
|
| 36 |
+
@njit(fastmath=True)
|
| 37 |
+
def set_fastmath():
|
| 38 |
+
return fastmath_status()
|
| 39 |
+
|
| 40 |
+
@njit()
|
| 41 |
+
def foo():
|
| 42 |
+
a = fastmath_status()
|
| 43 |
+
b = set_fastmath()
|
| 44 |
+
return (a, b)
|
| 45 |
+
|
| 46 |
+
a, b = foo()
|
| 47 |
+
self.assertEqual(a, "No fastmath")
|
| 48 |
+
self.assertEqual(b, "Has fastmath")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TestFlagMangling(TestCase):
|
| 52 |
+
|
| 53 |
+
def test_demangle(self):
|
| 54 |
+
|
| 55 |
+
def check(flags):
|
| 56 |
+
mangled = flags.get_mangle_string()
|
| 57 |
+
out = flags.demangle(mangled)
|
| 58 |
+
# Demangle result MUST match summary()
|
| 59 |
+
self.assertEqual(out, flags.summary())
|
| 60 |
+
|
| 61 |
+
# test empty flags
|
| 62 |
+
flags = Flags()
|
| 63 |
+
check(flags)
|
| 64 |
+
|
| 65 |
+
# test default
|
| 66 |
+
check(DEFAULT_FLAGS)
|
| 67 |
+
|
| 68 |
+
# test other
|
| 69 |
+
flags = Flags()
|
| 70 |
+
flags.no_cpython_wrapper = True
|
| 71 |
+
flags.nrt = True
|
| 72 |
+
flags.fastmath = True
|
| 73 |
+
check(flags)
|
| 74 |
+
|
| 75 |
+
def test_mangled_flags_is_shorter(self):
|
| 76 |
+
# at least for these control cases
|
| 77 |
+
flags = Flags()
|
| 78 |
+
flags.nrt = True
|
| 79 |
+
flags.auto_parallel = True
|
| 80 |
+
self.assertLess(len(flags.get_mangle_string()), len(flags.summary()))
|
| 81 |
+
|
| 82 |
+
def test_mangled_flags_with_fastmath_parfors_inline(self):
|
| 83 |
+
# at least for these control cases
|
| 84 |
+
flags = Flags()
|
| 85 |
+
flags.nrt = True
|
| 86 |
+
flags.auto_parallel = True
|
| 87 |
+
flags.fastmath = True
|
| 88 |
+
flags.inline = "always"
|
| 89 |
+
self.assertLess(len(flags.get_mangle_string()), len(flags.summary()))
|
| 90 |
+
demangled = flags.demangle(flags.get_mangle_string())
|
| 91 |
+
# There should be no pointer value in the demangled string.
|
| 92 |
+
self.assertNotIn("0x", demangled)
|
| 93 |
+
|
| 94 |
+
def test_demangling_from_mangled_symbols(self):
|
| 95 |
+
"""Test demangling of flags from mangled symbol"""
|
| 96 |
+
# Use default mangler to mangle the string
|
| 97 |
+
fname = 'foo'
|
| 98 |
+
argtypes = types.int32,
|
| 99 |
+
flags = Flags()
|
| 100 |
+
flags.nrt = True
|
| 101 |
+
flags.inline = "always"
|
| 102 |
+
name = default_mangler(
|
| 103 |
+
fname, argtypes, abi_tags=[flags.get_mangle_string()],
|
| 104 |
+
)
|
| 105 |
+
# Find the ABI-tag. Starts with "B"
|
| 106 |
+
prefix = "_Z3fooB"
|
| 107 |
+
# Find the length of the ABI-tag
|
| 108 |
+
m = re.match("[0-9]+", name[len(prefix):])
|
| 109 |
+
size = m.group(0)
|
| 110 |
+
# Extract the ABI tag
|
| 111 |
+
base = len(prefix) + len(size)
|
| 112 |
+
abi_mangled = name[base:base + int(size)]
|
| 113 |
+
# Demangle and check
|
| 114 |
+
demangled = Flags.demangle(abi_mangled)
|
| 115 |
+
self.assertEqual(demangled, flags.summary())
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_compiler_lock.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from numba.core.compiler_lock import (
|
| 3 |
+
global_compiler_lock,
|
| 4 |
+
require_global_compiler_lock,
|
| 5 |
+
)
|
| 6 |
+
from numba.tests.support import TestCase
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestCompilerLock(TestCase):
|
| 10 |
+
def test_gcl_as_context_manager(self):
|
| 11 |
+
with global_compiler_lock:
|
| 12 |
+
require_global_compiler_lock()
|
| 13 |
+
|
| 14 |
+
def test_gcl_as_decorator(self):
|
| 15 |
+
@global_compiler_lock
|
| 16 |
+
def func():
|
| 17 |
+
require_global_compiler_lock()
|
| 18 |
+
|
| 19 |
+
func()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if __name__ == '__main__':
|
| 23 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_complex.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import math
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from numba import jit, types
|
| 6 |
+
from numba.tests.support import TestCase
|
| 7 |
+
from .complex_usecases import *
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
enable_pyobj_flags = {'forceobj': True}
|
| 11 |
+
no_pyobj_flags = {'nopython': True}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BaseComplexTest(object):
|
| 15 |
+
|
| 16 |
+
def basic_values(self):
|
| 17 |
+
reals = [-0.0, +0.0, 1, -1, +1.5, -3.5,
|
| 18 |
+
float('-inf'), float('+inf')]
|
| 19 |
+
if sys.platform != 'win32':
|
| 20 |
+
reals += [float('nan')]
|
| 21 |
+
return [complex(x, y) for x, y in itertools.product(reals, reals)]
|
| 22 |
+
|
| 23 |
+
def more_values(self):
|
| 24 |
+
reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi,
|
| 25 |
+
float('-inf'), float('+inf')]
|
| 26 |
+
if sys.platform != 'win32':
|
| 27 |
+
reals += [float('nan')]
|
| 28 |
+
return [complex(x, y) for x, y in itertools.product(reals, reals)]
|
| 29 |
+
|
| 30 |
+
def non_nan_values(self):
|
| 31 |
+
reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi,
|
| 32 |
+
float('inf'), float('-inf')]
|
| 33 |
+
return [complex(x, y) for x, y in itertools.product(reals, reals)]
|
| 34 |
+
|
| 35 |
+
def run_unary(self, pyfunc, x_types, x_values, ulps=1, abs_tol=None,
|
| 36 |
+
flags=enable_pyobj_flags):
|
| 37 |
+
for tx in x_types:
|
| 38 |
+
cfunc = jit((tx,), **flags)(pyfunc)
|
| 39 |
+
prec = 'single' if tx in (types.float32, types.complex64) else 'double'
|
| 40 |
+
for vx in x_values:
|
| 41 |
+
try:
|
| 42 |
+
expected = pyfunc(vx)
|
| 43 |
+
except ValueError as e:
|
| 44 |
+
self.assertIn("math domain error", str(e))
|
| 45 |
+
continue
|
| 46 |
+
got = cfunc(vx)
|
| 47 |
+
msg = 'for input %r with prec %r' % (vx, prec)
|
| 48 |
+
self.assertPreciseEqual(got, expected, prec=prec,
|
| 49 |
+
ulps=ulps, abs_tol=abs_tol, msg=msg)
|
| 50 |
+
|
| 51 |
+
def run_binary(self, pyfunc, value_types, values, ulps=1,
|
| 52 |
+
flags=enable_pyobj_flags):
|
| 53 |
+
for tx, ty in value_types:
|
| 54 |
+
cfunc = jit((tx, ty), **flags)(pyfunc)
|
| 55 |
+
prec = ('single'
|
| 56 |
+
if set([tx, ty]) & set([types.float32, types.complex64])
|
| 57 |
+
else 'double')
|
| 58 |
+
for vx, vy in values:
|
| 59 |
+
try:
|
| 60 |
+
expected = pyfunc(vx, vy)
|
| 61 |
+
except ValueError as e:
|
| 62 |
+
self.assertIn("math domain error", str(e))
|
| 63 |
+
continue
|
| 64 |
+
except ZeroDivisionError:
|
| 65 |
+
continue
|
| 66 |
+
got = cfunc(vx, vy)
|
| 67 |
+
msg = 'for input %r with prec %r' % ((vx, vy), prec)
|
| 68 |
+
self.assertPreciseEqual(got, expected, prec=prec,
|
| 69 |
+
ulps=ulps, msg=msg)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class TestComplex(BaseComplexTest, TestCase):
|
| 73 |
+
|
| 74 |
+
def test_real(self, flags=enable_pyobj_flags):
|
| 75 |
+
self.run_unary(real_usecase, [types.complex64, types.complex128],
|
| 76 |
+
self.basic_values(), flags=flags)
|
| 77 |
+
self.run_unary(real_usecase, [types.int8, types.int64],
|
| 78 |
+
[1, 0, -3], flags=flags)
|
| 79 |
+
self.run_unary(real_usecase, [types.float32, types.float64],
|
| 80 |
+
[1.5, -0.5], flags=flags)
|
| 81 |
+
|
| 82 |
+
def test_real_npm(self):
|
| 83 |
+
self.test_real(flags=no_pyobj_flags)
|
| 84 |
+
|
| 85 |
+
def test_imag(self, flags=enable_pyobj_flags):
|
| 86 |
+
self.run_unary(imag_usecase, [types.complex64, types.complex128],
|
| 87 |
+
self.basic_values(), flags=flags)
|
| 88 |
+
self.run_unary(imag_usecase, [types.int8, types.int64],
|
| 89 |
+
[1, 0, -3], flags=flags)
|
| 90 |
+
self.run_unary(imag_usecase, [types.float32, types.float64],
|
| 91 |
+
[1.5, -0.5], flags=flags)
|
| 92 |
+
|
| 93 |
+
def test_imag_npm(self):
|
| 94 |
+
self.test_imag(flags=no_pyobj_flags)
|
| 95 |
+
|
| 96 |
+
def test_conjugate(self, flags=enable_pyobj_flags):
|
| 97 |
+
self.run_unary(conjugate_usecase, [types.complex64, types.complex128],
|
| 98 |
+
self.basic_values(), flags=flags)
|
| 99 |
+
self.run_unary(conjugate_usecase, [types.int8, types.int64],
|
| 100 |
+
[1, 0, -3], flags=flags)
|
| 101 |
+
self.run_unary(conjugate_usecase, [types.float32, types.float64],
|
| 102 |
+
[1.5, -0.5], flags=flags)
|
| 103 |
+
|
| 104 |
+
def test_conjugate_npm(self):
|
| 105 |
+
self.test_conjugate(flags=no_pyobj_flags)
|
| 106 |
+
|
| 107 |
+
def test_div(self, flags=enable_pyobj_flags):
|
| 108 |
+
"""
|
| 109 |
+
Test complex.__div__ implementation with non-trivial values.
|
| 110 |
+
"""
|
| 111 |
+
# XXX Fold into test_operator?
|
| 112 |
+
values = list(itertools.product(self.more_values(), self.more_values()))
|
| 113 |
+
value_types = [(types.complex128, types.complex128),
|
| 114 |
+
(types.complex64, types.complex64)]
|
| 115 |
+
self.run_binary(div_usecase, value_types, values, flags=flags)
|
| 116 |
+
|
| 117 |
+
def test_div_npm(self):
|
| 118 |
+
self.test_div(flags=no_pyobj_flags)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class TestCMath(BaseComplexTest, TestCase):
|
| 122 |
+
"""
|
| 123 |
+
Tests for cmath module support.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def check_predicate_func(self, pyfunc, flags):
|
| 127 |
+
self.run_unary(pyfunc, [types.complex128, types.complex64],
|
| 128 |
+
self.basic_values(), flags=flags)
|
| 129 |
+
|
| 130 |
+
def check_unary_func(self, pyfunc, flags, ulps=1, abs_tol=None,
|
| 131 |
+
values=None):
|
| 132 |
+
self.run_unary(pyfunc, [types.complex128],
|
| 133 |
+
values or self.more_values(), flags=flags, ulps=ulps,
|
| 134 |
+
abs_tol=abs_tol)
|
| 135 |
+
# Avoid discontinuities around pi when in single precision.
|
| 136 |
+
self.run_unary(pyfunc, [types.complex64],
|
| 137 |
+
values or self.basic_values(), flags=flags, ulps=ulps,
|
| 138 |
+
abs_tol=abs_tol)
|
| 139 |
+
|
| 140 |
+
# Conversions
|
| 141 |
+
|
| 142 |
+
def test_phase(self):
|
| 143 |
+
self.check_unary_func(phase_usecase, enable_pyobj_flags)
|
| 144 |
+
|
| 145 |
+
def test_phase_npm(self):
|
| 146 |
+
self.check_unary_func(phase_usecase, no_pyobj_flags)
|
| 147 |
+
|
| 148 |
+
def test_polar(self):
|
| 149 |
+
self.check_unary_func(polar_usecase, enable_pyobj_flags)
|
| 150 |
+
|
| 151 |
+
def test_polar_npm(self):
|
| 152 |
+
self.check_unary_func(polar_usecase, no_pyobj_flags)
|
| 153 |
+
|
| 154 |
+
def test_rect(self, flags=enable_pyobj_flags):
|
| 155 |
+
def do_test(tp, seed_values):
|
| 156 |
+
values = [(z.real, z.imag) for z in seed_values
|
| 157 |
+
if not math.isinf(z.imag) or z.real == 0]
|
| 158 |
+
self.run_binary(rect_usecase, [(tp, tp)], values, flags=flags)
|
| 159 |
+
do_test(types.float64, self.more_values())
|
| 160 |
+
# Avoid discontinuities around pi when in single precision.
|
| 161 |
+
do_test(types.float32, self.basic_values())
|
| 162 |
+
|
| 163 |
+
def test_rect_npm(self):
|
| 164 |
+
self.test_rect(flags=no_pyobj_flags)
|
| 165 |
+
|
| 166 |
+
# Classification
|
| 167 |
+
|
| 168 |
+
def test_isnan(self, flags=enable_pyobj_flags):
|
| 169 |
+
self.check_predicate_func(isnan_usecase, enable_pyobj_flags)
|
| 170 |
+
|
| 171 |
+
def test_isnan_npm(self):
|
| 172 |
+
self.check_predicate_func(isnan_usecase, no_pyobj_flags)
|
| 173 |
+
|
| 174 |
+
def test_isinf(self, flags=enable_pyobj_flags):
|
| 175 |
+
self.check_predicate_func(isinf_usecase, enable_pyobj_flags)
|
| 176 |
+
|
| 177 |
+
def test_isinf_npm(self):
|
| 178 |
+
self.check_predicate_func(isinf_usecase, no_pyobj_flags)
|
| 179 |
+
|
| 180 |
+
def test_isfinite(self, flags=enable_pyobj_flags):
|
| 181 |
+
self.check_predicate_func(isfinite_usecase, enable_pyobj_flags)
|
| 182 |
+
|
| 183 |
+
def test_isfinite_npm(self):
|
| 184 |
+
self.check_predicate_func(isfinite_usecase, no_pyobj_flags)
|
| 185 |
+
|
| 186 |
+
# Power and logarithms
|
| 187 |
+
|
| 188 |
+
def test_exp(self):
|
| 189 |
+
self.check_unary_func(exp_usecase, enable_pyobj_flags, ulps=2)
|
| 190 |
+
|
| 191 |
+
def test_exp_npm(self):
|
| 192 |
+
# Aggressive optimization fixes the following subnormal float problem.
|
| 193 |
+
## The two tests are failing due to subnormal float problems.
|
| 194 |
+
## We are seeing (6.9532198665326e-310+2.1221202807e-314j) != 0j
|
| 195 |
+
self.check_unary_func(exp_usecase, no_pyobj_flags, ulps=2)
|
| 196 |
+
|
| 197 |
+
def test_log(self):
|
| 198 |
+
self.check_unary_func(log_usecase, enable_pyobj_flags)
|
| 199 |
+
|
| 200 |
+
def test_log_npm(self):
|
| 201 |
+
self.check_unary_func(log_usecase, no_pyobj_flags)
|
| 202 |
+
|
| 203 |
+
def test_log_base(self, flags=enable_pyobj_flags):
|
| 204 |
+
values = list(itertools.product(self.more_values(), self.more_values()))
|
| 205 |
+
value_types = [(types.complex128, types.complex128),
|
| 206 |
+
(types.complex64, types.complex64)]
|
| 207 |
+
self.run_binary(log_base_usecase, value_types, values, flags=flags,
|
| 208 |
+
ulps=3)
|
| 209 |
+
|
| 210 |
+
def test_log_base_npm(self):
|
| 211 |
+
self.test_log_base(flags=no_pyobj_flags)
|
| 212 |
+
|
| 213 |
+
def test_log10(self):
|
| 214 |
+
self.check_unary_func(log10_usecase, enable_pyobj_flags)
|
| 215 |
+
|
| 216 |
+
def test_log10_npm(self):
|
| 217 |
+
self.check_unary_func(log10_usecase, no_pyobj_flags)
|
| 218 |
+
|
| 219 |
+
def test_sqrt(self):
|
| 220 |
+
self.check_unary_func(sqrt_usecase, enable_pyobj_flags)
|
| 221 |
+
|
| 222 |
+
def test_sqrt_npm(self):
|
| 223 |
+
self.check_unary_func(sqrt_usecase, no_pyobj_flags)
|
| 224 |
+
# issue #3499, check large complex128 values, values cross the float32
|
| 225 |
+
# representation limit threshold
|
| 226 |
+
values = [-10 ** i for i in range(36, 41)]
|
| 227 |
+
self.run_unary(sqrt_usecase, [types.complex128],
|
| 228 |
+
values, flags=no_pyobj_flags)
|
| 229 |
+
|
| 230 |
+
# Trigonometric functions
|
| 231 |
+
|
| 232 |
+
def test_acos(self):
|
| 233 |
+
self.check_unary_func(acos_usecase, enable_pyobj_flags, ulps=2)
|
| 234 |
+
|
| 235 |
+
def test_acos_npm(self):
|
| 236 |
+
self.check_unary_func(acos_usecase, no_pyobj_flags, ulps=2)
|
| 237 |
+
|
| 238 |
+
def test_asin(self):
|
| 239 |
+
self.check_unary_func(asin_usecase, enable_pyobj_flags, ulps=2)
|
| 240 |
+
|
| 241 |
+
def test_asin_npm(self):
|
| 242 |
+
self.check_unary_func(asin_usecase, no_pyobj_flags, ulps=2)
|
| 243 |
+
|
| 244 |
+
def test_atan(self):
|
| 245 |
+
self.check_unary_func(atan_usecase, enable_pyobj_flags, ulps=2,)
|
| 246 |
+
|
| 247 |
+
def test_atan_npm(self):
|
| 248 |
+
self.check_unary_func(atan_usecase, no_pyobj_flags, ulps=2,)
|
| 249 |
+
|
| 250 |
+
def test_cos(self):
|
| 251 |
+
self.check_unary_func(cos_usecase, enable_pyobj_flags, ulps=2)
|
| 252 |
+
|
| 253 |
+
def test_cos_npm(self):
|
| 254 |
+
self.check_unary_func(cos_usecase, no_pyobj_flags, ulps=2)
|
| 255 |
+
|
| 256 |
+
def test_sin(self):
|
| 257 |
+
# See test_sinh.
|
| 258 |
+
self.check_unary_func(sin_usecase, enable_pyobj_flags, abs_tol='eps')
|
| 259 |
+
|
| 260 |
+
def test_sin_npm(self):
|
| 261 |
+
self.check_unary_func(sin_usecase, no_pyobj_flags, abs_tol='eps')
|
| 262 |
+
|
| 263 |
+
def test_tan(self):
|
| 264 |
+
self.check_unary_func(tan_usecase, enable_pyobj_flags, ulps=2)
|
| 265 |
+
|
| 266 |
+
def test_tan_npm(self):
|
| 267 |
+
self.check_unary_func(tan_usecase, enable_pyobj_flags, ulps=2)
|
| 268 |
+
|
| 269 |
+
# Hyperbolic functions
|
| 270 |
+
|
| 271 |
+
def test_acosh(self):
|
| 272 |
+
self.check_unary_func(acosh_usecase, enable_pyobj_flags)
|
| 273 |
+
|
| 274 |
+
def test_acosh_npm(self):
|
| 275 |
+
self.check_unary_func(acosh_usecase, no_pyobj_flags)
|
| 276 |
+
|
| 277 |
+
def test_asinh(self):
|
| 278 |
+
self.check_unary_func(asinh_usecase, enable_pyobj_flags, ulps=2)
|
| 279 |
+
|
| 280 |
+
def test_asinh_npm(self):
|
| 281 |
+
self.check_unary_func(asinh_usecase, no_pyobj_flags, ulps=2)
|
| 282 |
+
|
| 283 |
+
def test_atanh(self):
|
| 284 |
+
self.check_unary_func(atanh_usecase, enable_pyobj_flags, ulps=2)
|
| 285 |
+
|
| 286 |
+
def test_atanh_npm(self):
|
| 287 |
+
self.check_unary_func(atanh_usecase, no_pyobj_flags, ulps=2)
|
| 288 |
+
|
| 289 |
+
def test_cosh(self):
|
| 290 |
+
self.check_unary_func(cosh_usecase, enable_pyobj_flags, ulps=2)
|
| 291 |
+
|
| 292 |
+
def test_cosh_npm(self):
|
| 293 |
+
self.check_unary_func(cosh_usecase, no_pyobj_flags, ulps=2)
|
| 294 |
+
|
| 295 |
+
def test_sinh(self):
|
| 296 |
+
self.check_unary_func(sinh_usecase, enable_pyobj_flags, abs_tol='eps')
|
| 297 |
+
|
| 298 |
+
def test_sinh_npm(self):
|
| 299 |
+
self.check_unary_func(sinh_usecase, no_pyobj_flags, abs_tol='eps')
|
| 300 |
+
|
| 301 |
+
def test_tanh(self):
|
| 302 |
+
self.check_unary_func(tanh_usecase, enable_pyobj_flags, ulps=2)
|
| 303 |
+
|
| 304 |
+
def test_tanh_npm(self):
|
| 305 |
+
self.check_unary_func(tanh_usecase, enable_pyobj_flags, ulps=2)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == '__main__':
|
| 309 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_conversion.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import itertools
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
import unittest
|
| 7 |
+
from numba import jit, njit
|
| 8 |
+
from numba.core import types
|
| 9 |
+
from numba.tests.support import TestCase
|
| 10 |
+
from numba.np import numpy_support
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def identity(x):
|
| 14 |
+
return x
|
| 15 |
+
|
| 16 |
+
def addition(x, y):
|
| 17 |
+
return x + y
|
| 18 |
+
|
| 19 |
+
def equality(x, y):
|
| 20 |
+
return x == y
|
| 21 |
+
|
| 22 |
+
def foobar(x, y, z):
|
| 23 |
+
return x
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TestConversion(TestCase):
|
| 27 |
+
"""
|
| 28 |
+
Testing Python to Native conversion
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def test_complex_identity(self):
|
| 32 |
+
pyfunc = identity
|
| 33 |
+
cfunc = njit(types.complex64(types.complex64))(pyfunc)
|
| 34 |
+
|
| 35 |
+
xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
|
| 36 |
+
for x in xs:
|
| 37 |
+
self.assertEqual(cfunc(x), x)
|
| 38 |
+
for x in np.complex64(xs):
|
| 39 |
+
self.assertEqual(cfunc(x), x)
|
| 40 |
+
|
| 41 |
+
cfunc = njit(types.complex128(types.complex128))(pyfunc)
|
| 42 |
+
|
| 43 |
+
xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
|
| 44 |
+
for x in xs:
|
| 45 |
+
self.assertEqual(cfunc(x), x)
|
| 46 |
+
for x in np.complex128(xs):
|
| 47 |
+
self.assertEqual(cfunc(x), x)
|
| 48 |
+
|
| 49 |
+
def test_complex_addition(self):
|
| 50 |
+
pyfunc = addition
|
| 51 |
+
cfunc = njit(types.complex64(types.complex64, types.complex64))(pyfunc)
|
| 52 |
+
|
| 53 |
+
xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
|
| 54 |
+
for x in xs:
|
| 55 |
+
y = x
|
| 56 |
+
self.assertEqual(cfunc(x, y), x + y)
|
| 57 |
+
for x in np.complex64(xs):
|
| 58 |
+
y = x
|
| 59 |
+
self.assertEqual(cfunc(x, y), x + y)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
cfunc = njit(types.complex128(types.complex128,
|
| 63 |
+
types.complex128))(pyfunc)
|
| 64 |
+
|
| 65 |
+
xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
|
| 66 |
+
for x in xs:
|
| 67 |
+
y = x
|
| 68 |
+
self.assertEqual(cfunc(x, y), x + y)
|
| 69 |
+
for x in np.complex128(xs):
|
| 70 |
+
y = x
|
| 71 |
+
self.assertEqual(cfunc(x, y), x + y)
|
| 72 |
+
|
| 73 |
+
def test_boolean_as_int(self):
|
| 74 |
+
pyfunc = equality
|
| 75 |
+
cfunc = njit((types.boolean, types.intp))(pyfunc)
|
| 76 |
+
|
| 77 |
+
xs = True, False
|
| 78 |
+
ys = -1, 0, 1
|
| 79 |
+
|
| 80 |
+
for xs, ys in itertools.product(xs, ys):
|
| 81 |
+
self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys))
|
| 82 |
+
|
| 83 |
+
def test_boolean_as_float(self):
|
| 84 |
+
pyfunc = equality
|
| 85 |
+
cfunc = njit((types.boolean, types.float64))(pyfunc)
|
| 86 |
+
|
| 87 |
+
xs = True, False
|
| 88 |
+
ys = -1, 0, 1
|
| 89 |
+
|
| 90 |
+
for xs, ys in itertools.product(xs, ys):
|
| 91 |
+
self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys))
|
| 92 |
+
|
| 93 |
+
def test_boolean_eq_boolean(self):
|
| 94 |
+
pyfunc = equality
|
| 95 |
+
cfunc = njit((types.boolean, types.boolean))(pyfunc)
|
| 96 |
+
|
| 97 |
+
xs = True, False
|
| 98 |
+
ys = True, False
|
| 99 |
+
|
| 100 |
+
for xs, ys in itertools.product(xs, ys):
|
| 101 |
+
self.assertEqual(pyfunc(xs, ys), cfunc(xs, ys))
|
| 102 |
+
|
| 103 |
+
# test when a function parameters are jitted as unsigned types
|
| 104 |
+
# the function is called with negative parameters the Python error
|
| 105 |
+
# that it generates is correctly handled -- a Python error is returned to the user
|
| 106 |
+
# For more info, see the comment in Include/longobject.h for _PyArray_AsByteArray
|
| 107 |
+
# which PyLong_AsUnsignedLongLong calls
|
| 108 |
+
def test_negative_to_unsigned(self):
|
| 109 |
+
def f(x):
|
| 110 |
+
return x
|
| 111 |
+
with self.assertRaises(OverflowError):
|
| 112 |
+
jit('uintp(uintp)', nopython=True)(f)(-5)
|
| 113 |
+
|
| 114 |
+
# test the switch logic in callwraper.py:build_wrapper() works for more than one argument
|
| 115 |
+
# and where the error occurs
|
| 116 |
+
def test_multiple_args_negative_to_unsigned(self):
|
| 117 |
+
pyfunc = foobar
|
| 118 |
+
cfunc = njit(types.uint64(types.uint64, types.uint64,
|
| 119 |
+
types.uint64),)(pyfunc)
|
| 120 |
+
|
| 121 |
+
test_fail_args = ((-1, 0, 1), (0, -1, 1), (0, 1, -1))
|
| 122 |
+
with self.assertRaises(OverflowError):
|
| 123 |
+
for a, b, c in test_fail_args:
|
| 124 |
+
cfunc(a, b, c)
|
| 125 |
+
|
| 126 |
+
# test switch logic of callwraper.py:build_wrapper() with records as function parameters
|
| 127 |
+
def test_multiple_args_records(self):
|
| 128 |
+
pyfunc = foobar
|
| 129 |
+
|
| 130 |
+
mystruct_dt = np.dtype([('p', np.float64),
|
| 131 |
+
('row', np.float64),
|
| 132 |
+
('col', np.float64)])
|
| 133 |
+
mystruct = numpy_support.from_dtype(mystruct_dt)
|
| 134 |
+
|
| 135 |
+
cfunc = njit(mystruct[:](mystruct[:], types.uint64,
|
| 136 |
+
types.uint64),)(pyfunc)
|
| 137 |
+
|
| 138 |
+
st1 = np.recarray(3, dtype=mystruct_dt)
|
| 139 |
+
|
| 140 |
+
st1.p = np.arange(st1.size) + 1
|
| 141 |
+
st1.row = np.arange(st1.size) + 1
|
| 142 |
+
st1.col = np.arange(st1.size) + 1
|
| 143 |
+
|
| 144 |
+
with self.assertRefCount(st1):
|
| 145 |
+
test_fail_args = ((st1, -1, 1), (st1, 1, -1))
|
| 146 |
+
|
| 147 |
+
for a, b, c in test_fail_args:
|
| 148 |
+
with self.assertRaises(OverflowError):
|
| 149 |
+
cfunc(a, b, c)
|
| 150 |
+
|
| 151 |
+
del test_fail_args, a, b, c
|
| 152 |
+
gc.collect()
|
| 153 |
+
|
| 154 |
+
# test switch logic of callwraper.py:build_wrapper() with no function parameters
|
| 155 |
+
def test_with_no_parameters(self):
|
| 156 |
+
def f():
|
| 157 |
+
pass
|
| 158 |
+
self.assertEqual(f(), jit('()', nopython=True)(f)())
|
| 159 |
+
|
| 160 |
+
def check_argument_cleanup(self, typ, obj):
|
| 161 |
+
"""
|
| 162 |
+
Check that argument cleanup doesn't leak references.
|
| 163 |
+
"""
|
| 164 |
+
def f(x, y):
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
def _objects(obj):
|
| 168 |
+
objs = [obj]
|
| 169 |
+
if isinstance(obj, tuple):
|
| 170 |
+
for v in obj:
|
| 171 |
+
objs += _objects(v)
|
| 172 |
+
return objs
|
| 173 |
+
|
| 174 |
+
objects = _objects(obj)
|
| 175 |
+
|
| 176 |
+
cfunc = njit((typ, types.uint32))(f)
|
| 177 |
+
with self.assertRefCount(*objects):
|
| 178 |
+
cfunc(obj, 1)
|
| 179 |
+
with self.assertRefCount(*objects):
|
| 180 |
+
with self.assertRaises(OverflowError):
|
| 181 |
+
cfunc(obj, -1)
|
| 182 |
+
|
| 183 |
+
cfunc = njit((types.uint32, typ))(f)
|
| 184 |
+
with self.assertRefCount(*objects):
|
| 185 |
+
cfunc(1, obj)
|
| 186 |
+
with self.assertRefCount(*objects):
|
| 187 |
+
with self.assertRaises(OverflowError):
|
| 188 |
+
cfunc(-1, obj)
|
| 189 |
+
|
| 190 |
+
def test_cleanup_buffer(self):
|
| 191 |
+
mem = memoryview(bytearray(b"xyz"))
|
| 192 |
+
self.check_argument_cleanup(types.MemoryView(types.byte, 1, 'C'), mem)
|
| 193 |
+
|
| 194 |
+
def test_cleanup_record(self):
|
| 195 |
+
dtype = np.dtype([('x', np.float64), ('y', np.float64)])
|
| 196 |
+
recarr = np.zeros(1, dtype=dtype)
|
| 197 |
+
self.check_argument_cleanup(numpy_support.from_dtype(dtype), recarr[0])
|
| 198 |
+
|
| 199 |
+
def test_cleanup_tuple(self):
|
| 200 |
+
mem = memoryview(bytearray(b"xyz"))
|
| 201 |
+
tp = types.UniTuple(types.MemoryView(types.byte, 1, 'C'), 2)
|
| 202 |
+
self.check_argument_cleanup(tp, (mem, mem))
|
| 203 |
+
|
| 204 |
+
def test_cleanup_optional(self):
|
| 205 |
+
mem = memoryview(bytearray(b"xyz"))
|
| 206 |
+
tp = types.Optional(types.MemoryView(types.byte, 1, 'C'))
|
| 207 |
+
self.check_argument_cleanup(tp, mem)
|
| 208 |
+
|
| 209 |
+
def test_stringliteral_to_unicode(self):
|
| 210 |
+
# See issue #6907, explicit signature on bar() takes a unicode_type but
|
| 211 |
+
# the call to bar() in foo() is with a StringLiteral
|
| 212 |
+
|
| 213 |
+
@jit(types.void(types.unicode_type), nopython=True)
|
| 214 |
+
def bar(string):
|
| 215 |
+
pass
|
| 216 |
+
|
| 217 |
+
@jit(types.void(), nopython=True)
|
| 218 |
+
def foo2():
|
| 219 |
+
bar("literal string")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if __name__ == '__main__':
|
| 223 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_datamodel.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from llvmlite import ir, binding as ll
|
| 2 |
+
|
| 3 |
+
from numba.core import types, datamodel
|
| 4 |
+
from numba.core.datamodel.testing import test_factory
|
| 5 |
+
from numba.core.datamodel.manager import DataModelManager
|
| 6 |
+
from numba.core.datamodel.models import OpaqueModel
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestBool(test_factory()):
|
| 11 |
+
fe_type = types.boolean
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestPyObject(test_factory()):
|
| 15 |
+
fe_type = types.pyobject
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestInt8(test_factory()):
|
| 19 |
+
fe_type = types.int8
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestInt16(test_factory()):
|
| 23 |
+
fe_type = types.int16
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TestInt32(test_factory()):
|
| 27 |
+
fe_type = types.int32
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestInt64(test_factory()):
|
| 31 |
+
fe_type = types.int64
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestUInt8(test_factory()):
|
| 35 |
+
fe_type = types.uint8
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestUInt16(test_factory()):
|
| 39 |
+
fe_type = types.uint16
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class TestUInt32(test_factory()):
|
| 43 |
+
fe_type = types.uint32
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestUInt64(test_factory()):
|
| 47 |
+
fe_type = types.uint64
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TestFloat(test_factory()):
|
| 51 |
+
fe_type = types.float32
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TestDouble(test_factory()):
|
| 55 |
+
fe_type = types.float64
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class TestComplex(test_factory()):
|
| 59 |
+
fe_type = types.complex64
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class TestDoubleComplex(test_factory()):
|
| 63 |
+
fe_type = types.complex128
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class TestPointerOfInt32(test_factory()):
|
| 67 |
+
fe_type = types.CPointer(types.int32)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class TestUniTupleOf2xInt32(test_factory()):
|
| 71 |
+
fe_type = types.UniTuple(types.int32, 2)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestUniTupleEmpty(test_factory()):
|
| 75 |
+
fe_type = types.UniTuple(types.int32, 0)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class TestTupleInt32Float32(test_factory()):
|
| 79 |
+
fe_type = types.Tuple([types.int32, types.float32])
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class TestTupleEmpty(test_factory()):
|
| 83 |
+
fe_type = types.Tuple([])
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Test1DArrayOfInt32(test_factory()):
|
| 87 |
+
fe_type = types.Array(types.int32, 1, 'C')
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Test2DArrayOfComplex128(test_factory()):
|
| 91 |
+
fe_type = types.Array(types.complex128, 2, 'C')
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class Test0DArrayOfInt32(test_factory()):
|
| 95 |
+
fe_type = types.Array(types.int32, 0, 'C')
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class TestArgInfo(unittest.TestCase):
|
| 99 |
+
|
| 100 |
+
def _test_as_arguments(self, fe_args):
|
| 101 |
+
"""
|
| 102 |
+
Test round-tripping types *fe_args* through the default data model's
|
| 103 |
+
argument conversion and unpacking logic.
|
| 104 |
+
"""
|
| 105 |
+
dmm = datamodel.default_manager
|
| 106 |
+
fi = datamodel.ArgPacker(dmm, fe_args)
|
| 107 |
+
|
| 108 |
+
module = ir.Module()
|
| 109 |
+
fnty = ir.FunctionType(ir.VoidType(), [])
|
| 110 |
+
function = ir.Function(module, fnty, name="test_arguments")
|
| 111 |
+
builder = ir.IRBuilder()
|
| 112 |
+
builder.position_at_end(function.append_basic_block())
|
| 113 |
+
|
| 114 |
+
args = [ir.Constant(dmm.lookup(t).get_value_type(), None)
|
| 115 |
+
for t in fe_args]
|
| 116 |
+
|
| 117 |
+
# Roundtrip
|
| 118 |
+
values = fi.as_arguments(builder, args)
|
| 119 |
+
asargs = fi.from_arguments(builder, values)
|
| 120 |
+
|
| 121 |
+
self.assertEqual(len(asargs), len(fe_args))
|
| 122 |
+
valtys = tuple([v.type for v in values])
|
| 123 |
+
self.assertEqual(valtys, fi.argument_types)
|
| 124 |
+
|
| 125 |
+
expect_types = [a.type for a in args]
|
| 126 |
+
got_types = [a.type for a in asargs]
|
| 127 |
+
|
| 128 |
+
self.assertEqual(expect_types, got_types)
|
| 129 |
+
|
| 130 |
+
# Assign names (check this doesn't raise)
|
| 131 |
+
fi.assign_names(values, ["arg%i" for i in range(len(fe_args))])
|
| 132 |
+
|
| 133 |
+
builder.ret_void()
|
| 134 |
+
|
| 135 |
+
ll.parse_assembly(str(module))
|
| 136 |
+
|
| 137 |
+
def test_int32_array_complex(self):
|
| 138 |
+
fe_args = [types.int32,
|
| 139 |
+
types.Array(types.int32, 1, 'C'),
|
| 140 |
+
types.complex64]
|
| 141 |
+
self._test_as_arguments(fe_args)
|
| 142 |
+
|
| 143 |
+
def test_two_arrays(self):
|
| 144 |
+
fe_args = [types.Array(types.int32, 1, 'C')] * 2
|
| 145 |
+
self._test_as_arguments(fe_args)
|
| 146 |
+
|
| 147 |
+
def test_two_0d_arrays(self):
|
| 148 |
+
fe_args = [types.Array(types.int32, 0, 'C')] * 2
|
| 149 |
+
self._test_as_arguments(fe_args)
|
| 150 |
+
|
| 151 |
+
def test_tuples(self):
|
| 152 |
+
fe_args = [types.UniTuple(types.int32, 2),
|
| 153 |
+
types.UniTuple(types.int32, 3)]
|
| 154 |
+
self._test_as_arguments(fe_args)
|
| 155 |
+
# Tuple of struct-likes
|
| 156 |
+
arrty = types.Array(types.int32, 1, 'C')
|
| 157 |
+
fe_args = [types.UniTuple(arrty, 2),
|
| 158 |
+
types.UniTuple(arrty, 3)]
|
| 159 |
+
self._test_as_arguments(fe_args)
|
| 160 |
+
# Nested tuple
|
| 161 |
+
fe_args = [types.UniTuple(types.UniTuple(types.int32, 2), 3)]
|
| 162 |
+
self._test_as_arguments(fe_args)
|
| 163 |
+
|
| 164 |
+
def test_empty_tuples(self):
|
| 165 |
+
# Empty tuple
|
| 166 |
+
fe_args = [types.UniTuple(types.int16, 0),
|
| 167 |
+
types.Tuple(()),
|
| 168 |
+
types.int32]
|
| 169 |
+
self._test_as_arguments(fe_args)
|
| 170 |
+
|
| 171 |
+
def test_nested_empty_tuples(self):
|
| 172 |
+
fe_args = [types.int32,
|
| 173 |
+
types.UniTuple(types.Tuple(()), 2),
|
| 174 |
+
types.int64]
|
| 175 |
+
self._test_as_arguments(fe_args)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TestMemInfo(unittest.TestCase):
|
| 179 |
+
def setUp(self):
|
| 180 |
+
self.dmm = datamodel.default_manager
|
| 181 |
+
|
| 182 |
+
def test_number(self):
|
| 183 |
+
ty = types.int32
|
| 184 |
+
dm = self.dmm[ty]
|
| 185 |
+
self.assertFalse(dm.contains_nrt_meminfo())
|
| 186 |
+
|
| 187 |
+
def test_array(self):
|
| 188 |
+
ty = types.int32[:]
|
| 189 |
+
dm = self.dmm[ty]
|
| 190 |
+
self.assertTrue(dm.contains_nrt_meminfo())
|
| 191 |
+
|
| 192 |
+
def test_tuple_of_number(self):
|
| 193 |
+
ty = types.UniTuple(dtype=types.int32, count=2)
|
| 194 |
+
dm = self.dmm[ty]
|
| 195 |
+
self.assertFalse(dm.contains_nrt_meminfo())
|
| 196 |
+
|
| 197 |
+
def test_tuple_of_array(self):
|
| 198 |
+
ty = types.UniTuple(dtype=types.int32[:], count=2)
|
| 199 |
+
dm = self.dmm[ty]
|
| 200 |
+
self.assertTrue(dm.contains_nrt_meminfo())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class TestMisc(unittest.TestCase):
|
| 204 |
+
|
| 205 |
+
def test_issue2921(self):
|
| 206 |
+
import numpy as np
|
| 207 |
+
from numba import njit
|
| 208 |
+
|
| 209 |
+
@njit
|
| 210 |
+
def copy(a, b):
|
| 211 |
+
for i in range(a.shape[0]):
|
| 212 |
+
a[i] = b[i]
|
| 213 |
+
|
| 214 |
+
b = np.arange(5, dtype=np.uint8).view(np.bool_)
|
| 215 |
+
a = np.zeros_like(b)
|
| 216 |
+
copy(a, b)
|
| 217 |
+
np.testing.assert_equal(a, np.array((False,) + (True,) * 4))
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class TestDMMChaining(unittest.TestCase):
|
| 221 |
+
def test_basic(self):
|
| 222 |
+
dmm = DataModelManager()
|
| 223 |
+
|
| 224 |
+
class int_handler(OpaqueModel):
|
| 225 |
+
pass
|
| 226 |
+
|
| 227 |
+
class float_handler(OpaqueModel):
|
| 228 |
+
pass
|
| 229 |
+
|
| 230 |
+
dmm.register(types.Integer, int_handler)
|
| 231 |
+
dmm.register(types.Float, float_handler)
|
| 232 |
+
|
| 233 |
+
inter_dmm = DataModelManager()
|
| 234 |
+
|
| 235 |
+
class new_int_handler(OpaqueModel):
|
| 236 |
+
pass
|
| 237 |
+
|
| 238 |
+
inter_dmm.register(types.Integer, new_int_handler)
|
| 239 |
+
chained_dmm = inter_dmm.chain(dmm)
|
| 240 |
+
|
| 241 |
+
# Check that the chained DMM has the new handler
|
| 242 |
+
self.assertIsInstance(chained_dmm.lookup(types.intp), new_int_handler)
|
| 243 |
+
# and not the old handler
|
| 244 |
+
self.assertNotIsInstance(chained_dmm.lookup(types.intp), int_handler)
|
| 245 |
+
# Check that the base DMM has the old handler
|
| 246 |
+
self.assertIsInstance(dmm.lookup(types.intp), int_handler)
|
| 247 |
+
# Check that float goes to the float_handler
|
| 248 |
+
self.assertIsInstance(chained_dmm.lookup(types.float32), float_handler)
|
| 249 |
+
self.assertIsInstance(dmm.lookup(types.float32), float_handler)
|
| 250 |
+
# Check the intermediate DMM
|
| 251 |
+
self.assertIsInstance(inter_dmm.lookup(types.intp), new_int_handler)
|
| 252 |
+
with self.assertRaises(KeyError):
|
| 253 |
+
inter_dmm.lookup(types.float32)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == '__main__':
|
| 257 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_debuginfo.py
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
import inspect
|
| 3 |
+
import re
|
| 4 |
+
import numpy as np
|
| 5 |
+
import math
|
| 6 |
+
from textwrap import dedent
|
| 7 |
+
import unittest
|
| 8 |
+
import warnings
|
| 9 |
+
|
| 10 |
+
from numba.tests.support import (TestCase, override_config,
|
| 11 |
+
ignore_internal_warnings)
|
| 12 |
+
from numba import jit, njit
|
| 13 |
+
from numba.core import types
|
| 14 |
+
from numba.core.datamodel import default_manager
|
| 15 |
+
from numba.core.errors import NumbaDebugInfoWarning
|
| 16 |
+
import llvmlite.binding as llvm
|
| 17 |
+
|
| 18 |
+
#NOTE: These tests are potentially sensitive to changes in SSA or lowering
|
| 19 |
+
# behaviour and may need updating should changes be made to the corresponding
|
| 20 |
+
# algorithms.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestDebugInfo(TestCase):
|
| 24 |
+
"""
|
| 25 |
+
These tests only checks the compiled assembly for debuginfo.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def _getasm(self, fn, sig):
|
| 29 |
+
fn.compile(sig)
|
| 30 |
+
return fn.inspect_asm(sig)
|
| 31 |
+
|
| 32 |
+
def _check(self, fn, sig, expect):
|
| 33 |
+
asm = self._getasm(fn, sig=sig)
|
| 34 |
+
m = re.search(r"\.section.+debug", asm, re.I)
|
| 35 |
+
got = m is not None
|
| 36 |
+
self.assertEqual(expect, got, msg='debug info not found in:\n%s' % asm)
|
| 37 |
+
|
| 38 |
+
def test_no_debuginfo_in_asm(self):
|
| 39 |
+
@jit(nopython=True, debug=False)
|
| 40 |
+
def foo(x):
|
| 41 |
+
return x
|
| 42 |
+
|
| 43 |
+
self._check(foo, sig=(types.int32,), expect=False)
|
| 44 |
+
|
| 45 |
+
def test_debuginfo_in_asm(self):
|
| 46 |
+
@jit(nopython=True, debug=True)
|
| 47 |
+
def foo(x):
|
| 48 |
+
return x
|
| 49 |
+
|
| 50 |
+
self._check(foo, sig=(types.int32,), expect=True)
|
| 51 |
+
|
| 52 |
+
def test_environment_override(self):
|
| 53 |
+
with override_config('DEBUGINFO_DEFAULT', 1):
|
| 54 |
+
# Using default value
|
| 55 |
+
@jit(nopython=True)
|
| 56 |
+
def foo(x):
|
| 57 |
+
return x
|
| 58 |
+
self._check(foo, sig=(types.int32,), expect=True)
|
| 59 |
+
|
| 60 |
+
# User override default
|
| 61 |
+
@jit(nopython=True, debug=False)
|
| 62 |
+
def bar(x):
|
| 63 |
+
return x
|
| 64 |
+
self._check(bar, sig=(types.int32,), expect=False)
|
| 65 |
+
|
| 66 |
+
def test_llvm_inliner_flag_conflict(self):
|
| 67 |
+
# bar will be marked as 'alwaysinline', but when DEBUGINFO_DEFAULT is
|
| 68 |
+
# set functions are marked as 'noinline' this results in a conflict.
|
| 69 |
+
# baz will be marked as 'noinline' as a result of DEBUGINFO_DEFAULT
|
| 70 |
+
|
| 71 |
+
@njit(forceinline=True)
|
| 72 |
+
def bar(x):
|
| 73 |
+
return math.sin(x)
|
| 74 |
+
|
| 75 |
+
@njit(forceinline=False)
|
| 76 |
+
def baz(x):
|
| 77 |
+
return math.cos(x)
|
| 78 |
+
|
| 79 |
+
@njit
|
| 80 |
+
def foo(x):
|
| 81 |
+
a = bar(x)
|
| 82 |
+
b = baz(x)
|
| 83 |
+
return a, b
|
| 84 |
+
|
| 85 |
+
# check it compiles
|
| 86 |
+
with override_config('DEBUGINFO_DEFAULT', 1):
|
| 87 |
+
result = foo(np.pi)
|
| 88 |
+
|
| 89 |
+
self.assertPreciseEqual(result, foo.py_func(np.pi))
|
| 90 |
+
|
| 91 |
+
# check the LLVM IR has bar marked as 'alwaysinline' and baz as noinline
|
| 92 |
+
full_ir = foo.inspect_llvm(foo.signatures[0])
|
| 93 |
+
module = llvm.parse_assembly(full_ir)
|
| 94 |
+
name = foo.overloads[foo.signatures[0]].fndesc.mangled_name
|
| 95 |
+
funcs = [x for x in module.functions if x.name == name]
|
| 96 |
+
self.assertEqual(len(funcs), 1)
|
| 97 |
+
func = funcs[0]
|
| 98 |
+
|
| 99 |
+
# find the function calls and save the associated statements
|
| 100 |
+
f_names = []
|
| 101 |
+
for blk in func.blocks:
|
| 102 |
+
for stmt in blk.instructions:
|
| 103 |
+
if stmt.opcode == 'call':
|
| 104 |
+
# stmt.function.name This is the function being called
|
| 105 |
+
f_names.append(str(stmt).strip())
|
| 106 |
+
|
| 107 |
+
# Need to check there's two specific things in the calls in the IR
|
| 108 |
+
# 1. a call to the llvm.sin.f64 intrinsic, this is from the inlined bar
|
| 109 |
+
# 2. a call to the baz function, this is from the noinline baz
|
| 110 |
+
found_sin = False
|
| 111 |
+
found_baz = False
|
| 112 |
+
baz_name = baz.overloads[baz.signatures[0]].fndesc.mangled_name
|
| 113 |
+
for x in f_names:
|
| 114 |
+
if not found_sin and re.match('.*llvm.sin.f64.*', x):
|
| 115 |
+
found_sin = True
|
| 116 |
+
if not found_baz and re.match(f'.*{baz_name}.*', x):
|
| 117 |
+
found_baz = True
|
| 118 |
+
|
| 119 |
+
self.assertTrue(found_sin)
|
| 120 |
+
self.assertTrue(found_baz)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class TestDebugInfoEmission(TestCase):
|
| 124 |
+
""" Tests that debug info is emitted correctly.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
_NUMBA_OPT_0_ENV = {'NUMBA_OPT': '0'}
|
| 128 |
+
|
| 129 |
+
def _get_llvmir(self, fn, sig):
|
| 130 |
+
with override_config('OPT', 0):
|
| 131 |
+
fn.compile(sig)
|
| 132 |
+
return fn.inspect_llvm(sig)
|
| 133 |
+
|
| 134 |
+
def _get_metadata(self, fn, sig):
|
| 135 |
+
ll = self._get_llvmir(fn, sig).splitlines()
|
| 136 |
+
meta_re = re.compile(r'![0-9]+ =.*')
|
| 137 |
+
metadata = []
|
| 138 |
+
for line in ll:
|
| 139 |
+
if meta_re.match(line):
|
| 140 |
+
metadata.append(line)
|
| 141 |
+
return metadata
|
| 142 |
+
|
| 143 |
+
def _get_metadata_map(self, metadata):
|
| 144 |
+
"""Gets the map of DI label to md, e.g.
|
| 145 |
+
'!33' -> '!{!"branch_weights", i32 1, i32 99}'
|
| 146 |
+
"""
|
| 147 |
+
metadata_definition_map = dict()
|
| 148 |
+
meta_definition_split = re.compile(r'(![0-9]+) = (.*)')
|
| 149 |
+
for line in metadata:
|
| 150 |
+
matched = meta_definition_split.match(line)
|
| 151 |
+
if matched:
|
| 152 |
+
dbg_val, info = matched.groups()
|
| 153 |
+
metadata_definition_map[dbg_val] = info
|
| 154 |
+
return metadata_definition_map
|
| 155 |
+
|
| 156 |
+
def _get_lines_from_debuginfo(self, metadata):
|
| 157 |
+
# Get the lines contained in the debug info
|
| 158 |
+
md_def_map = self._get_metadata_map(metadata)
|
| 159 |
+
|
| 160 |
+
lines = set()
|
| 161 |
+
for md in md_def_map.values():
|
| 162 |
+
m = re.match(r"!DILocation\(line: (\d+),", md)
|
| 163 |
+
if m:
|
| 164 |
+
ln = int(m.group(1))
|
| 165 |
+
lines.add(ln)
|
| 166 |
+
return lines
|
| 167 |
+
|
| 168 |
+
def test_DW_LANG(self):
|
| 169 |
+
|
| 170 |
+
@njit(debug=True)
|
| 171 |
+
def foo():
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
metadata = self._get_metadata(foo, sig=())
|
| 175 |
+
DICompileUnit = metadata[0]
|
| 176 |
+
self.assertEqual('!0', DICompileUnit[:2])
|
| 177 |
+
self.assertIn('!DICompileUnit(language: DW_LANG_C_plus_plus',
|
| 178 |
+
DICompileUnit)
|
| 179 |
+
self.assertIn('producer: "clang (Numba)"', DICompileUnit)
|
| 180 |
+
|
| 181 |
+
def test_DILocation(self):
|
| 182 |
+
""" Tests that DILocation information is reasonable.
|
| 183 |
+
"""
|
| 184 |
+
@njit(debug=True, error_model='numpy')
|
| 185 |
+
def foo(a):
|
| 186 |
+
b = a + 1.23
|
| 187 |
+
c = b * 2.34
|
| 188 |
+
d = b / c
|
| 189 |
+
print(d)
|
| 190 |
+
return d
|
| 191 |
+
|
| 192 |
+
# the above produces LLVM like:
|
| 193 |
+
# define function() {
|
| 194 |
+
# entry:
|
| 195 |
+
# alloca
|
| 196 |
+
# store 0 to alloca
|
| 197 |
+
# <arithmetic for doing the operations on b, c, d>
|
| 198 |
+
# setup for print
|
| 199 |
+
# branch
|
| 200 |
+
# other_labels:
|
| 201 |
+
# ... <elided>
|
| 202 |
+
# }
|
| 203 |
+
#
|
| 204 |
+
# The following checks that:
|
| 205 |
+
# * the alloca and store have no !dbg
|
| 206 |
+
# * the arithmetic occurs in the order defined and with !dbg
|
| 207 |
+
# * that the !dbg entries are monotonically increasing in value with
|
| 208 |
+
# source line number
|
| 209 |
+
|
| 210 |
+
sig = (types.float64,)
|
| 211 |
+
metadata = self._get_metadata(foo, sig=sig)
|
| 212 |
+
full_ir = self._get_llvmir(foo, sig=sig)
|
| 213 |
+
|
| 214 |
+
module = llvm.parse_assembly(full_ir)
|
| 215 |
+
|
| 216 |
+
name = foo.overloads[foo.signatures[0]].fndesc.mangled_name
|
| 217 |
+
funcs = [x for x in module.functions if x.name == name]
|
| 218 |
+
self.assertEqual(len(funcs), 1)
|
| 219 |
+
func = funcs[0]
|
| 220 |
+
blocks = [x for x in func.blocks]
|
| 221 |
+
self.assertGreater(len(blocks), 1)
|
| 222 |
+
block = blocks[0]
|
| 223 |
+
|
| 224 |
+
# Find non-call/non-memory instr and check the sequence is as expected
|
| 225 |
+
instrs = [x for x in block.instructions if x.opcode not in
|
| 226 |
+
['call', 'load', 'store']]
|
| 227 |
+
op_expect = {'fadd', 'fmul', 'fdiv'}
|
| 228 |
+
started = False
|
| 229 |
+
for x in instrs:
|
| 230 |
+
if x.opcode in op_expect:
|
| 231 |
+
op_expect.remove(x.opcode)
|
| 232 |
+
if not started:
|
| 233 |
+
started = True
|
| 234 |
+
elif op_expect and started:
|
| 235 |
+
self.fail("Math opcodes are not contiguous")
|
| 236 |
+
self.assertFalse(op_expect, "Math opcodes were not found")
|
| 237 |
+
|
| 238 |
+
# Parse out metadata from end of each line, check it monotonically
|
| 239 |
+
# ascends with LLVM source line. Also store all the dbg references,
|
| 240 |
+
# these will be checked later.
|
| 241 |
+
line2dbg = set()
|
| 242 |
+
re_dbg_ref = re.compile(r'.*!dbg (![0-9]+).*$')
|
| 243 |
+
found = -1
|
| 244 |
+
for instr in instrs:
|
| 245 |
+
inst_as_str = str(instr)
|
| 246 |
+
matched = re_dbg_ref.match(inst_as_str)
|
| 247 |
+
if not matched:
|
| 248 |
+
# if there's no match, ensure it is one of alloca or store,
|
| 249 |
+
# it's important that the zero init/alloca instructions have
|
| 250 |
+
# no dbg data
|
| 251 |
+
accepted = ('alloca ', 'store ')
|
| 252 |
+
self.assertTrue(any([x in inst_as_str for x in accepted]))
|
| 253 |
+
continue
|
| 254 |
+
groups = matched.groups()
|
| 255 |
+
self.assertEqual(len(groups), 1)
|
| 256 |
+
dbg_val = groups[0]
|
| 257 |
+
int_dbg_val = int(dbg_val[1:])
|
| 258 |
+
if found >= 0:
|
| 259 |
+
self.assertTrue(int_dbg_val >= found)
|
| 260 |
+
found = int_dbg_val
|
| 261 |
+
# some lines will alias dbg info, this is fine, it's only used to
|
| 262 |
+
# make sure that the line numbers are correct WRT python
|
| 263 |
+
line2dbg.add(dbg_val)
|
| 264 |
+
|
| 265 |
+
pysrc, pysrc_line_start = inspect.getsourcelines(foo)
|
| 266 |
+
|
| 267 |
+
# build a map of dbg reference to DI* information
|
| 268 |
+
metadata_definition_map = self._get_metadata_map(metadata)
|
| 269 |
+
|
| 270 |
+
# Pull out metadata entries referred to by the llvm line end !dbg
|
| 271 |
+
# check they match the python source, the +2 is for the @njit decorator
|
| 272 |
+
# and the function definition line.
|
| 273 |
+
offsets = [0, # b = a + 1
|
| 274 |
+
1, # a * 2.34
|
| 275 |
+
2, # d = b / c
|
| 276 |
+
3, # print(d)
|
| 277 |
+
]
|
| 278 |
+
pyln_range = [pysrc_line_start + 2 + x for x in offsets]
|
| 279 |
+
|
| 280 |
+
# do the check
|
| 281 |
+
for (k, line_no) in zip(sorted(line2dbg, key=lambda x: int(x[1:])),
|
| 282 |
+
pyln_range):
|
| 283 |
+
dilocation_info = metadata_definition_map[k]
|
| 284 |
+
self.assertIn(f'line: {line_no}', dilocation_info)
|
| 285 |
+
|
| 286 |
+
# Check that variable "a" is declared as on the same line as function
|
| 287 |
+
# definition.
|
| 288 |
+
expr = r'.*!DILocalVariable\(name: "a",.*line: ([0-9]+),.*'
|
| 289 |
+
match_local_var_a = re.compile(expr)
|
| 290 |
+
for entry in metadata_definition_map.values():
|
| 291 |
+
matched = match_local_var_a.match(entry)
|
| 292 |
+
if matched:
|
| 293 |
+
groups = matched.groups()
|
| 294 |
+
self.assertEqual(len(groups), 1)
|
| 295 |
+
dbg_line = int(groups[0])
|
| 296 |
+
# +1 for the decorator.
|
| 297 |
+
# Recall that Numba's DWARF refers to the "def" line, but
|
| 298 |
+
# `inspect` uses the decorator as the first line.
|
| 299 |
+
defline = pysrc_line_start + 1
|
| 300 |
+
self.assertEqual(dbg_line, defline)
|
| 301 |
+
break
|
| 302 |
+
else:
|
| 303 |
+
self.fail('Assertion on DILocalVariable not made')
|
| 304 |
+
|
| 305 |
+
@TestCase.run_test_in_subprocess(envvars=_NUMBA_OPT_0_ENV)
|
| 306 |
+
def test_DILocation_entry_blk(self):
|
| 307 |
+
# Needs a subprocess as jitting literally anything at any point in the
|
| 308 |
+
# lifetime of the process ends up with a codegen at opt 3. This is not
|
| 309 |
+
# amenable to this test!
|
| 310 |
+
# This test relies on the CFG not being simplified as it checks the jump
|
| 311 |
+
# from the entry block to the first basic block. Force OPT as 0, if set
|
| 312 |
+
# via the env var the targetmachine and various pass managers all end up
|
| 313 |
+
# at OPT 0 and the IR is minimally transformed prior to lowering to ELF.
|
| 314 |
+
#
|
| 315 |
+
# This tests that the unconditional jump emitted at the tail of
|
| 316 |
+
# the entry block has no debug metadata associated with it. In practice,
|
| 317 |
+
# if debug metadata is associated with it, it manifests as the
|
| 318 |
+
# prologue_end being associated with the end_sequence or similar (due to
|
| 319 |
+
# the way code gen works for the entry block).
|
| 320 |
+
|
| 321 |
+
@njit(debug=True)
|
| 322 |
+
def foo(a):
|
| 323 |
+
return a + 1
|
| 324 |
+
foo(123)
|
| 325 |
+
|
| 326 |
+
full_ir = foo.inspect_llvm(foo.signatures[0])
|
| 327 |
+
# The above produces LLVM like:
|
| 328 |
+
#
|
| 329 |
+
# define function() {
|
| 330 |
+
# entry:
|
| 331 |
+
# alloca
|
| 332 |
+
# store 0 to alloca
|
| 333 |
+
# unconditional jump to body:
|
| 334 |
+
#
|
| 335 |
+
# body:
|
| 336 |
+
# ... <elided>
|
| 337 |
+
# }
|
| 338 |
+
|
| 339 |
+
module = llvm.parse_assembly(full_ir)
|
| 340 |
+
name = foo.overloads[foo.signatures[0]].fndesc.mangled_name
|
| 341 |
+
funcs = [x for x in module.functions if x.name == name]
|
| 342 |
+
self.assertEqual(len(funcs), 1)
|
| 343 |
+
func = funcs[0]
|
| 344 |
+
blocks = [x for x in func.blocks]
|
| 345 |
+
self.assertEqual(len(blocks), 2)
|
| 346 |
+
entry_block, body_block = blocks
|
| 347 |
+
|
| 348 |
+
# Assert that the tail of the entry block is an unconditional jump to
|
| 349 |
+
# the body block and that the jump has no associated debug info.
|
| 350 |
+
entry_instr = [x for x in entry_block.instructions]
|
| 351 |
+
ujmp = entry_instr[-1]
|
| 352 |
+
self.assertEqual(ujmp.opcode, 'br')
|
| 353 |
+
ujmp_operands = [x for x in ujmp.operands]
|
| 354 |
+
self.assertEqual(len(ujmp_operands), 1)
|
| 355 |
+
target_data = ujmp_operands[0]
|
| 356 |
+
target = str(target_data).split(':')[0].strip()
|
| 357 |
+
# check the unconditional jump target is to the body block
|
| 358 |
+
self.assertEqual(target, body_block.name)
|
| 359 |
+
# check the uncondition jump instr itself has no metadata
|
| 360 |
+
self.assertTrue(str(ujmp).endswith(target))
|
| 361 |
+
|
| 362 |
+
@TestCase.run_test_in_subprocess(envvars=_NUMBA_OPT_0_ENV)
|
| 363 |
+
def test_DILocation_decref(self):
|
| 364 |
+
""" This tests that decref's generated from `ir.Del`s as variables go
|
| 365 |
+
out of scope do not have debuginfo associated with them (the location of
|
| 366 |
+
`ir.Del` is an implementation detail).
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
@njit(debug=True)
|
| 370 |
+
def sink(*x):
|
| 371 |
+
pass
|
| 372 |
+
|
| 373 |
+
# This function has many decrefs!
|
| 374 |
+
@njit(debug=True)
|
| 375 |
+
def foo(a):
|
| 376 |
+
x = (a, a)
|
| 377 |
+
if a[0] == 0:
|
| 378 |
+
sink(x)
|
| 379 |
+
return 12
|
| 380 |
+
z = x[0][0]
|
| 381 |
+
return z
|
| 382 |
+
|
| 383 |
+
sig = (types.float64[::1],)
|
| 384 |
+
full_ir = self._get_llvmir(foo, sig=sig)
|
| 385 |
+
|
| 386 |
+
# make sure decref lines end with `meminfo.<number>)` without !dbg info.
|
| 387 |
+
count = 0
|
| 388 |
+
for line in full_ir.splitlines():
|
| 389 |
+
line_stripped = line.strip()
|
| 390 |
+
if line_stripped.startswith('call void @NRT_decref'):
|
| 391 |
+
self.assertRegex(line, r'.*meminfo\.[0-9]+\)$')
|
| 392 |
+
count += 1
|
| 393 |
+
self.assertGreater(count, 0) # make sure there were some decrefs!
|
| 394 |
+
|
| 395 |
+
def test_DILocation_undefined(self):
|
| 396 |
+
""" Tests that DILocation information for undefined vars is associated
|
| 397 |
+
with the line of the function definition (so it ends up in the prologue)
|
| 398 |
+
"""
|
| 399 |
+
@njit(debug=True)
|
| 400 |
+
def foo(n):
|
| 401 |
+
if n:
|
| 402 |
+
if n > 0:
|
| 403 |
+
c = 0
|
| 404 |
+
return c
|
| 405 |
+
else:
|
| 406 |
+
# variable c is not defined in this branch
|
| 407 |
+
c += 1
|
| 408 |
+
return c
|
| 409 |
+
|
| 410 |
+
sig = (types.intp,)
|
| 411 |
+
metadata = self._get_metadata(foo, sig=sig)
|
| 412 |
+
pysrc, pysrc_line_start = inspect.getsourcelines(foo)
|
| 413 |
+
# Looks for versions of variable "c" and captures the line number
|
| 414 |
+
expr = r'.*!DILocalVariable\(name: "c\$?[0-9]?",.*line: ([0-9]+),.*'
|
| 415 |
+
matcher = re.compile(expr)
|
| 416 |
+
associated_lines = set()
|
| 417 |
+
for md in metadata:
|
| 418 |
+
match = matcher.match(md)
|
| 419 |
+
if match:
|
| 420 |
+
groups = match.groups()
|
| 421 |
+
self.assertEqual(len(groups), 1)
|
| 422 |
+
associated_lines.add(int(groups[0]))
|
| 423 |
+
# 3 versions of 'c': `c = 0`, `return c`, `c+=1`
|
| 424 |
+
self.assertEqual(len(associated_lines), 3)
|
| 425 |
+
self.assertIn(pysrc_line_start, associated_lines)
|
| 426 |
+
|
| 427 |
+
def test_DILocation_versioned_variables(self):
|
| 428 |
+
""" Tests that DILocation information for versions of variables matches
|
| 429 |
+
up to their definition site."""
|
| 430 |
+
# Note: there's still something wrong in the DI/SSA naming, the ret c is
|
| 431 |
+
# associated with the logically first definition.
|
| 432 |
+
|
| 433 |
+
@njit(debug=True)
|
| 434 |
+
def foo(n):
|
| 435 |
+
if n:
|
| 436 |
+
c = 5
|
| 437 |
+
else:
|
| 438 |
+
c = 1
|
| 439 |
+
# prevents inline of return on py310
|
| 440 |
+
py310_defeat1 = 1 # noqa
|
| 441 |
+
py310_defeat2 = 2 # noqa
|
| 442 |
+
py310_defeat3 = 3 # noqa
|
| 443 |
+
py310_defeat4 = 4 # noqa
|
| 444 |
+
return c
|
| 445 |
+
|
| 446 |
+
sig = (types.intp,)
|
| 447 |
+
metadata = self._get_metadata(foo, sig=sig)
|
| 448 |
+
pysrc, pysrc_line_start = inspect.getsourcelines(foo)
|
| 449 |
+
|
| 450 |
+
# Looks for SSA versioned names i.e. <basename>$<version id> of the
|
| 451 |
+
# variable 'c' and captures the line
|
| 452 |
+
expr = r'.*!DILocalVariable\(name: "c\$[0-9]?",.*line: ([0-9]+),.*'
|
| 453 |
+
matcher = re.compile(expr)
|
| 454 |
+
associated_lines = set()
|
| 455 |
+
for md in metadata:
|
| 456 |
+
match = matcher.match(md)
|
| 457 |
+
if match:
|
| 458 |
+
groups = match.groups()
|
| 459 |
+
self.assertEqual(len(groups), 1)
|
| 460 |
+
associated_lines.add(int(groups[0]))
|
| 461 |
+
self.assertEqual(len(associated_lines), 2) # 2 SSA versioned names 'c'
|
| 462 |
+
|
| 463 |
+
# Now find the `c = ` lines in the python source
|
| 464 |
+
py_lines = set()
|
| 465 |
+
for ix, pyln in enumerate(pysrc):
|
| 466 |
+
if 'c = ' in pyln:
|
| 467 |
+
py_lines.add(ix + pysrc_line_start)
|
| 468 |
+
self.assertEqual(len(py_lines), 2) # 2 assignments to c
|
| 469 |
+
|
| 470 |
+
# check that the DILocation from the DI for `c` matches the python src
|
| 471 |
+
self.assertEqual(associated_lines, py_lines)
|
| 472 |
+
|
| 473 |
+
def test_numeric_scalars(self):
|
| 474 |
+
""" Tests that dwarf info is correctly emitted for numeric scalars."""
|
| 475 |
+
|
| 476 |
+
DI = namedtuple('DI', 'name bits encoding')
|
| 477 |
+
|
| 478 |
+
type_infos = {np.float32: DI("float32", 32, "DW_ATE_float"),
|
| 479 |
+
np.float64: DI("float64", 64, "DW_ATE_float"),
|
| 480 |
+
np.int8: DI("int8", 8, "DW_ATE_signed"),
|
| 481 |
+
np.int16: DI("int16", 16, "DW_ATE_signed"),
|
| 482 |
+
np.int32: DI("int32", 32, "DW_ATE_signed"),
|
| 483 |
+
np.int64: DI("int64", 64, "DW_ATE_signed"),
|
| 484 |
+
np.uint8: DI("uint8", 8, "DW_ATE_unsigned"),
|
| 485 |
+
np.uint16: DI("uint16", 16, "DW_ATE_unsigned"),
|
| 486 |
+
np.uint32: DI("uint32", 32, "DW_ATE_unsigned"),
|
| 487 |
+
np.uint64: DI("uint64", 64, "DW_ATE_unsigned"),
|
| 488 |
+
np.complex64: DI("complex64", 64,
|
| 489 |
+
"DW_TAG_structure_type"),
|
| 490 |
+
np.complex128: DI("complex128", 128,
|
| 491 |
+
"DW_TAG_structure_type"),}
|
| 492 |
+
|
| 493 |
+
for ty, dwarf_info in type_infos.items():
|
| 494 |
+
|
| 495 |
+
@njit(debug=True)
|
| 496 |
+
def foo():
|
| 497 |
+
a = ty(10)
|
| 498 |
+
return a
|
| 499 |
+
|
| 500 |
+
metadata = self._get_metadata(foo, sig=())
|
| 501 |
+
metadata_definition_map = self._get_metadata_map(metadata)
|
| 502 |
+
|
| 503 |
+
for k, v in metadata_definition_map.items():
|
| 504 |
+
if 'DILocalVariable(name: "a"' in v:
|
| 505 |
+
lvar = metadata_definition_map[k]
|
| 506 |
+
break
|
| 507 |
+
else:
|
| 508 |
+
assert 0, "missing DILocalVariable 'a'"
|
| 509 |
+
|
| 510 |
+
type_marker = re.match('.*type: (![0-9]+).*', lvar).groups()[0]
|
| 511 |
+
type_decl = metadata_definition_map[type_marker]
|
| 512 |
+
|
| 513 |
+
if 'DW_ATE' in dwarf_info.encoding:
|
| 514 |
+
expected = (f'!DIBasicType(name: "{dwarf_info.name}", '
|
| 515 |
+
f'size: {dwarf_info.bits}, '
|
| 516 |
+
f'encoding: {dwarf_info.encoding})')
|
| 517 |
+
self.assertEqual(type_decl, expected)
|
| 518 |
+
else: # numerical complex type
|
| 519 |
+
# Don't match the whole string, just the known parts
|
| 520 |
+
raw_flt = 'float' if dwarf_info.bits == 64 else 'double'
|
| 521 |
+
expected = (f'distinct !DICompositeType('
|
| 522 |
+
f'tag: {dwarf_info.encoding}, '
|
| 523 |
+
f'name: "{dwarf_info.name} '
|
| 524 |
+
f'({{{raw_flt}, {raw_flt}}})", '
|
| 525 |
+
f'size: {dwarf_info.bits}')
|
| 526 |
+
self.assertIn(expected, type_decl)
|
| 527 |
+
|
| 528 |
+
def test_arrays(self):
|
| 529 |
+
|
| 530 |
+
@njit(debug=True)
|
| 531 |
+
def foo():
|
| 532 |
+
a = np.ones((2, 3), dtype=np.float64)
|
| 533 |
+
return a
|
| 534 |
+
|
| 535 |
+
metadata = self._get_metadata(foo, sig=())
|
| 536 |
+
metadata_definition_map = self._get_metadata_map(metadata)
|
| 537 |
+
|
| 538 |
+
for k, v in metadata_definition_map.items():
|
| 539 |
+
if 'DILocalVariable(name: "a"' in v:
|
| 540 |
+
lvar = metadata_definition_map[k]
|
| 541 |
+
break
|
| 542 |
+
else:
|
| 543 |
+
assert 0, "missing DILocalVariable 'a'"
|
| 544 |
+
|
| 545 |
+
type_marker = re.match('.*type: (![0-9]+).*', lvar).groups()[0]
|
| 546 |
+
type_decl = metadata_definition_map[type_marker]
|
| 547 |
+
|
| 548 |
+
# check type
|
| 549 |
+
self.assertIn("!DICompositeType(tag: DW_TAG_structure_type", type_decl)
|
| 550 |
+
# check name encoding
|
| 551 |
+
self.assertIn(f'name: "{str(types.float64[:, ::1])}', type_decl)
|
| 552 |
+
|
| 553 |
+
# pop out the "elements" of the composite type
|
| 554 |
+
match_elements = re.compile(r'.*elements: (![0-9]+),.*')
|
| 555 |
+
elem_matches = match_elements.match(type_decl).groups()
|
| 556 |
+
self.assertEqual(len(elem_matches), 1)
|
| 557 |
+
elem_match = elem_matches[0]
|
| 558 |
+
# The match should be something like, it's the elements from an array
|
| 559 |
+
# data model.
|
| 560 |
+
# !{!35, !36, !37, !39, !40, !43, !45}'
|
| 561 |
+
struct_markers = metadata_definition_map[elem_match]
|
| 562 |
+
struct_pattern = '!{' + '(![0-9]+), ' * 6 + '(![0-9]+)}'
|
| 563 |
+
match_struct = re.compile(struct_pattern)
|
| 564 |
+
struct_member_matches = match_struct.match(struct_markers).groups()
|
| 565 |
+
self.assertIsNotNone(struct_member_matches is not None)
|
| 566 |
+
data_model = default_manager.lookup(types.float64[:, ::1])
|
| 567 |
+
self.assertEqual(len(struct_member_matches), len(data_model._fields))
|
| 568 |
+
|
| 569 |
+
ptr_size = types.intp.bitwidth
|
| 570 |
+
ptr_re = (r'!DIDerivedType\(tag: DW_TAG_pointer_type, '
|
| 571 |
+
rf'baseType: ![0-9]+, size: {ptr_size}\)')
|
| 572 |
+
int_re = (rf'!DIBasicType\(name: "int{ptr_size}", size: {ptr_size}, '
|
| 573 |
+
r'encoding: DW_ATE_signed\)')
|
| 574 |
+
utuple_re = (r'!DICompositeType\(tag: DW_TAG_array_type, '
|
| 575 |
+
rf'name: "UniTuple\(int{ptr_size} x 2\) '
|
| 576 |
+
rf'\(\[2 x i{ptr_size}\]\)", baseType: ![0-9]+, '
|
| 577 |
+
rf'size: {2 * ptr_size}, elements: ![0-9]+, '
|
| 578 |
+
rf'identifier: "\[2 x i{ptr_size}\]"\)')
|
| 579 |
+
expected = {'meminfo': ptr_re,
|
| 580 |
+
'parent': ptr_re,
|
| 581 |
+
'nitems': int_re,
|
| 582 |
+
'itemsize': int_re,
|
| 583 |
+
'data': ptr_re,
|
| 584 |
+
'shape': utuple_re,
|
| 585 |
+
'strides': utuple_re}
|
| 586 |
+
|
| 587 |
+
# look for `baseType: <>` for the type
|
| 588 |
+
base_type_pattern = r'!DIDerivedType\(.*, baseType: (![0-9]+),.*'
|
| 589 |
+
base_type_matcher = re.compile(base_type_pattern)
|
| 590 |
+
|
| 591 |
+
for ix, field in enumerate(data_model._fields):
|
| 592 |
+
derived_type = metadata_definition_map[struct_member_matches[ix]]
|
| 593 |
+
self.assertIn("DIDerivedType", derived_type)
|
| 594 |
+
self.assertIn(f'name: "{field}"', derived_type)
|
| 595 |
+
base_type_match = base_type_matcher.match(derived_type)
|
| 596 |
+
base_type_matches = base_type_match.groups()
|
| 597 |
+
self.assertEqual(len(base_type_matches), 1)
|
| 598 |
+
base_type_marker = base_type_matches[0]
|
| 599 |
+
data_type = metadata_definition_map[base_type_marker]
|
| 600 |
+
self.assertRegex(data_type, expected[field])
|
| 601 |
+
|
| 602 |
+
def test_debug_optnone(self):
|
| 603 |
+
def get_debug_lines(fn):
|
| 604 |
+
metadata = self._get_metadata(fn, fn.signatures[0])
|
| 605 |
+
lines = self._get_lines_from_debuginfo(metadata)
|
| 606 |
+
return lines
|
| 607 |
+
|
| 608 |
+
def get_func_attrs(fn):
|
| 609 |
+
cres = fn.overloads[fn.signatures[0]]
|
| 610 |
+
lib = cres.library
|
| 611 |
+
fn = lib._final_module.get_function(cres.fndesc.mangled_name)
|
| 612 |
+
attrs = set(b' '.join(fn.attributes).split())
|
| 613 |
+
return attrs
|
| 614 |
+
|
| 615 |
+
def foo():
|
| 616 |
+
n = 10
|
| 617 |
+
c = 0
|
| 618 |
+
for i in range(n):
|
| 619 |
+
c += i
|
| 620 |
+
return c
|
| 621 |
+
|
| 622 |
+
foo_debug = njit(debug=True)(foo)
|
| 623 |
+
foo_debug_optnone = njit(debug=True, _dbg_optnone=True)(foo)
|
| 624 |
+
foo_debug_optnone_inline = njit(debug=True, _dbg_optnone=True,
|
| 625 |
+
forceinline=True)(foo)
|
| 626 |
+
|
| 627 |
+
firstline = foo.__code__.co_firstlineno
|
| 628 |
+
|
| 629 |
+
expected_info = {}
|
| 630 |
+
expected_info[foo_debug] = dict(
|
| 631 |
+
# just the dummy line-0 and the line of the return statement
|
| 632 |
+
lines={0, firstline + 5},
|
| 633 |
+
must_have_attrs=set(),
|
| 634 |
+
must_not_have_attrs=set([b"optnone"]),
|
| 635 |
+
)
|
| 636 |
+
expected_info[foo_debug_optnone] = dict(
|
| 637 |
+
# all the lines should be included
|
| 638 |
+
lines=set(range(firstline + 1, firstline + 6)),
|
| 639 |
+
must_have_attrs=set([b"optnone"]),
|
| 640 |
+
must_not_have_attrs=set(),
|
| 641 |
+
)
|
| 642 |
+
expected_info[foo_debug_optnone_inline] = dict(
|
| 643 |
+
# optnone=True is overridden by forceinline, so this looks like the
|
| 644 |
+
# foo_debug version
|
| 645 |
+
lines={0, firstline + 5},
|
| 646 |
+
must_have_attrs=set([b"alwaysinline"]),
|
| 647 |
+
must_not_have_attrs=set([b"optnone"]),
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
expected_ret = foo()
|
| 651 |
+
|
| 652 |
+
for udt, expected in expected_info.items():
|
| 653 |
+
with self.subTest(udt.targetoptions):
|
| 654 |
+
got = udt()
|
| 655 |
+
self.assertEqual(got, expected_ret)
|
| 656 |
+
|
| 657 |
+
# Compare the line locations in the debug info.
|
| 658 |
+
self.assertEqual(get_debug_lines(udt), expected["lines"])
|
| 659 |
+
|
| 660 |
+
# Check for attributes on the LLVM function
|
| 661 |
+
attrs = get_func_attrs(udt)
|
| 662 |
+
must_have = expected["must_have_attrs"]
|
| 663 |
+
self.assertEqual(attrs & must_have, must_have)
|
| 664 |
+
must_not_have = expected["must_not_have_attrs"]
|
| 665 |
+
self.assertFalse(attrs & must_not_have)
|
| 666 |
+
|
| 667 |
+
def test_omitted_arg(self):
|
| 668 |
+
# See issue 7726
|
| 669 |
+
@njit(debug=True)
|
| 670 |
+
def foo(missing=None):
|
| 671 |
+
pass
|
| 672 |
+
|
| 673 |
+
# check that it will actually compile (verifies DI emission is ok)
|
| 674 |
+
with override_config('DEBUGINFO_DEFAULT', 1):
|
| 675 |
+
foo()
|
| 676 |
+
|
| 677 |
+
metadata = self._get_metadata(foo, sig=(types.Omitted(None),))
|
| 678 |
+
metadata_definition_map = self._get_metadata_map(metadata)
|
| 679 |
+
|
| 680 |
+
# Find DISubroutineType
|
| 681 |
+
tmp_disubr = []
|
| 682 |
+
for md in metadata:
|
| 683 |
+
if "DISubroutineType" in md:
|
| 684 |
+
tmp_disubr.append(md)
|
| 685 |
+
self.assertEqual(len(tmp_disubr), 1)
|
| 686 |
+
disubr = tmp_disubr.pop()
|
| 687 |
+
|
| 688 |
+
disubr_matched = re.match(r'.*!DISubroutineType\(types: ([!0-9]+)\)$',
|
| 689 |
+
disubr)
|
| 690 |
+
self.assertIsNotNone(disubr_matched)
|
| 691 |
+
disubr_groups = disubr_matched.groups()
|
| 692 |
+
self.assertEqual(len(disubr_groups), 1)
|
| 693 |
+
disubr_meta = disubr_groups[0]
|
| 694 |
+
|
| 695 |
+
# Find the types in the DISubroutineType arg list
|
| 696 |
+
disubr_types = metadata_definition_map[disubr_meta]
|
| 697 |
+
disubr_types_matched = re.match(r'!{(.*)}', disubr_types)
|
| 698 |
+
self.assertIsNotNone(disubr_matched)
|
| 699 |
+
disubr_types_groups = disubr_types_matched.groups()
|
| 700 |
+
self.assertEqual(len(disubr_types_groups), 1)
|
| 701 |
+
|
| 702 |
+
# fetch out and assert the last argument type, should be void *
|
| 703 |
+
md_fn_arg = [x.strip() for x in disubr_types_groups[0].split(',')][-1]
|
| 704 |
+
arg_ty = metadata_definition_map[md_fn_arg]
|
| 705 |
+
expected_arg_ty = (r'^.*!DICompositeType\(tag: DW_TAG_structure_type, '
|
| 706 |
+
r'name: "Anonymous struct \({}\)", elements: '
|
| 707 |
+
r'(![0-9]+), identifier: "{}"\)')
|
| 708 |
+
self.assertRegex(arg_ty, expected_arg_ty)
|
| 709 |
+
md_base_ty = re.match(expected_arg_ty, arg_ty).groups()[0]
|
| 710 |
+
base_ty = metadata_definition_map[md_base_ty]
|
| 711 |
+
# expect ir.LiteralStructType([])
|
| 712 |
+
self.assertEqual(base_ty, ('!{}'))
|
| 713 |
+
|
| 714 |
+
def test_missing_source(self):
|
| 715 |
+
strsrc = """
|
| 716 |
+
def foo():
|
| 717 |
+
return 1
|
| 718 |
+
"""
|
| 719 |
+
l = dict()
|
| 720 |
+
exec(dedent(strsrc), {}, l)
|
| 721 |
+
foo = njit(debug=True)(l['foo'])
|
| 722 |
+
|
| 723 |
+
with warnings.catch_warnings(record=True) as w:
|
| 724 |
+
warnings.simplefilter('always', NumbaDebugInfoWarning)
|
| 725 |
+
ignore_internal_warnings()
|
| 726 |
+
foo()
|
| 727 |
+
|
| 728 |
+
self.assertEqual(len(w), 1)
|
| 729 |
+
found = w[0]
|
| 730 |
+
self.assertEqual(found.category, NumbaDebugInfoWarning)
|
| 731 |
+
msg = str(found.message)
|
| 732 |
+
# make sure the warning contains the right message
|
| 733 |
+
self.assertIn('Could not find source for function', msg)
|
| 734 |
+
# and refers to the offending function
|
| 735 |
+
self.assertIn(str(foo.py_func), msg)
|
| 736 |
+
|
| 737 |
+
def test_irregularly_indented_source(self):
|
| 738 |
+
|
| 739 |
+
@njit(debug=True)
|
| 740 |
+
def foo():
|
| 741 |
+
# NOTE: THIS COMMENT MUST START AT COLUMN 0 FOR THIS SAMPLE CODE TO BE VALID # noqa: E115, E501
|
| 742 |
+
return 1
|
| 743 |
+
|
| 744 |
+
with warnings.catch_warnings(record=True) as w:
|
| 745 |
+
warnings.simplefilter('always', NumbaDebugInfoWarning)
|
| 746 |
+
ignore_internal_warnings()
|
| 747 |
+
foo()
|
| 748 |
+
|
| 749 |
+
# No warnings
|
| 750 |
+
self.assertEqual(len(w), 0)
|
| 751 |
+
|
| 752 |
+
metadata = self._get_metadata(foo, foo.signatures[0])
|
| 753 |
+
lines = self._get_lines_from_debuginfo(metadata)
|
| 754 |
+
# Only one line
|
| 755 |
+
self.assertEqual(len(lines), 1)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
if __name__ == '__main__':
|
| 759 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_dictimpl.py
ADDED
|
@@ -0,0 +1,656 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Testing C implementation of the numba dictionary
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import ctypes
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
from numba.tests.support import TestCase
|
| 9 |
+
from numba import _helperlib, jit, typed, types
|
| 10 |
+
from numba.core.config import IS_32BITS
|
| 11 |
+
from numba.core.datamodel.models import UniTupleModel
|
| 12 |
+
from numba.extending import register_model, typeof_impl, unbox, overload
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
DKIX_EMPTY = -1
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
ALIGN = 4 if IS_32BITS else 8
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Dict(object):
|
| 22 |
+
"""A wrapper around the C-API to provide a minimal dictionary object for
|
| 23 |
+
testing.
|
| 24 |
+
"""
|
| 25 |
+
def __init__(self, tc, keysize, valsize):
|
| 26 |
+
"""
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
tc : TestCase instance
|
| 30 |
+
keysize : int
|
| 31 |
+
byte size for the key
|
| 32 |
+
valsize : int
|
| 33 |
+
byte size for the value
|
| 34 |
+
"""
|
| 35 |
+
self.tc = tc
|
| 36 |
+
self.keysize = keysize
|
| 37 |
+
self.valsize = valsize
|
| 38 |
+
self.dp = self.dict_new_minsize(keysize, valsize)
|
| 39 |
+
|
| 40 |
+
def __del__(self):
|
| 41 |
+
self.tc.numba_dict_free(self.dp)
|
| 42 |
+
|
| 43 |
+
def __len__(self):
|
| 44 |
+
return self.dict_length()
|
| 45 |
+
|
| 46 |
+
def __setitem__(self, k, v):
|
| 47 |
+
bk = bytes(k.encode())
|
| 48 |
+
bv = bytes(v.encode())
|
| 49 |
+
self.tc.assertEqual(len(bk), self.keysize)
|
| 50 |
+
self.tc.assertEqual(len(bv), self.valsize)
|
| 51 |
+
self.dict_insert(bk, bv)
|
| 52 |
+
|
| 53 |
+
def __getitem__(self, k):
|
| 54 |
+
bk = bytes(k.encode())
|
| 55 |
+
self.tc.assertEqual(len(bk), self.keysize)
|
| 56 |
+
ix, old = self.dict_lookup(bk)
|
| 57 |
+
if ix == DKIX_EMPTY:
|
| 58 |
+
raise KeyError
|
| 59 |
+
else:
|
| 60 |
+
return old.decode()
|
| 61 |
+
|
| 62 |
+
def __delitem__(self, k):
|
| 63 |
+
bk = bytes(k.encode())
|
| 64 |
+
self.tc.assertEqual(len(bk), self.keysize)
|
| 65 |
+
if not self.dict_delitem(bk):
|
| 66 |
+
raise KeyError(k)
|
| 67 |
+
|
| 68 |
+
def get(self, k):
|
| 69 |
+
try:
|
| 70 |
+
return self[k]
|
| 71 |
+
except KeyError:
|
| 72 |
+
return
|
| 73 |
+
|
| 74 |
+
def items(self):
|
| 75 |
+
return DictIter(self)
|
| 76 |
+
|
| 77 |
+
def popitem(self):
|
| 78 |
+
k, v = self.dict_popitem()
|
| 79 |
+
return k.decode(), v.decode()
|
| 80 |
+
|
| 81 |
+
#
|
| 82 |
+
# The methods below are higher-level wrappers for the C-API
|
| 83 |
+
#
|
| 84 |
+
|
| 85 |
+
def dict_new_minsize(self, key_size, val_size):
|
| 86 |
+
dp = ctypes.c_void_p()
|
| 87 |
+
status = self.tc.numba_dict_new_sized(
|
| 88 |
+
ctypes.byref(dp), 0, key_size, val_size,
|
| 89 |
+
)
|
| 90 |
+
self.tc.assertEqual(status, 0)
|
| 91 |
+
return dp
|
| 92 |
+
|
| 93 |
+
def dict_length(self):
|
| 94 |
+
return self.tc.numba_dict_length(self.dp)
|
| 95 |
+
|
| 96 |
+
def dict_insert(self, key_bytes, val_bytes):
|
| 97 |
+
hashval = hash(key_bytes)
|
| 98 |
+
status = self.tc.numba_dict_insert_ez(
|
| 99 |
+
self.dp, key_bytes, hashval, val_bytes,
|
| 100 |
+
)
|
| 101 |
+
self.tc.assertGreaterEqual(status, 0)
|
| 102 |
+
|
| 103 |
+
def dict_lookup(self, key_bytes):
|
| 104 |
+
hashval = hash(key_bytes)
|
| 105 |
+
oldval_bytes = ctypes.create_string_buffer(self.valsize)
|
| 106 |
+
ix = self.tc.numba_dict_lookup(
|
| 107 |
+
self.dp, key_bytes, hashval, oldval_bytes,
|
| 108 |
+
)
|
| 109 |
+
self.tc.assertGreaterEqual(ix, DKIX_EMPTY)
|
| 110 |
+
return ix, oldval_bytes.value
|
| 111 |
+
|
| 112 |
+
def dict_delitem(self, key_bytes):
|
| 113 |
+
ix, oldval = self.dict_lookup(key_bytes)
|
| 114 |
+
if ix == DKIX_EMPTY:
|
| 115 |
+
return False
|
| 116 |
+
hashval = hash(key_bytes)
|
| 117 |
+
status = self.tc.numba_dict_delitem(self.dp, hashval, ix)
|
| 118 |
+
self.tc.assertEqual(status, 0)
|
| 119 |
+
return True
|
| 120 |
+
|
| 121 |
+
def dict_popitem(self):
|
| 122 |
+
key_bytes = ctypes.create_string_buffer(self.keysize)
|
| 123 |
+
val_bytes = ctypes.create_string_buffer(self.valsize)
|
| 124 |
+
status = self.tc.numba_dict_popitem(self.dp, key_bytes, val_bytes)
|
| 125 |
+
if status != 0:
|
| 126 |
+
if status == -4:
|
| 127 |
+
raise KeyError('popitem(): dictionary is empty')
|
| 128 |
+
else:
|
| 129 |
+
self.tc._fail('Unknown')
|
| 130 |
+
return key_bytes.value, val_bytes.value
|
| 131 |
+
|
| 132 |
+
def dict_iter(self, itptr):
|
| 133 |
+
self.tc.numba_dict_iter(itptr, self.dp)
|
| 134 |
+
|
| 135 |
+
def dict_iter_next(self, itptr):
|
| 136 |
+
bk = ctypes.c_void_p(0)
|
| 137 |
+
bv = ctypes.c_void_p(0)
|
| 138 |
+
status = self.tc.numba_dict_iter_next(
|
| 139 |
+
itptr, ctypes.byref(bk), ctypes.byref(bv),
|
| 140 |
+
)
|
| 141 |
+
if status == -2:
|
| 142 |
+
raise ValueError('dictionary mutated')
|
| 143 |
+
elif status == -3:
|
| 144 |
+
return
|
| 145 |
+
else:
|
| 146 |
+
self.tc.assertGreaterEqual(status, 0)
|
| 147 |
+
|
| 148 |
+
# Check the alignment of the key-value in the entries.
|
| 149 |
+
# We know we are getting the pointers to data in the entries.
|
| 150 |
+
|
| 151 |
+
self.tc.assertEqual(bk.value % ALIGN, 0, msg='key not aligned')
|
| 152 |
+
self.tc.assertEqual(bv.value % ALIGN, 0, msg='val not aligned')
|
| 153 |
+
|
| 154 |
+
key = (ctypes.c_char * self.keysize).from_address(bk.value)
|
| 155 |
+
val = (ctypes.c_char * self.valsize).from_address(bv.value)
|
| 156 |
+
return key.value, val.value
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class DictIter(object):
|
| 160 |
+
"""A iterator for the `Dict.items()`.
|
| 161 |
+
|
| 162 |
+
Only the `.items()` is needed. `.keys` and `.values` can be trivially
|
| 163 |
+
implemented on the `.items` iterator.
|
| 164 |
+
"""
|
| 165 |
+
def __init__(self, parent):
|
| 166 |
+
self.parent = parent
|
| 167 |
+
itsize = self.parent.tc.numba_dict_iter_sizeof()
|
| 168 |
+
self.it_state_buf = (ctypes.c_char_p * itsize)(0)
|
| 169 |
+
self.it = ctypes.cast(self.it_state_buf, ctypes.c_void_p)
|
| 170 |
+
self.parent.dict_iter(self.it)
|
| 171 |
+
|
| 172 |
+
def __iter__(self):
|
| 173 |
+
return self
|
| 174 |
+
|
| 175 |
+
def __next__(self):
|
| 176 |
+
out = self.parent.dict_iter_next(self.it)
|
| 177 |
+
if out is None:
|
| 178 |
+
raise StopIteration
|
| 179 |
+
else:
|
| 180 |
+
k, v = out
|
| 181 |
+
return k.decode(), v.decode()
|
| 182 |
+
|
| 183 |
+
next = __next__ # needed for py2 only
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class Parametrized(tuple):
|
| 187 |
+
"""supporting type for TestDictImpl.test_parametrized_types
|
| 188 |
+
needs to be global to be cacheable"""
|
| 189 |
+
def __init__(self, tup):
|
| 190 |
+
assert all(isinstance(v, str) for v in tup)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class ParametrizedType(types.Type):
|
| 194 |
+
"""this is essentially UniTuple(unicode_type, n)
|
| 195 |
+
BUT type name is the same for all n"""
|
| 196 |
+
|
| 197 |
+
def __init__(self, value):
|
| 198 |
+
super(ParametrizedType, self).__init__('ParametrizedType')
|
| 199 |
+
self.dtype = types.unicode_type
|
| 200 |
+
self.n = len(value)
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def key(self):
|
| 204 |
+
return self.n
|
| 205 |
+
|
| 206 |
+
def __len__(self):
|
| 207 |
+
return self.n
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class TestDictImpl(TestCase):
|
| 211 |
+
def setUp(self):
|
| 212 |
+
"""Bind to the c_helper library and provide the ctypes wrapper.
|
| 213 |
+
"""
|
| 214 |
+
dict_t = ctypes.c_void_p
|
| 215 |
+
iter_t = ctypes.c_void_p
|
| 216 |
+
hash_t = ctypes.c_ssize_t
|
| 217 |
+
|
| 218 |
+
def wrap(name, restype, argtypes=()):
|
| 219 |
+
proto = ctypes.CFUNCTYPE(restype, *argtypes)
|
| 220 |
+
return proto(_helperlib.c_helpers[name])
|
| 221 |
+
|
| 222 |
+
# numba_test_dict()
|
| 223 |
+
self.numba_test_dict = wrap(
|
| 224 |
+
'test_dict',
|
| 225 |
+
ctypes.c_int,
|
| 226 |
+
)
|
| 227 |
+
# numba_dict_new_sized(
|
| 228 |
+
# NB_Dict **out,
|
| 229 |
+
# Py_ssize_t n_keys,
|
| 230 |
+
# Py_ssize_t key_size,
|
| 231 |
+
# Py_ssize_t val_size
|
| 232 |
+
# )
|
| 233 |
+
self.numba_dict_new_sized = wrap(
|
| 234 |
+
'dict_new_sized',
|
| 235 |
+
ctypes.c_int,
|
| 236 |
+
[
|
| 237 |
+
ctypes.POINTER(dict_t), # out
|
| 238 |
+
ctypes.c_ssize_t, # n_keys
|
| 239 |
+
ctypes.c_ssize_t, # key_size
|
| 240 |
+
ctypes.c_ssize_t, # val_size
|
| 241 |
+
],
|
| 242 |
+
)
|
| 243 |
+
# numba_dict_free(NB_Dict *d)
|
| 244 |
+
self.numba_dict_free = wrap(
|
| 245 |
+
'dict_free',
|
| 246 |
+
None,
|
| 247 |
+
[dict_t],
|
| 248 |
+
)
|
| 249 |
+
# numba_dict_length(NB_Dict *d)
|
| 250 |
+
self.numba_dict_length = wrap(
|
| 251 |
+
'dict_length',
|
| 252 |
+
ctypes.c_ssize_t,
|
| 253 |
+
[dict_t],
|
| 254 |
+
)
|
| 255 |
+
# numba_dict_insert_ez(
|
| 256 |
+
# NB_Dict *d,
|
| 257 |
+
# const char *key_bytes,
|
| 258 |
+
# Py_hash_t hash,
|
| 259 |
+
# const char *val_bytes,
|
| 260 |
+
# )
|
| 261 |
+
self.numba_dict_insert_ez = wrap(
|
| 262 |
+
'dict_insert_ez',
|
| 263 |
+
ctypes.c_int,
|
| 264 |
+
[
|
| 265 |
+
dict_t, # d
|
| 266 |
+
ctypes.c_char_p, # key_bytes
|
| 267 |
+
hash_t, # hash
|
| 268 |
+
ctypes.c_char_p, # val_bytes
|
| 269 |
+
],
|
| 270 |
+
)
|
| 271 |
+
# numba_dict_lookup(
|
| 272 |
+
# NB_Dict *d,
|
| 273 |
+
# const char *key_bytes,
|
| 274 |
+
# Py_hash_t hash,
|
| 275 |
+
# char *oldval_bytes
|
| 276 |
+
# )
|
| 277 |
+
self.numba_dict_lookup = wrap(
|
| 278 |
+
'dict_lookup',
|
| 279 |
+
ctypes.c_ssize_t,
|
| 280 |
+
[
|
| 281 |
+
dict_t, # d
|
| 282 |
+
ctypes.c_char_p, # key_bytes
|
| 283 |
+
hash_t, # hash
|
| 284 |
+
ctypes.c_char_p, # oldval_bytes
|
| 285 |
+
],
|
| 286 |
+
)
|
| 287 |
+
# numba_dict_delitem(
|
| 288 |
+
# NB_Dict *d,
|
| 289 |
+
# Py_hash_t hash,
|
| 290 |
+
# Py_ssize_t ix
|
| 291 |
+
# )
|
| 292 |
+
self.numba_dict_delitem = wrap(
|
| 293 |
+
'dict_delitem',
|
| 294 |
+
ctypes.c_int,
|
| 295 |
+
[
|
| 296 |
+
dict_t, # d
|
| 297 |
+
hash_t, # hash
|
| 298 |
+
ctypes.c_ssize_t, # ix
|
| 299 |
+
],
|
| 300 |
+
)
|
| 301 |
+
# numba_dict_popitem(
|
| 302 |
+
# NB_Dict *d,
|
| 303 |
+
# char *key_bytes,
|
| 304 |
+
# char *val_bytes
|
| 305 |
+
# )
|
| 306 |
+
self.numba_dict_popitem = wrap(
|
| 307 |
+
'dict_popitem',
|
| 308 |
+
ctypes.c_int,
|
| 309 |
+
[
|
| 310 |
+
dict_t, # d
|
| 311 |
+
ctypes.c_char_p, # key_bytes
|
| 312 |
+
ctypes.c_char_p, # val_bytes
|
| 313 |
+
],
|
| 314 |
+
)
|
| 315 |
+
# numba_dict_iter_sizeof()
|
| 316 |
+
self.numba_dict_iter_sizeof = wrap(
|
| 317 |
+
'dict_iter_sizeof',
|
| 318 |
+
ctypes.c_size_t,
|
| 319 |
+
)
|
| 320 |
+
# numba_dict_iter(
|
| 321 |
+
# NB_DictIter *it,
|
| 322 |
+
# NB_Dict *d
|
| 323 |
+
# )
|
| 324 |
+
self.numba_dict_iter = wrap(
|
| 325 |
+
'dict_iter',
|
| 326 |
+
None,
|
| 327 |
+
[
|
| 328 |
+
iter_t,
|
| 329 |
+
dict_t,
|
| 330 |
+
],
|
| 331 |
+
)
|
| 332 |
+
# numba_dict_iter_next(
|
| 333 |
+
# NB_DictIter *it,
|
| 334 |
+
# const char **key_ptr,
|
| 335 |
+
# const char **val_ptr
|
| 336 |
+
# )
|
| 337 |
+
self.numba_dict_iter_next = wrap(
|
| 338 |
+
'dict_iter_next',
|
| 339 |
+
ctypes.c_int,
|
| 340 |
+
[
|
| 341 |
+
iter_t, # it
|
| 342 |
+
ctypes.POINTER(ctypes.c_void_p), # key_ptr
|
| 343 |
+
ctypes.POINTER(ctypes.c_void_p), # val_ptr
|
| 344 |
+
],
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
def test_simple_c_test(self):
|
| 348 |
+
# Runs the basic test in C.
|
| 349 |
+
ret = self.numba_test_dict()
|
| 350 |
+
self.assertEqual(ret, 0)
|
| 351 |
+
|
| 352 |
+
def test_insertion_small(self):
|
| 353 |
+
# Tests insertion and lookup for a small dict.
|
| 354 |
+
d = Dict(self, 4, 8)
|
| 355 |
+
self.assertEqual(len(d), 0)
|
| 356 |
+
self.assertIsNone(d.get('abcd'))
|
| 357 |
+
|
| 358 |
+
# First key
|
| 359 |
+
d['abcd'] = 'beefcafe'
|
| 360 |
+
self.assertEqual(len(d), 1)
|
| 361 |
+
self.assertIsNotNone(d.get('abcd'))
|
| 362 |
+
self.assertEqual(d['abcd'], 'beefcafe')
|
| 363 |
+
|
| 364 |
+
# Duplicated key replaces
|
| 365 |
+
d['abcd'] = 'cafe0000'
|
| 366 |
+
self.assertEqual(len(d), 1)
|
| 367 |
+
self.assertEqual(d['abcd'], 'cafe0000')
|
| 368 |
+
|
| 369 |
+
# Second key
|
| 370 |
+
d['abce'] = 'cafe0001'
|
| 371 |
+
self.assertEqual(len(d), 2)
|
| 372 |
+
self.assertEqual(d['abcd'], 'cafe0000')
|
| 373 |
+
self.assertEqual(d['abce'], 'cafe0001')
|
| 374 |
+
|
| 375 |
+
# Third key
|
| 376 |
+
d['abcf'] = 'cafe0002'
|
| 377 |
+
self.assertEqual(len(d), 3)
|
| 378 |
+
self.assertEqual(d['abcd'], 'cafe0000')
|
| 379 |
+
self.assertEqual(d['abce'], 'cafe0001')
|
| 380 |
+
self.assertEqual(d['abcf'], 'cafe0002')
|
| 381 |
+
|
| 382 |
+
def check_insertion_many(self, nmax):
|
| 383 |
+
# Helper to test insertion/lookup/resize
|
| 384 |
+
d = Dict(self, 8, 8)
|
| 385 |
+
|
| 386 |
+
def make_key(v):
|
| 387 |
+
return "key_{:04}".format(v)
|
| 388 |
+
|
| 389 |
+
def make_val(v):
|
| 390 |
+
return "val_{:04}".format(v)
|
| 391 |
+
|
| 392 |
+
# Check insert
|
| 393 |
+
for i in range(nmax):
|
| 394 |
+
d[make_key(i)] = make_val(i)
|
| 395 |
+
self.assertEqual(len(d), i + 1)
|
| 396 |
+
|
| 397 |
+
# Check lookup
|
| 398 |
+
for i in range(nmax):
|
| 399 |
+
self.assertEqual(d[make_key(i)], make_val(i))
|
| 400 |
+
|
| 401 |
+
def test_insertion_many(self):
|
| 402 |
+
# Test insertion for differently sized dict
|
| 403 |
+
# Around minsize
|
| 404 |
+
self.check_insertion_many(nmax=7)
|
| 405 |
+
self.check_insertion_many(nmax=8)
|
| 406 |
+
self.check_insertion_many(nmax=9)
|
| 407 |
+
# Around nmax = 32
|
| 408 |
+
self.check_insertion_many(nmax=31)
|
| 409 |
+
self.check_insertion_many(nmax=32)
|
| 410 |
+
self.check_insertion_many(nmax=33)
|
| 411 |
+
# Around nmax = 1024
|
| 412 |
+
self.check_insertion_many(nmax=1023)
|
| 413 |
+
self.check_insertion_many(nmax=1024)
|
| 414 |
+
self.check_insertion_many(nmax=1025)
|
| 415 |
+
# Around nmax = 4096
|
| 416 |
+
self.check_insertion_many(nmax=4095)
|
| 417 |
+
self.check_insertion_many(nmax=4096)
|
| 418 |
+
self.check_insertion_many(nmax=4097)
|
| 419 |
+
|
| 420 |
+
def test_deletion_small(self):
|
| 421 |
+
# Test deletion
|
| 422 |
+
d = Dict(self, 4, 8)
|
| 423 |
+
self.assertEqual(len(d), 0)
|
| 424 |
+
self.assertIsNone(d.get('abcd'))
|
| 425 |
+
|
| 426 |
+
d['abcd'] = 'cafe0000'
|
| 427 |
+
d['abce'] = 'cafe0001'
|
| 428 |
+
d['abcf'] = 'cafe0002'
|
| 429 |
+
|
| 430 |
+
self.assertEqual(len(d), 3)
|
| 431 |
+
self.assertEqual(d['abcd'], 'cafe0000')
|
| 432 |
+
self.assertEqual(d['abce'], 'cafe0001')
|
| 433 |
+
self.assertEqual(d['abcf'], 'cafe0002')
|
| 434 |
+
self.assertEqual(len(d), 3)
|
| 435 |
+
|
| 436 |
+
# Delete first item
|
| 437 |
+
del d['abcd']
|
| 438 |
+
self.assertIsNone(d.get('abcd'))
|
| 439 |
+
self.assertEqual(d['abce'], 'cafe0001')
|
| 440 |
+
self.assertEqual(d['abcf'], 'cafe0002')
|
| 441 |
+
self.assertEqual(len(d), 2)
|
| 442 |
+
|
| 443 |
+
# Delete first item again
|
| 444 |
+
with self.assertRaises(KeyError):
|
| 445 |
+
del d['abcd']
|
| 446 |
+
|
| 447 |
+
# Delete third
|
| 448 |
+
del d['abcf']
|
| 449 |
+
self.assertIsNone(d.get('abcd'))
|
| 450 |
+
self.assertEqual(d['abce'], 'cafe0001')
|
| 451 |
+
self.assertIsNone(d.get('abcf'))
|
| 452 |
+
self.assertEqual(len(d), 1)
|
| 453 |
+
|
| 454 |
+
# Delete second
|
| 455 |
+
del d['abce']
|
| 456 |
+
self.assertIsNone(d.get('abcd'))
|
| 457 |
+
self.assertIsNone(d.get('abce'))
|
| 458 |
+
self.assertIsNone(d.get('abcf'))
|
| 459 |
+
self.assertEqual(len(d), 0)
|
| 460 |
+
|
| 461 |
+
def check_delete_randomly(self, nmax, ndrop, nrefill, seed=0):
|
| 462 |
+
# Helper to test deletion
|
| 463 |
+
random.seed(seed)
|
| 464 |
+
|
| 465 |
+
d = Dict(self, 8, 8)
|
| 466 |
+
keys = {}
|
| 467 |
+
|
| 468 |
+
def make_key(v):
|
| 469 |
+
return "k_{:06x}".format(v)
|
| 470 |
+
|
| 471 |
+
def make_val(v):
|
| 472 |
+
return "v_{:06x}".format(v)
|
| 473 |
+
|
| 474 |
+
for i in range(nmax):
|
| 475 |
+
d[make_key(i)] = make_val(i)
|
| 476 |
+
|
| 477 |
+
# Fill to nmax
|
| 478 |
+
for i in range(nmax):
|
| 479 |
+
k = make_key(i)
|
| 480 |
+
v = make_val(i)
|
| 481 |
+
keys[k] = v
|
| 482 |
+
self.assertEqual(d[k], v)
|
| 483 |
+
|
| 484 |
+
self.assertEqual(len(d), nmax)
|
| 485 |
+
|
| 486 |
+
# Randomly drop
|
| 487 |
+
droplist = random.sample(list(keys), ndrop)
|
| 488 |
+
remain = keys.copy()
|
| 489 |
+
for i, k in enumerate(droplist, start=1):
|
| 490 |
+
del d[k]
|
| 491 |
+
del remain[k]
|
| 492 |
+
self.assertEqual(len(d), nmax - i)
|
| 493 |
+
self.assertEqual(len(d), nmax - ndrop)
|
| 494 |
+
|
| 495 |
+
# Make sure everything dropped is gone
|
| 496 |
+
for k in droplist:
|
| 497 |
+
self.assertIsNone(d.get(k))
|
| 498 |
+
|
| 499 |
+
# Make sure everything else is still here
|
| 500 |
+
for k in remain:
|
| 501 |
+
self.assertEqual(d[k], remain[k])
|
| 502 |
+
|
| 503 |
+
# Refill
|
| 504 |
+
for i in range(nrefill):
|
| 505 |
+
k = make_key(nmax + i)
|
| 506 |
+
v = make_val(nmax + i)
|
| 507 |
+
remain[k] = v
|
| 508 |
+
d[k] = v
|
| 509 |
+
|
| 510 |
+
self.assertEqual(len(remain), len(d))
|
| 511 |
+
|
| 512 |
+
# Make sure everything is here
|
| 513 |
+
for k in remain:
|
| 514 |
+
self.assertEqual(d[k], remain[k])
|
| 515 |
+
|
| 516 |
+
def test_delete_randomly(self):
|
| 517 |
+
# Test deletion for differently sized dict
|
| 518 |
+
self.check_delete_randomly(nmax=8, ndrop=2, nrefill=2)
|
| 519 |
+
self.check_delete_randomly(nmax=13, ndrop=10, nrefill=31)
|
| 520 |
+
self.check_delete_randomly(nmax=100, ndrop=50, nrefill=200)
|
| 521 |
+
self.check_delete_randomly(nmax=100, ndrop=99, nrefill=100)
|
| 522 |
+
self.check_delete_randomly(nmax=100, ndrop=100, nrefill=100)
|
| 523 |
+
self.check_delete_randomly(nmax=1024, ndrop=999, nrefill=1)
|
| 524 |
+
self.check_delete_randomly(nmax=1024, ndrop=999, nrefill=2048)
|
| 525 |
+
|
| 526 |
+
def test_delete_randomly_large(self):
|
| 527 |
+
# Go beyond 2^16 to exercise large indices.
|
| 528 |
+
# Internally, size of index changes as the hashtable size changes.
|
| 529 |
+
# Size of index can be 8, 16, 32 or 64 bytes (on 64-bit).
|
| 530 |
+
# We are not inserting >2^32 elements because of limitation of time.
|
| 531 |
+
self.check_delete_randomly(nmax=2**17, ndrop=2**16, nrefill=2**10)
|
| 532 |
+
|
| 533 |
+
def test_popitem(self):
|
| 534 |
+
nmax = 10
|
| 535 |
+
d = Dict(self, 8, 8)
|
| 536 |
+
|
| 537 |
+
def make_key(v):
|
| 538 |
+
return "k_{:06x}".format(v)
|
| 539 |
+
|
| 540 |
+
def make_val(v):
|
| 541 |
+
return "v_{:06x}".format(v)
|
| 542 |
+
|
| 543 |
+
for i in range(nmax):
|
| 544 |
+
d[make_key(i)] = make_val(i)
|
| 545 |
+
|
| 546 |
+
self.assertEqual(len(d), nmax)
|
| 547 |
+
k, v = d.popitem()
|
| 548 |
+
self.assertEqual(len(d), nmax - 1)
|
| 549 |
+
self.assertEqual(k, make_key(len(d)))
|
| 550 |
+
self.assertEqual(v, make_val(len(d)))
|
| 551 |
+
|
| 552 |
+
while len(d):
|
| 553 |
+
n = len(d)
|
| 554 |
+
k, v = d.popitem()
|
| 555 |
+
self.assertEqual(len(d), n - 1)
|
| 556 |
+
self.assertEqual(k, make_key(len(d)))
|
| 557 |
+
self.assertEqual(v, make_val(len(d)))
|
| 558 |
+
|
| 559 |
+
self.assertEqual(len(d), 0)
|
| 560 |
+
with self.assertRaises(KeyError) as raises:
|
| 561 |
+
d.popitem()
|
| 562 |
+
self.assertIn(
|
| 563 |
+
'popitem(): dictionary is empty',
|
| 564 |
+
str(raises.exception),
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
def test_iter_items(self):
|
| 568 |
+
# Test .items iteration
|
| 569 |
+
d = Dict(self, 4, 4)
|
| 570 |
+
nmax = 1000
|
| 571 |
+
|
| 572 |
+
def make_key(v):
|
| 573 |
+
return "{:04}".format(v)
|
| 574 |
+
|
| 575 |
+
def make_val(v):
|
| 576 |
+
return "{:04}".format(v + nmax)
|
| 577 |
+
|
| 578 |
+
for i in range(nmax):
|
| 579 |
+
d[make_key(i)] = make_val(i)
|
| 580 |
+
|
| 581 |
+
# Check that the everything is ordered
|
| 582 |
+
for i, (k, v) in enumerate(d.items()):
|
| 583 |
+
self.assertEqual(make_key(i), k)
|
| 584 |
+
self.assertEqual(make_val(i), v)
|
| 585 |
+
|
| 586 |
+
def check_sizing(self, key_size, val_size, nmax):
|
| 587 |
+
# Helper to verify different key/value sizes.
|
| 588 |
+
d = Dict(self, key_size, val_size)
|
| 589 |
+
|
| 590 |
+
def make_key(v):
|
| 591 |
+
return "{:0{}}".format(v, key_size)[:key_size]
|
| 592 |
+
|
| 593 |
+
def make_val(v):
|
| 594 |
+
return "{:0{}}".format(nmax - v - 1, val_size)[:val_size]
|
| 595 |
+
|
| 596 |
+
for i in range(nmax):
|
| 597 |
+
d[make_key(i)] = make_val(i)
|
| 598 |
+
|
| 599 |
+
# Check that the everything is ordered
|
| 600 |
+
for i, (k, v) in enumerate(d.items()):
|
| 601 |
+
self.assertEqual(make_key(i), k)
|
| 602 |
+
self.assertEqual(make_val(i), v)
|
| 603 |
+
|
| 604 |
+
def test_sizing(self):
|
| 605 |
+
# Check different sizes of the key & value.
|
| 606 |
+
for i in range(1, 8):
|
| 607 |
+
self.check_sizing(key_size=i, val_size=i, nmax=2**i)
|
| 608 |
+
|
| 609 |
+
def test_parameterized_types(self):
|
| 610 |
+
"""https://github.com/numba/numba/issues/6401"""
|
| 611 |
+
|
| 612 |
+
register_model(ParametrizedType)(UniTupleModel)
|
| 613 |
+
|
| 614 |
+
@typeof_impl.register(Parametrized)
|
| 615 |
+
def typeof_unit(val, c):
|
| 616 |
+
return ParametrizedType(val)
|
| 617 |
+
|
| 618 |
+
@unbox(ParametrizedType)
|
| 619 |
+
def unbox_parametrized(typ, obj, context):
|
| 620 |
+
return context.unbox(types.UniTuple(typ.dtype, len(typ)), obj)
|
| 621 |
+
|
| 622 |
+
def dict_vs_cache_vs_parametrized(v):
|
| 623 |
+
assert 0
|
| 624 |
+
|
| 625 |
+
@overload(dict_vs_cache_vs_parametrized)
|
| 626 |
+
def ol_dict_vs_cache_vs_parametrized(v):
|
| 627 |
+
typ = v
|
| 628 |
+
|
| 629 |
+
def objmode_vs_cache_vs_parametrized_impl(v):
|
| 630 |
+
# typed.List shows same behaviour after fix for #6397
|
| 631 |
+
d = typed.Dict.empty(types.unicode_type, typ)
|
| 632 |
+
d['data'] = v
|
| 633 |
+
|
| 634 |
+
return objmode_vs_cache_vs_parametrized_impl
|
| 635 |
+
|
| 636 |
+
@jit(nopython=True, cache=True)
|
| 637 |
+
def set_parametrized_data(x, y):
|
| 638 |
+
# Has had a tendency to segfault when the compiled function
|
| 639 |
+
# was loaded from cache in a different process than the one
|
| 640 |
+
# it was originally compiled in.
|
| 641 |
+
# The new process is simulated below by resetting the dispatchers
|
| 642 |
+
# and the target context
|
| 643 |
+
dict_vs_cache_vs_parametrized(x)
|
| 644 |
+
dict_vs_cache_vs_parametrized(y)
|
| 645 |
+
|
| 646 |
+
x, y = Parametrized(('a', 'b')), Parametrized(('a',))
|
| 647 |
+
set_parametrized_data(x, y)
|
| 648 |
+
|
| 649 |
+
# reset dispatchers and targetctx to force re-load from cache as if a
|
| 650 |
+
# new process would jit the function
|
| 651 |
+
set_parametrized_data._make_finalizer()()
|
| 652 |
+
set_parametrized_data._reset_overloads()
|
| 653 |
+
set_parametrized_data.targetctx.init()
|
| 654 |
+
|
| 655 |
+
for ii in range(50): # <- sometimes works a few times
|
| 656 |
+
self.assertIsNone(set_parametrized_data(x, y))
|
lib/python3.10/site-packages/numba/tests/test_dicts.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from numba import njit, jit
|
| 3 |
+
from numba.core.errors import TypingError
|
| 4 |
+
import unittest
|
| 5 |
+
from numba.tests.support import TestCase
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def build_map():
|
| 9 |
+
return {0: 1, 2: 3}
|
| 10 |
+
|
| 11 |
+
def build_map_from_local_vars():
|
| 12 |
+
# There used to be a crash due to wrong IR generation for STORE_MAP
|
| 13 |
+
x = TestCase
|
| 14 |
+
return {0: x, x: 1}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class DictTestCase(TestCase):
|
| 18 |
+
|
| 19 |
+
def check(self, pyfunc):
|
| 20 |
+
cfunc = jit(forceobj=True)(pyfunc)
|
| 21 |
+
self.assertPreciseEqual(pyfunc(), cfunc())
|
| 22 |
+
|
| 23 |
+
def test_build_map(self):
|
| 24 |
+
self.check(build_map)
|
| 25 |
+
|
| 26 |
+
def test_build_map_from_local_vars(self):
|
| 27 |
+
self.check(build_map_from_local_vars)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestCompiledDict(TestCase):
|
| 31 |
+
"""Testing `dict()` and `{}` usage that are redirected to
|
| 32 |
+
`numba.typed.Dict`.
|
| 33 |
+
"""
|
| 34 |
+
def test_use_dict(self):
|
| 35 |
+
# Test dict()
|
| 36 |
+
@njit
|
| 37 |
+
def foo():
|
| 38 |
+
d = dict()
|
| 39 |
+
d[1] = 2
|
| 40 |
+
return d
|
| 41 |
+
|
| 42 |
+
d = foo()
|
| 43 |
+
self.assertEqual(d, {1: 2})
|
| 44 |
+
|
| 45 |
+
def test_use_dict_iterable_args(self):
|
| 46 |
+
# Test dict(iterable)
|
| 47 |
+
@njit
|
| 48 |
+
def dict_iterable_1(a, b):
|
| 49 |
+
d = dict(zip(a, b))
|
| 50 |
+
return d
|
| 51 |
+
|
| 52 |
+
@njit
|
| 53 |
+
def dict_iterable_2():
|
| 54 |
+
# from python docs
|
| 55 |
+
return dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
|
| 56 |
+
|
| 57 |
+
inps = (
|
| 58 |
+
([1, 2, 3], [4, 5, 6]),
|
| 59 |
+
(np.arange(4), np.arange(4)),
|
| 60 |
+
([1, 2, 3], 'abc'),
|
| 61 |
+
([1, 2, 3, 4], 'abc'),
|
| 62 |
+
)
|
| 63 |
+
for a, b in inps:
|
| 64 |
+
d = dict_iterable_1(a, b)
|
| 65 |
+
self.assertEqual(d, dict(zip(a, b)))
|
| 66 |
+
|
| 67 |
+
self.assertEqual(dict_iterable_2(), dict_iterable_2.py_func())
|
| 68 |
+
|
| 69 |
+
def test_ctor_iterable_tuple(self):
|
| 70 |
+
@njit
|
| 71 |
+
def ctor():
|
| 72 |
+
return dict(((1, 2), (1, 2)))
|
| 73 |
+
|
| 74 |
+
expected = dict({1: 2})
|
| 75 |
+
got = ctor()
|
| 76 |
+
self.assertEqual(expected, got)
|
| 77 |
+
|
| 78 |
+
def test_unsupported_dict_usage(self):
|
| 79 |
+
# Test dict(dict())
|
| 80 |
+
from numba.core.typing.dictdecl import _message_dict_support
|
| 81 |
+
|
| 82 |
+
@njit
|
| 83 |
+
def ctor1():
|
| 84 |
+
d = dict()
|
| 85 |
+
d[1] = 2
|
| 86 |
+
return dict(d)
|
| 87 |
+
|
| 88 |
+
@njit
|
| 89 |
+
def ctor2():
|
| 90 |
+
return dict(((1, 2), (3, 'a')))
|
| 91 |
+
|
| 92 |
+
@njit
|
| 93 |
+
def ctor3():
|
| 94 |
+
return dict((('a', 'b', 'c'), ('d', 'e', 'f')))
|
| 95 |
+
|
| 96 |
+
@njit
|
| 97 |
+
def ctor4():
|
| 98 |
+
return dict((({}, 1), ({}, 2)))
|
| 99 |
+
|
| 100 |
+
_non_iter_args = "Non-iterable args used in dict(iterable)"
|
| 101 |
+
_dict_upd_item_len = "dictionary update sequence element has length 3;"
|
| 102 |
+
_unhashable_type = "Unhashable type"
|
| 103 |
+
|
| 104 |
+
inputs = [
|
| 105 |
+
(ctor1, TypingError, _message_dict_support),
|
| 106 |
+
(ctor2, TypingError, _non_iter_args),
|
| 107 |
+
(ctor3, TypingError, _dict_upd_item_len),
|
| 108 |
+
(ctor4, TypingError, _unhashable_type),
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
for func, exc, msg in inputs:
|
| 112 |
+
with self.assertRaises(exc) as raises:
|
| 113 |
+
func()
|
| 114 |
+
|
| 115 |
+
self.assertIn(msg, str(raises.exception))
|
| 116 |
+
|
| 117 |
+
def test_use_curlybraces(self):
|
| 118 |
+
# Test {} with empty args
|
| 119 |
+
@njit
|
| 120 |
+
def foo():
|
| 121 |
+
d = {}
|
| 122 |
+
d[1] = 2
|
| 123 |
+
return d
|
| 124 |
+
|
| 125 |
+
d = foo()
|
| 126 |
+
self.assertEqual(d, {1: 2})
|
| 127 |
+
|
| 128 |
+
def test_use_curlybraces_with_init1(self):
|
| 129 |
+
# Test {} with 1 item
|
| 130 |
+
@njit
|
| 131 |
+
def foo():
|
| 132 |
+
return {1: 2}
|
| 133 |
+
|
| 134 |
+
d = foo()
|
| 135 |
+
self.assertEqual(d, {1: 2})
|
| 136 |
+
|
| 137 |
+
def test_use_curlybraces_with_initmany(self):
|
| 138 |
+
# Test {} with many items
|
| 139 |
+
@njit
|
| 140 |
+
def foo():
|
| 141 |
+
return {1: 2.2, 3: 4.4, 5: 6.6}
|
| 142 |
+
|
| 143 |
+
d = foo()
|
| 144 |
+
self.assertEqual(d, {1: 2.2, 3: 4.4, 5: 6.6})
|
| 145 |
+
|
| 146 |
+
def test_curlybraces_init_with_coercion(self):
|
| 147 |
+
# Type coercion at dict init is tested
|
| 148 |
+
@njit
|
| 149 |
+
def foo():
|
| 150 |
+
return {1: 2.2, 3: 4, 5: 6}
|
| 151 |
+
|
| 152 |
+
self.assertEqual(foo(), foo.py_func())
|
| 153 |
+
|
| 154 |
+
def test_use_curlybraces_with_manyvar(self):
|
| 155 |
+
# Test using variable in {}
|
| 156 |
+
@njit
|
| 157 |
+
def foo(x, y):
|
| 158 |
+
return {x: 1, y: x + y}
|
| 159 |
+
|
| 160 |
+
x, y = 10, 20
|
| 161 |
+
self.assertEqual(foo(x, y), foo.py_func(x, y))
|
| 162 |
+
|
| 163 |
+
def test_mixed_curlybraces_and_dict(self):
|
| 164 |
+
# Test mixed use of {} and dict()
|
| 165 |
+
@njit
|
| 166 |
+
def foo():
|
| 167 |
+
k = dict()
|
| 168 |
+
k[1] = {1: 3}
|
| 169 |
+
k[2] = {4: 2}
|
| 170 |
+
return k
|
| 171 |
+
|
| 172 |
+
self.assertEqual(foo(), foo.py_func())
|
| 173 |
+
|
| 174 |
+
def test_dict_use_with_none_value(self):
|
| 175 |
+
# Test that NoneType cannot be used as value for Dict
|
| 176 |
+
@njit
|
| 177 |
+
def foo():
|
| 178 |
+
k = {1: None}
|
| 179 |
+
return k
|
| 180 |
+
|
| 181 |
+
with self.assertRaises(TypingError) as raises:
|
| 182 |
+
foo()
|
| 183 |
+
self.assertIn(
|
| 184 |
+
"Dict.value_type cannot be of type none",
|
| 185 |
+
str(raises.exception),
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_dict_use_with_optional_value(self):
|
| 190 |
+
# Test that Optional cannot be used as value for Dict
|
| 191 |
+
@njit
|
| 192 |
+
def foo(choice):
|
| 193 |
+
optional = 2.5 if choice else None
|
| 194 |
+
k = {1: optional}
|
| 195 |
+
return k
|
| 196 |
+
|
| 197 |
+
with self.assertRaises(TypingError) as raises:
|
| 198 |
+
foo(True)
|
| 199 |
+
self.assertIn(
|
| 200 |
+
"Dict.value_type cannot be of type OptionalType(float64)",
|
| 201 |
+
str(raises.exception),
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
def test_dict_use_with_optional_key(self):
|
| 205 |
+
# Test that Optional cannot be used as a key for Dict
|
| 206 |
+
@njit
|
| 207 |
+
def foo(choice):
|
| 208 |
+
k = {2.5 if choice else None: 1}
|
| 209 |
+
return k
|
| 210 |
+
|
| 211 |
+
with self.assertRaises(TypingError) as raises:
|
| 212 |
+
foo(True)
|
| 213 |
+
self.assertIn(
|
| 214 |
+
"Dict.key_type cannot be of type OptionalType(float64)",
|
| 215 |
+
str(raises.exception),
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def test_dict_use_with_none_key(self):
|
| 219 |
+
# Test that NoneType cannot be used as a key for Dict
|
| 220 |
+
@njit
|
| 221 |
+
def foo():
|
| 222 |
+
k = {None: 1}
|
| 223 |
+
return k
|
| 224 |
+
|
| 225 |
+
with self.assertRaises(TypingError) as raises:
|
| 226 |
+
foo()
|
| 227 |
+
self.assertIn(
|
| 228 |
+
"Dict.key_type cannot be of type none",
|
| 229 |
+
str(raises.exception),
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if __name__ == '__main__':
|
| 233 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_dyn_func.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import numba
|
| 4 |
+
from numba.tests.support import TestCase
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Issue455(object):
|
| 8 |
+
"""
|
| 9 |
+
Test code from issue 455.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.f = []
|
| 14 |
+
|
| 15 |
+
def create_f(self):
|
| 16 |
+
code = """
|
| 17 |
+
def f(x):
|
| 18 |
+
n = x.shape[0]
|
| 19 |
+
for i in range(n):
|
| 20 |
+
x[i] = 1.
|
| 21 |
+
"""
|
| 22 |
+
d = {}
|
| 23 |
+
exec(code.strip(), d)
|
| 24 |
+
self.f.append(numba.jit("void(f8[:])", nopython=True)(d['f']))
|
| 25 |
+
|
| 26 |
+
def call_f(self):
|
| 27 |
+
a = np.zeros(10)
|
| 28 |
+
for f in self.f:
|
| 29 |
+
f(a)
|
| 30 |
+
return a
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestDynFunc(TestCase):
|
| 34 |
+
|
| 35 |
+
def test_issue_455(self):
|
| 36 |
+
inst = Issue455()
|
| 37 |
+
inst.create_f()
|
| 38 |
+
a = inst.call_f()
|
| 39 |
+
self.assertPreciseEqual(a, np.ones_like(a))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_enums.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import unittest
|
| 8 |
+
from numba import jit, vectorize, int8, int16, int32
|
| 9 |
+
|
| 10 |
+
from numba.tests.support import TestCase
|
| 11 |
+
from numba.tests.enum_usecases import (Color, Shape, Shake,
|
| 12 |
+
Planet, RequestError,
|
| 13 |
+
IntEnumWithNegatives)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def compare_usecase(a, b):
|
| 17 |
+
return a == b, a != b, a is b, a is not b
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def getattr_usecase(a):
|
| 21 |
+
# Lookup of a enum member on its class
|
| 22 |
+
return a is Color.red
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def getitem_usecase(a):
|
| 26 |
+
"""Lookup enum member by string name"""
|
| 27 |
+
return a is Color['red']
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def identity_usecase(a, b, c):
|
| 31 |
+
return (a is Shake.mint,
|
| 32 |
+
b is Shape.circle,
|
| 33 |
+
c is RequestError.internal_error,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def make_constant_usecase(const):
|
| 38 |
+
def constant_usecase(a):
|
| 39 |
+
return a is const
|
| 40 |
+
return constant_usecase
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def return_usecase(a, b, pred):
|
| 44 |
+
return a if pred else b
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def int_coerce_usecase(x):
|
| 48 |
+
# Implicit coercion of intenums to ints
|
| 49 |
+
if x > RequestError.internal_error:
|
| 50 |
+
return x - RequestError.not_found
|
| 51 |
+
else:
|
| 52 |
+
return x + Shape.circle
|
| 53 |
+
|
| 54 |
+
def int_cast_usecase(x):
|
| 55 |
+
# Explicit coercion of intenums to ints
|
| 56 |
+
if x > int16(RequestError.internal_error):
|
| 57 |
+
return x - int32(RequestError.not_found)
|
| 58 |
+
else:
|
| 59 |
+
return x + int16(Shape.circle)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def vectorize_usecase(x):
|
| 63 |
+
if x != RequestError.not_found:
|
| 64 |
+
return RequestError['internal_error']
|
| 65 |
+
else:
|
| 66 |
+
return RequestError.dummy
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BaseEnumTest(object):
|
| 70 |
+
|
| 71 |
+
def test_compare(self):
|
| 72 |
+
pyfunc = compare_usecase
|
| 73 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 74 |
+
|
| 75 |
+
for args in self.pairs:
|
| 76 |
+
self.assertPreciseEqual(pyfunc(*args), cfunc(*args))
|
| 77 |
+
|
| 78 |
+
def test_return(self):
|
| 79 |
+
"""
|
| 80 |
+
Passing and returning enum members.
|
| 81 |
+
"""
|
| 82 |
+
pyfunc = return_usecase
|
| 83 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 84 |
+
|
| 85 |
+
for pair in self.pairs:
|
| 86 |
+
for pred in (True, False):
|
| 87 |
+
args = pair + (pred,)
|
| 88 |
+
self.assertIs(pyfunc(*args), cfunc(*args))
|
| 89 |
+
|
| 90 |
+
def check_constant_usecase(self, pyfunc):
|
| 91 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 92 |
+
|
| 93 |
+
for arg in self.values:
|
| 94 |
+
self.assertPreciseEqual(pyfunc(arg), cfunc(arg))
|
| 95 |
+
|
| 96 |
+
def test_constant(self):
|
| 97 |
+
self.check_constant_usecase(getattr_usecase)
|
| 98 |
+
self.check_constant_usecase(getitem_usecase)
|
| 99 |
+
self.check_constant_usecase(make_constant_usecase(self.values[0]))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TestEnum(BaseEnumTest, TestCase):
|
| 103 |
+
"""
|
| 104 |
+
Tests for Enum classes and members.
|
| 105 |
+
"""
|
| 106 |
+
values = [Color.red, Color.green]
|
| 107 |
+
|
| 108 |
+
pairs = [
|
| 109 |
+
(Color.red, Color.red),
|
| 110 |
+
(Color.red, Color.green),
|
| 111 |
+
(Shake.mint, Shake.vanilla),
|
| 112 |
+
(Planet.VENUS, Planet.MARS),
|
| 113 |
+
(Planet.EARTH, Planet.EARTH),
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
def test_identity(self):
|
| 117 |
+
"""
|
| 118 |
+
Enum with equal values should not compare identical
|
| 119 |
+
"""
|
| 120 |
+
pyfunc = identity_usecase
|
| 121 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 122 |
+
args = (Color.blue, Color.green, Shape.square)
|
| 123 |
+
self.assertPreciseEqual(pyfunc(*args), cfunc(*args))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class TestIntEnum(BaseEnumTest, TestCase):
|
| 127 |
+
"""
|
| 128 |
+
Tests for IntEnum classes and members.
|
| 129 |
+
"""
|
| 130 |
+
values = [Shape.circle, Shape.square]
|
| 131 |
+
|
| 132 |
+
pairs = [
|
| 133 |
+
(Shape.circle, Shape.circle),
|
| 134 |
+
(Shape.circle, Shape.square),
|
| 135 |
+
(RequestError.not_found, RequestError.not_found),
|
| 136 |
+
(RequestError.internal_error, RequestError.not_found),
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
def test_int_coerce(self):
|
| 140 |
+
pyfunc = int_coerce_usecase
|
| 141 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 142 |
+
|
| 143 |
+
for arg in [300, 450, 550]:
|
| 144 |
+
self.assertPreciseEqual(pyfunc(arg), cfunc(arg))
|
| 145 |
+
|
| 146 |
+
def test_int_cast(self):
|
| 147 |
+
pyfunc = int_cast_usecase
|
| 148 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 149 |
+
|
| 150 |
+
for arg in [300, 450, 550]:
|
| 151 |
+
self.assertPreciseEqual(pyfunc(arg), cfunc(arg))
|
| 152 |
+
|
| 153 |
+
def test_vectorize(self):
|
| 154 |
+
cfunc = vectorize(nopython=True)(vectorize_usecase)
|
| 155 |
+
arg = np.array([2, 404, 500, 404])
|
| 156 |
+
sol = np.array([vectorize_usecase(i) for i in arg], dtype=arg.dtype)
|
| 157 |
+
self.assertPreciseEqual(sol, cfunc(arg))
|
| 158 |
+
|
| 159 |
+
def test_hash(self):
|
| 160 |
+
def pyfun(x):
|
| 161 |
+
return hash(x)
|
| 162 |
+
cfunc = jit(nopython=True)(pyfun)
|
| 163 |
+
for member in IntEnumWithNegatives:
|
| 164 |
+
self.assertPreciseEqual(pyfun(member), cfunc(member))
|
| 165 |
+
|
| 166 |
+
def test_int_shape_cast(self):
|
| 167 |
+
def pyfun_empty(x):
|
| 168 |
+
return np.empty((x, x), dtype='int64').fill(-1)
|
| 169 |
+
def pyfun_zeros(x):
|
| 170 |
+
return np.zeros((x, x), dtype='int64')
|
| 171 |
+
def pyfun_ones(x):
|
| 172 |
+
return np.ones((x, x), dtype='int64')
|
| 173 |
+
for pyfun in [pyfun_empty, pyfun_zeros, pyfun_ones]:
|
| 174 |
+
cfunc = jit(nopython=True)(pyfun)
|
| 175 |
+
for member in IntEnumWithNegatives:
|
| 176 |
+
if member >= 0:
|
| 177 |
+
self.assertPreciseEqual(pyfun(member), cfunc(member))
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == '__main__':
|
| 181 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_errorhandling.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unspecified error handling tests
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
from numba import jit, njit, types
|
| 10 |
+
from numba.core import errors
|
| 11 |
+
from numba.experimental import structref
|
| 12 |
+
from numba.extending import (overload, intrinsic, overload_method,
|
| 13 |
+
overload_attribute)
|
| 14 |
+
from numba.core.compiler import CompilerBase
|
| 15 |
+
from numba.core.untyped_passes import (TranslateByteCode, FixupArgs,
|
| 16 |
+
IRProcessing,)
|
| 17 |
+
from numba.core.typed_passes import (NopythonTypeInference, DeadCodeElimination,
|
| 18 |
+
NoPythonBackend, NativeLowering)
|
| 19 |
+
from numba.core.compiler_machinery import PassManager
|
| 20 |
+
from numba.core.types.functions import _err_reasons as error_reasons
|
| 21 |
+
|
| 22 |
+
from numba.tests.support import (skip_parfors_unsupported, override_config,
|
| 23 |
+
SerialMixin, skip_unless_cffi,
|
| 24 |
+
skip_unless_scipy, TestCase)
|
| 25 |
+
import unittest
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestErrorHandlingBeforeLowering(unittest.TestCase):
|
| 29 |
+
|
| 30 |
+
def test_unsupported_make_function_return_inner_func(self):
|
| 31 |
+
def func(x):
|
| 32 |
+
""" return the closure """
|
| 33 |
+
z = x + 1
|
| 34 |
+
|
| 35 |
+
def inner(x):
|
| 36 |
+
return x + z
|
| 37 |
+
return inner
|
| 38 |
+
|
| 39 |
+
for pipeline in jit, njit:
|
| 40 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 41 |
+
pipeline(func)(1)
|
| 42 |
+
|
| 43 |
+
expected = "Cannot capture the non-constant value"
|
| 44 |
+
self.assertIn(expected, str(raises.exception))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class TestUnsupportedReporting(unittest.TestCase):
|
| 48 |
+
|
| 49 |
+
def test_unsupported_numpy_function(self):
|
| 50 |
+
# np.asanyarray(list) currently unsupported
|
| 51 |
+
@njit
|
| 52 |
+
def func():
|
| 53 |
+
np.asanyarray([1,2,3])
|
| 54 |
+
|
| 55 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 56 |
+
func()
|
| 57 |
+
|
| 58 |
+
expected = "Use of unsupported NumPy function 'numpy.asanyarray'"
|
| 59 |
+
self.assertIn(expected, str(raises.exception))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class TestMiscErrorHandling(unittest.TestCase):
|
| 63 |
+
|
| 64 |
+
def test_use_of_exception_for_flow_control(self):
|
| 65 |
+
# constant inference uses exceptions with no Loc specified to determine
|
| 66 |
+
# flow control, this asserts that the construction of the lowering
|
| 67 |
+
# error context handler works in the case of an exception with no Loc
|
| 68 |
+
# specified. See issue #3135.
|
| 69 |
+
@njit
|
| 70 |
+
def fn(x):
|
| 71 |
+
return 10**x
|
| 72 |
+
|
| 73 |
+
a = np.array([1.0],dtype=np.float64)
|
| 74 |
+
fn(a) # should not raise
|
| 75 |
+
|
| 76 |
+
def test_commented_func_definition_is_not_a_definition(self):
|
| 77 |
+
# See issue #4056, the commented def should not be found as the
|
| 78 |
+
# definition for reporting purposes when creating the synthetic
|
| 79 |
+
# traceback because it is commented! Use of def in docstring would also
|
| 80 |
+
# cause this issue hence is tested.
|
| 81 |
+
|
| 82 |
+
def foo_commented():
|
| 83 |
+
#def commented_definition()
|
| 84 |
+
raise Exception('test_string')
|
| 85 |
+
|
| 86 |
+
def foo_docstring():
|
| 87 |
+
""" def docstring containing def might match function definition!"""
|
| 88 |
+
raise Exception('test_string')
|
| 89 |
+
|
| 90 |
+
for func in (foo_commented, foo_docstring):
|
| 91 |
+
with self.assertRaises(Exception) as raises:
|
| 92 |
+
func()
|
| 93 |
+
|
| 94 |
+
self.assertIn("test_string", str(raises.exception))
|
| 95 |
+
|
| 96 |
+
def test_use_of_ir_unknown_loc(self):
|
| 97 |
+
# for context see # 3390
|
| 98 |
+
class TestPipeline(CompilerBase):
|
| 99 |
+
def define_pipelines(self):
|
| 100 |
+
name = 'bad_DCE_pipeline'
|
| 101 |
+
pm = PassManager(name)
|
| 102 |
+
pm.add_pass(TranslateByteCode, "analyzing bytecode")
|
| 103 |
+
pm.add_pass(FixupArgs, "fix up args")
|
| 104 |
+
pm.add_pass(IRProcessing, "processing IR")
|
| 105 |
+
# remove dead before type inference so that the Arg node is
|
| 106 |
+
# removed and the location of the arg cannot be found
|
| 107 |
+
pm.add_pass(DeadCodeElimination, "DCE")
|
| 108 |
+
# typing
|
| 109 |
+
pm.add_pass(NopythonTypeInference, "nopython frontend")
|
| 110 |
+
pm.add_pass(NativeLowering, "native lowering")
|
| 111 |
+
pm.add_pass(NoPythonBackend, "nopython mode backend")
|
| 112 |
+
pm.finalize()
|
| 113 |
+
return [pm]
|
| 114 |
+
|
| 115 |
+
@njit(pipeline_class=TestPipeline)
|
| 116 |
+
def f(a):
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 120 |
+
f(iter([1,2])) # use a type that Numba doesn't recognize
|
| 121 |
+
|
| 122 |
+
expected = 'File "unknown location", line 0:'
|
| 123 |
+
self.assertIn(expected, str(raises.exception))
|
| 124 |
+
|
| 125 |
+
def check_write_to_globals(self, func):
|
| 126 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 127 |
+
func()
|
| 128 |
+
|
| 129 |
+
expected = ["The use of a", "in globals, is not supported as globals"]
|
| 130 |
+
for ex in expected:
|
| 131 |
+
self.assertIn(ex, str(raises.exception))
|
| 132 |
+
|
| 133 |
+
def test_handling_of_write_to_reflected_global(self):
|
| 134 |
+
from numba.tests.errorhandling_usecases import global_reflected_write
|
| 135 |
+
self.check_write_to_globals(njit(global_reflected_write))
|
| 136 |
+
|
| 137 |
+
def test_handling_of_write_to_typed_dict_global(self):
|
| 138 |
+
from numba.tests.errorhandling_usecases import global_dict_write
|
| 139 |
+
self.check_write_to_globals(njit(global_dict_write))
|
| 140 |
+
|
| 141 |
+
@skip_parfors_unsupported
|
| 142 |
+
def test_handling_forgotten_numba_internal_import(self):
|
| 143 |
+
@njit(parallel=True)
|
| 144 |
+
def foo():
|
| 145 |
+
for i in prange(10): # noqa: F821 prange is not imported
|
| 146 |
+
pass
|
| 147 |
+
|
| 148 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 149 |
+
foo()
|
| 150 |
+
|
| 151 |
+
expected = ("'prange' looks like a Numba internal function, "
|
| 152 |
+
"has it been imported")
|
| 153 |
+
self.assertIn(expected, str(raises.exception))
|
| 154 |
+
|
| 155 |
+
def test_handling_unsupported_generator_expression(self):
|
| 156 |
+
def foo():
|
| 157 |
+
(x for x in range(10))
|
| 158 |
+
|
| 159 |
+
expected = "The use of yield in a closure is unsupported."
|
| 160 |
+
|
| 161 |
+
for dec in jit(forceobj=True), njit:
|
| 162 |
+
with self.assertRaises(errors.UnsupportedError) as raises:
|
| 163 |
+
dec(foo)()
|
| 164 |
+
self.assertIn(expected, str(raises.exception))
|
| 165 |
+
|
| 166 |
+
def test_handling_undefined_variable(self):
|
| 167 |
+
@njit
|
| 168 |
+
def foo():
|
| 169 |
+
return a # noqa: F821
|
| 170 |
+
|
| 171 |
+
expected = "NameError: name 'a' is not defined"
|
| 172 |
+
|
| 173 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 174 |
+
foo()
|
| 175 |
+
self.assertIn(expected, str(raises.exception))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TestErrorMessages(unittest.TestCase):
|
| 179 |
+
|
| 180 |
+
def test_specific_error(self):
|
| 181 |
+
|
| 182 |
+
given_reason = "specific_reason"
|
| 183 |
+
|
| 184 |
+
def foo():
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
@overload(foo)
|
| 188 |
+
def ol_foo():
|
| 189 |
+
raise errors.NumbaValueError(given_reason)
|
| 190 |
+
|
| 191 |
+
@njit
|
| 192 |
+
def call_foo():
|
| 193 |
+
foo()
|
| 194 |
+
|
| 195 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 196 |
+
call_foo()
|
| 197 |
+
|
| 198 |
+
excstr = str(raises.exception)
|
| 199 |
+
self.assertIn(error_reasons['specific_error'].splitlines()[0], excstr)
|
| 200 |
+
self.assertIn(given_reason, excstr)
|
| 201 |
+
|
| 202 |
+
def test_no_match_error(self):
|
| 203 |
+
|
| 204 |
+
def foo():
|
| 205 |
+
pass
|
| 206 |
+
|
| 207 |
+
@overload(foo)
|
| 208 |
+
def ol_foo():
|
| 209 |
+
return None # emulate no impl available for type
|
| 210 |
+
|
| 211 |
+
@njit
|
| 212 |
+
def call_foo():
|
| 213 |
+
foo()
|
| 214 |
+
|
| 215 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 216 |
+
call_foo()
|
| 217 |
+
|
| 218 |
+
excstr = str(raises.exception)
|
| 219 |
+
self.assertIn("No match", excstr)
|
| 220 |
+
|
| 221 |
+
@skip_unless_scipy
|
| 222 |
+
def test_error_function_source_is_correct(self):
|
| 223 |
+
""" Checks that the reported source location for an overload is the
|
| 224 |
+
overload implementation source, not the actual function source from the
|
| 225 |
+
target library."""
|
| 226 |
+
|
| 227 |
+
@njit
|
| 228 |
+
def foo():
|
| 229 |
+
np.linalg.svd("chars")
|
| 230 |
+
|
| 231 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 232 |
+
foo()
|
| 233 |
+
|
| 234 |
+
excstr = str(raises.exception)
|
| 235 |
+
self.assertIn(error_reasons['specific_error'].splitlines()[0], excstr)
|
| 236 |
+
expected_file = os.path.join("numba", "np", "linalg.py")
|
| 237 |
+
expected = f"Overload in function 'svd_impl': File: {expected_file}:"
|
| 238 |
+
self.assertIn(expected.format(expected_file), excstr)
|
| 239 |
+
|
| 240 |
+
def test_concrete_template_source(self):
|
| 241 |
+
# hits ConcreteTemplate
|
| 242 |
+
@njit
|
| 243 |
+
def foo():
|
| 244 |
+
return 'a' + 1
|
| 245 |
+
|
| 246 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 247 |
+
foo()
|
| 248 |
+
|
| 249 |
+
excstr = str(raises.exception)
|
| 250 |
+
|
| 251 |
+
self.assertIn("Overload of function 'add'", excstr)
|
| 252 |
+
# there'll be numerous matched templates that don't work but as they
|
| 253 |
+
# are mostly "overload"s they'll just appear as "No match".
|
| 254 |
+
self.assertIn("No match.", excstr)
|
| 255 |
+
|
| 256 |
+
def test_abstract_template_source(self):
|
| 257 |
+
# hits AbstractTemplate
|
| 258 |
+
@njit
|
| 259 |
+
def foo():
|
| 260 |
+
return len(1)
|
| 261 |
+
|
| 262 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 263 |
+
foo()
|
| 264 |
+
|
| 265 |
+
excstr = str(raises.exception)
|
| 266 |
+
self.assertIn("Overload of function 'len'", excstr)
|
| 267 |
+
|
| 268 |
+
def test_callable_template_source(self):
|
| 269 |
+
# hits CallableTemplate
|
| 270 |
+
@njit
|
| 271 |
+
def foo():
|
| 272 |
+
return np.angle(None)
|
| 273 |
+
|
| 274 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 275 |
+
foo()
|
| 276 |
+
|
| 277 |
+
excstr = str(raises.exception)
|
| 278 |
+
self.assertIn("No implementation of function Function(<function angle",
|
| 279 |
+
excstr)
|
| 280 |
+
|
| 281 |
+
def test_overloadfunction_template_source(self):
|
| 282 |
+
# hits _OverloadFunctionTemplate
|
| 283 |
+
def bar(x):
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
@overload(bar)
|
| 287 |
+
def ol_bar(x):
|
| 288 |
+
pass
|
| 289 |
+
|
| 290 |
+
@njit
|
| 291 |
+
def foo():
|
| 292 |
+
return bar(1)
|
| 293 |
+
|
| 294 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 295 |
+
foo()
|
| 296 |
+
|
| 297 |
+
excstr = str(raises.exception)
|
| 298 |
+
# there will not be "numerous" matched templates, there's just one,
|
| 299 |
+
# the one above, so assert it is reported
|
| 300 |
+
self.assertNotIn("<numerous>", excstr)
|
| 301 |
+
expected_file = os.path.join("numba", "tests",
|
| 302 |
+
"test_errorhandling.py")
|
| 303 |
+
expected_ol = f"Overload of function 'bar': File: {expected_file}:"
|
| 304 |
+
self.assertIn(expected_ol.format(expected_file), excstr)
|
| 305 |
+
self.assertIn("No match.", excstr)
|
| 306 |
+
|
| 307 |
+
def test_intrinsic_template_source(self):
|
| 308 |
+
# hits _IntrinsicTemplate
|
| 309 |
+
given_reason1 = "x must be literal"
|
| 310 |
+
given_reason2 = "array.ndim must be 1"
|
| 311 |
+
|
| 312 |
+
@intrinsic
|
| 313 |
+
def myintrin(typingctx, x, arr):
|
| 314 |
+
if not isinstance(x, types.IntegerLiteral):
|
| 315 |
+
raise errors.RequireLiteralValue(given_reason1)
|
| 316 |
+
|
| 317 |
+
if arr.ndim != 1:
|
| 318 |
+
raise errors.NumbaValueError(given_reason2)
|
| 319 |
+
|
| 320 |
+
sig = types.intp(x, arr)
|
| 321 |
+
|
| 322 |
+
def codegen(context, builder, signature, args):
|
| 323 |
+
pass
|
| 324 |
+
return sig, codegen
|
| 325 |
+
|
| 326 |
+
@njit
|
| 327 |
+
def call_intrin():
|
| 328 |
+
arr = np.zeros((2, 2))
|
| 329 |
+
myintrin(1, arr)
|
| 330 |
+
|
| 331 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 332 |
+
call_intrin()
|
| 333 |
+
|
| 334 |
+
excstr = str(raises.exception)
|
| 335 |
+
self.assertIn(error_reasons['specific_error'].splitlines()[0], excstr)
|
| 336 |
+
self.assertIn(given_reason1, excstr)
|
| 337 |
+
self.assertIn(given_reason2, excstr)
|
| 338 |
+
self.assertIn("Intrinsic in function", excstr)
|
| 339 |
+
|
| 340 |
+
def test_overloadmethod_template_source(self):
|
| 341 |
+
# doesn't hit _OverloadMethodTemplate for source as it's a nested
|
| 342 |
+
# exception
|
| 343 |
+
@overload_method(types.UnicodeType, 'isnonsense')
|
| 344 |
+
def ol_unicode_isnonsense(self):
|
| 345 |
+
pass
|
| 346 |
+
|
| 347 |
+
@njit
|
| 348 |
+
def foo():
|
| 349 |
+
"abc".isnonsense()
|
| 350 |
+
|
| 351 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 352 |
+
foo()
|
| 353 |
+
|
| 354 |
+
excstr = str(raises.exception)
|
| 355 |
+
self.assertIn("Overload of function 'ol_unicode_isnonsense'", excstr)
|
| 356 |
+
|
| 357 |
+
def test_overloadattribute_template_source(self):
|
| 358 |
+
# doesn't hit _OverloadMethodTemplate for source as it's a nested
|
| 359 |
+
# exception
|
| 360 |
+
@overload_attribute(types.UnicodeType, 'isnonsense')
|
| 361 |
+
def ol_unicode_isnonsense(self):
|
| 362 |
+
pass
|
| 363 |
+
|
| 364 |
+
@njit
|
| 365 |
+
def foo():
|
| 366 |
+
"abc".isnonsense
|
| 367 |
+
|
| 368 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 369 |
+
foo()
|
| 370 |
+
|
| 371 |
+
excstr = str(raises.exception)
|
| 372 |
+
self.assertIn("Overload of function 'ol_unicode_isnonsense'", excstr)
|
| 373 |
+
|
| 374 |
+
def test_external_function_pointer_template_source(self):
|
| 375 |
+
from numba.tests.ctypes_usecases import c_cos
|
| 376 |
+
|
| 377 |
+
@njit
|
| 378 |
+
def foo():
|
| 379 |
+
c_cos('a')
|
| 380 |
+
|
| 381 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 382 |
+
foo()
|
| 383 |
+
|
| 384 |
+
excstr = str(raises.exception)
|
| 385 |
+
self.assertIn("Type Restricted Function in function 'unknown'", excstr)
|
| 386 |
+
|
| 387 |
+
@skip_unless_cffi
|
| 388 |
+
def test_cffi_function_pointer_template_source(self):
|
| 389 |
+
from numba.tests import cffi_usecases as mod
|
| 390 |
+
mod.init()
|
| 391 |
+
func = mod.cffi_cos
|
| 392 |
+
|
| 393 |
+
@njit
|
| 394 |
+
def foo():
|
| 395 |
+
func('a')
|
| 396 |
+
|
| 397 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 398 |
+
foo()
|
| 399 |
+
|
| 400 |
+
excstr = str(raises.exception)
|
| 401 |
+
self.assertIn("Type Restricted Function in function 'unknown'", excstr)
|
| 402 |
+
|
| 403 |
+
def test_missing_source(self):
|
| 404 |
+
|
| 405 |
+
@structref.register
|
| 406 |
+
class ParticleType(types.StructRef):
|
| 407 |
+
pass
|
| 408 |
+
|
| 409 |
+
class Particle(structref.StructRefProxy):
|
| 410 |
+
def __new__(cls, pos, mass):
|
| 411 |
+
return structref.StructRefProxy.__new__(cls, pos)
|
| 412 |
+
# didn't provide the required mass argument ----^
|
| 413 |
+
|
| 414 |
+
structref.define_proxy(Particle, ParticleType, ["pos", "mass"])
|
| 415 |
+
|
| 416 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 417 |
+
Particle(pos=1, mass=2)
|
| 418 |
+
|
| 419 |
+
excstr = str(raises.exception)
|
| 420 |
+
self.assertIn("missing a required argument: 'mass'", excstr)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
class TestDeveloperSpecificErrorMessages(SerialMixin, unittest.TestCase):
|
| 424 |
+
|
| 425 |
+
def test_bound_function_error_string(self):
|
| 426 |
+
# See PR #5952
|
| 427 |
+
def foo(x):
|
| 428 |
+
x.max(-1)
|
| 429 |
+
|
| 430 |
+
with override_config('DEVELOPER_MODE', 1):
|
| 431 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 432 |
+
njit("void(int64[:,:])")(foo)
|
| 433 |
+
|
| 434 |
+
excstr = str(raises.exception)
|
| 435 |
+
self.assertIn("too many positional arguments", excstr)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
class TestCapturedErrorHandling(SerialMixin, TestCase):
|
| 439 |
+
"""Checks that the way errors are captured.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
def test_error_in_overload(self):
|
| 443 |
+
|
| 444 |
+
def bar(x):
|
| 445 |
+
pass
|
| 446 |
+
|
| 447 |
+
@overload(bar)
|
| 448 |
+
def ol_bar(x):
|
| 449 |
+
x.some_invalid_attr # doesn't exist!
|
| 450 |
+
|
| 451 |
+
def impl(x):
|
| 452 |
+
pass
|
| 453 |
+
return impl
|
| 454 |
+
|
| 455 |
+
with warnings.catch_warnings():
|
| 456 |
+
# Suppress error going into stdout
|
| 457 |
+
warnings.simplefilter("ignore",
|
| 458 |
+
errors.NumbaPendingDeprecationWarning)
|
| 459 |
+
|
| 460 |
+
with self.assertRaises(AttributeError) as raises:
|
| 461 |
+
@njit('void(int64)')
|
| 462 |
+
def foo(x):
|
| 463 |
+
bar(x)
|
| 464 |
+
expected = "object has no attribute 'some_invalid_attr'"
|
| 465 |
+
self.assertIn(expected, str(raises.exception))
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
if __name__ == '__main__':
|
| 469 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_errormodels.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test setting/overriding error models
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from numba import jit
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestErrorModel(unittest.TestCase):
|
| 10 |
+
|
| 11 |
+
def test_div_by_zero_python(self):
|
| 12 |
+
@jit # python model is the default
|
| 13 |
+
def model_python(val):
|
| 14 |
+
return 1 / val
|
| 15 |
+
|
| 16 |
+
with self.assertRaises(ZeroDivisionError):
|
| 17 |
+
model_python(0)
|
| 18 |
+
|
| 19 |
+
def test_div_by_zero_numpy(self):
|
| 20 |
+
@jit(error_model='numpy')
|
| 21 |
+
def model_numpy(val):
|
| 22 |
+
return 1 / val
|
| 23 |
+
|
| 24 |
+
self.assertEqual(model_numpy(0), float('inf'))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if __name__ == '__main__':
|
| 28 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_extending.py
ADDED
|
@@ -0,0 +1,2248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import math
|
| 3 |
+
import operator
|
| 4 |
+
import sys
|
| 5 |
+
import pickle
|
| 6 |
+
import multiprocessing
|
| 7 |
+
import ctypes
|
| 8 |
+
import warnings
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from llvmlite import ir
|
| 13 |
+
|
| 14 |
+
import numba
|
| 15 |
+
from numba import njit, jit, vectorize, guvectorize, objmode
|
| 16 |
+
from numba.core import types, errors, typing, compiler, cgutils
|
| 17 |
+
from numba.core.typed_passes import type_inference_stage
|
| 18 |
+
from numba.core.registry import cpu_target
|
| 19 |
+
from numba.core.imputils import lower_constant
|
| 20 |
+
from numba.tests.support import (
|
| 21 |
+
TestCase,
|
| 22 |
+
captured_stdout,
|
| 23 |
+
temp_directory,
|
| 24 |
+
override_config,
|
| 25 |
+
run_in_new_process_in_cache_dir,
|
| 26 |
+
skip_if_typeguard,
|
| 27 |
+
)
|
| 28 |
+
from numba.core.errors import LoweringError
|
| 29 |
+
import unittest
|
| 30 |
+
|
| 31 |
+
from numba.extending import (
|
| 32 |
+
typeof_impl,
|
| 33 |
+
type_callable,
|
| 34 |
+
lower_builtin,
|
| 35 |
+
lower_cast,
|
| 36 |
+
overload,
|
| 37 |
+
overload_attribute,
|
| 38 |
+
overload_method,
|
| 39 |
+
models,
|
| 40 |
+
register_model,
|
| 41 |
+
box,
|
| 42 |
+
unbox,
|
| 43 |
+
NativeValue,
|
| 44 |
+
intrinsic,
|
| 45 |
+
_Intrinsic,
|
| 46 |
+
register_jitable,
|
| 47 |
+
get_cython_function_address,
|
| 48 |
+
is_jitted,
|
| 49 |
+
overload_classmethod,
|
| 50 |
+
)
|
| 51 |
+
from numba.core.typing.templates import (
|
| 52 |
+
ConcreteTemplate,
|
| 53 |
+
signature,
|
| 54 |
+
infer,
|
| 55 |
+
infer_global,
|
| 56 |
+
AbstractTemplate,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Pandas-like API implementation
|
| 61 |
+
from .pdlike_usecase import Index, Series
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
import scipy.special.cython_special as sc
|
| 66 |
+
except ImportError:
|
| 67 |
+
sc = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# -----------------------------------------------------------------------
|
| 71 |
+
# Define a custom type and an implicit cast on it
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class MyDummy(object):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class MyDummyType(types.Opaque):
|
| 79 |
+
def can_convert_to(self, context, toty):
|
| 80 |
+
if isinstance(toty, types.Number):
|
| 81 |
+
from numba.core.typeconv import Conversion
|
| 82 |
+
|
| 83 |
+
return Conversion.safe
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
mydummy_type = MyDummyType("mydummy")
|
| 87 |
+
mydummy = MyDummy()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@typeof_impl.register(MyDummy)
|
| 91 |
+
def typeof_mydummy(val, c):
|
| 92 |
+
return mydummy_type
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@lower_cast(MyDummyType, types.Number)
|
| 96 |
+
def mydummy_to_number(context, builder, fromty, toty, val):
|
| 97 |
+
"""
|
| 98 |
+
Implicit conversion from MyDummy to int.
|
| 99 |
+
"""
|
| 100 |
+
return context.get_constant(toty, 42)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_dummy():
|
| 104 |
+
return mydummy
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
register_model(MyDummyType)(models.OpaqueModel)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@unbox(MyDummyType)
|
| 111 |
+
def unbox_index(typ, obj, c):
|
| 112 |
+
return NativeValue(c.context.get_dummy_value())
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# -----------------------------------------------------------------------
|
| 116 |
+
# Define a second custom type but w/o implicit cast to Number
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def base_dummy_type_factory(name):
|
| 120 |
+
class DynType(object):
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
class DynTypeType(types.Opaque):
|
| 124 |
+
pass
|
| 125 |
+
|
| 126 |
+
dyn_type_type = DynTypeType(name)
|
| 127 |
+
|
| 128 |
+
@typeof_impl.register(DynType)
|
| 129 |
+
def typeof_mydummy(val, c):
|
| 130 |
+
return dyn_type_type
|
| 131 |
+
|
| 132 |
+
register_model(DynTypeType)(models.OpaqueModel)
|
| 133 |
+
return DynTypeType, DynType, dyn_type_type
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
MyDummyType2, MyDummy2, mydummy_type_2 = base_dummy_type_factory("mydummy2")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@unbox(MyDummyType2)
|
| 140 |
+
def unbox_index2(typ, obj, c):
|
| 141 |
+
return NativeValue(c.context.get_dummy_value())
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# -----------------------------------------------------------------------
|
| 145 |
+
# Define a function's typing and implementation using the classical
|
| 146 |
+
# two-step API
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def func1(x=None):
|
| 150 |
+
raise NotImplementedError
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def type_func1_(context):
|
| 154 |
+
def typer(x=None):
|
| 155 |
+
if x in (None, types.none):
|
| 156 |
+
# 0-arg or 1-arg with None
|
| 157 |
+
return types.int32
|
| 158 |
+
elif isinstance(x, types.Float):
|
| 159 |
+
# 1-arg with float
|
| 160 |
+
return x
|
| 161 |
+
|
| 162 |
+
return typer
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
type_func1 = type_callable(func1)(type_func1_)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@lower_builtin(func1)
|
| 169 |
+
@lower_builtin(func1, types.none)
|
| 170 |
+
def func1_nullary(context, builder, sig, args):
|
| 171 |
+
return context.get_constant(sig.return_type, 42)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@lower_builtin(func1, types.Float)
|
| 175 |
+
def func1_unary(context, builder, sig, args):
|
| 176 |
+
def func1_impl(x):
|
| 177 |
+
return math.sqrt(2 * x)
|
| 178 |
+
|
| 179 |
+
return context.compile_internal(builder, func1_impl, sig, args)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# We can do the same for a known internal operation, here "print_item"
|
| 183 |
+
# which we extend to support MyDummyType.
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@infer
|
| 187 |
+
class PrintDummy(ConcreteTemplate):
|
| 188 |
+
key = "print_item"
|
| 189 |
+
cases = [signature(types.none, mydummy_type)]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@lower_builtin("print_item", MyDummyType)
|
| 193 |
+
def print_dummy(context, builder, sig, args):
|
| 194 |
+
[x] = args
|
| 195 |
+
pyapi = context.get_python_api(builder)
|
| 196 |
+
strobj = pyapi.unserialize(pyapi.serialize_object("hello!"))
|
| 197 |
+
pyapi.print_object(strobj)
|
| 198 |
+
pyapi.decref(strobj)
|
| 199 |
+
return context.get_dummy_value()
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# -----------------------------------------------------------------------
|
| 203 |
+
# Define an overloaded function (combined API)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def where(cond, x, y):
|
| 207 |
+
raise NotImplementedError
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def np_where(cond, x, y):
|
| 211 |
+
"""
|
| 212 |
+
Wrap np.where() to allow for keyword arguments
|
| 213 |
+
"""
|
| 214 |
+
return np.where(cond, x, y)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def call_where(cond, x, y):
|
| 218 |
+
return where(cond, y=y, x=x)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@overload(where)
|
| 222 |
+
def overload_where_arrays(cond, x, y):
|
| 223 |
+
"""
|
| 224 |
+
Implement where() for arrays.
|
| 225 |
+
"""
|
| 226 |
+
# Choose implementation based on argument types.
|
| 227 |
+
if isinstance(cond, types.Array):
|
| 228 |
+
if x.dtype != y.dtype:
|
| 229 |
+
raise errors.TypingError("x and y should have the same dtype")
|
| 230 |
+
|
| 231 |
+
# Array where() => return an array of the same shape
|
| 232 |
+
if all(ty.layout == "C" for ty in (cond, x, y)):
|
| 233 |
+
|
| 234 |
+
def where_impl(cond, x, y):
|
| 235 |
+
"""
|
| 236 |
+
Fast implementation for C-contiguous arrays
|
| 237 |
+
"""
|
| 238 |
+
shape = cond.shape
|
| 239 |
+
if x.shape != shape or y.shape != shape:
|
| 240 |
+
raise ValueError("all inputs should have the same shape")
|
| 241 |
+
res = np.empty_like(x)
|
| 242 |
+
cf = cond.flat
|
| 243 |
+
xf = x.flat
|
| 244 |
+
yf = y.flat
|
| 245 |
+
rf = res.flat
|
| 246 |
+
for i in range(cond.size):
|
| 247 |
+
rf[i] = xf[i] if cf[i] else yf[i]
|
| 248 |
+
return res
|
| 249 |
+
|
| 250 |
+
else:
|
| 251 |
+
|
| 252 |
+
def where_impl(cond, x, y):
|
| 253 |
+
"""
|
| 254 |
+
Generic implementation for other arrays
|
| 255 |
+
"""
|
| 256 |
+
shape = cond.shape
|
| 257 |
+
if x.shape != shape or y.shape != shape:
|
| 258 |
+
raise ValueError("all inputs should have the same shape")
|
| 259 |
+
res = np.empty_like(x)
|
| 260 |
+
for idx, c in np.ndenumerate(cond):
|
| 261 |
+
res[idx] = x[idx] if c else y[idx]
|
| 262 |
+
return res
|
| 263 |
+
|
| 264 |
+
return where_impl
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# We can define another overload function for the same function, they
|
| 268 |
+
# will be tried in turn until one succeeds.
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@overload(where)
|
| 272 |
+
def overload_where_scalars(cond, x, y):
|
| 273 |
+
"""
|
| 274 |
+
Implement where() for scalars.
|
| 275 |
+
"""
|
| 276 |
+
if not isinstance(cond, types.Array):
|
| 277 |
+
if x != y:
|
| 278 |
+
raise errors.TypingError("x and y should have the same type")
|
| 279 |
+
|
| 280 |
+
def where_impl(cond, x, y):
|
| 281 |
+
"""
|
| 282 |
+
Scalar where() => return a 0-dim array
|
| 283 |
+
"""
|
| 284 |
+
scal = x if cond else y
|
| 285 |
+
# Can't use full_like() on Numpy < 1.8
|
| 286 |
+
arr = np.empty_like(scal)
|
| 287 |
+
arr[()] = scal
|
| 288 |
+
return arr
|
| 289 |
+
|
| 290 |
+
return where_impl
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# -----------------------------------------------------------------------
|
| 294 |
+
# Overload an already defined built-in function, extending it for new types.
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@overload(len)
|
| 298 |
+
def overload_len_dummy(arg):
|
| 299 |
+
if isinstance(arg, MyDummyType):
|
| 300 |
+
|
| 301 |
+
def len_impl(arg):
|
| 302 |
+
return 13
|
| 303 |
+
|
| 304 |
+
return len_impl
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
@overload(operator.add)
|
| 308 |
+
def overload_add_dummy(arg1, arg2):
|
| 309 |
+
if isinstance(arg1, (MyDummyType, MyDummyType2)) and isinstance(
|
| 310 |
+
arg2, (MyDummyType, MyDummyType2)
|
| 311 |
+
):
|
| 312 |
+
|
| 313 |
+
def dummy_add_impl(arg1, arg2):
|
| 314 |
+
return 42
|
| 315 |
+
|
| 316 |
+
return dummy_add_impl
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@overload(operator.delitem)
|
| 320 |
+
def overload_dummy_delitem(obj, idx):
|
| 321 |
+
if isinstance(obj, MyDummyType) and isinstance(idx, types.Integer):
|
| 322 |
+
|
| 323 |
+
def dummy_delitem_impl(obj, idx):
|
| 324 |
+
print("del", obj, idx)
|
| 325 |
+
|
| 326 |
+
return dummy_delitem_impl
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@overload(operator.getitem)
|
| 330 |
+
def overload_dummy_getitem(obj, idx):
|
| 331 |
+
if isinstance(obj, MyDummyType) and isinstance(idx, types.Integer):
|
| 332 |
+
|
| 333 |
+
def dummy_getitem_impl(obj, idx):
|
| 334 |
+
return idx + 123
|
| 335 |
+
|
| 336 |
+
return dummy_getitem_impl
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@overload(operator.setitem)
|
| 340 |
+
def overload_dummy_setitem(obj, idx, val):
|
| 341 |
+
if all(
|
| 342 |
+
[
|
| 343 |
+
isinstance(obj, MyDummyType),
|
| 344 |
+
isinstance(idx, types.Integer),
|
| 345 |
+
isinstance(val, types.Integer),
|
| 346 |
+
]
|
| 347 |
+
):
|
| 348 |
+
|
| 349 |
+
def dummy_setitem_impl(obj, idx, val):
|
| 350 |
+
print(idx, val)
|
| 351 |
+
|
| 352 |
+
return dummy_setitem_impl
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def call_add_operator(arg1, arg2):
|
| 356 |
+
return operator.add(arg1, arg2)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def call_add_binop(arg1, arg2):
|
| 360 |
+
return arg1 + arg2
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
@overload(operator.iadd)
|
| 364 |
+
def overload_iadd_dummy(arg1, arg2):
|
| 365 |
+
if isinstance(arg1, (MyDummyType, MyDummyType2)) and isinstance(
|
| 366 |
+
arg2, (MyDummyType, MyDummyType2)
|
| 367 |
+
):
|
| 368 |
+
|
| 369 |
+
def dummy_iadd_impl(arg1, arg2):
|
| 370 |
+
return 42
|
| 371 |
+
|
| 372 |
+
return dummy_iadd_impl
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def call_iadd_operator(arg1, arg2):
|
| 376 |
+
return operator.add(arg1, arg2)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def call_iadd_binop(arg1, arg2):
|
| 380 |
+
arg1 += arg2
|
| 381 |
+
|
| 382 |
+
return arg1
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def call_delitem(obj, idx):
|
| 386 |
+
del obj[idx]
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def call_getitem(obj, idx):
|
| 390 |
+
return obj[idx]
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def call_setitem(obj, idx, val):
|
| 394 |
+
obj[idx] = val
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
@overload_method(MyDummyType, "length")
|
| 398 |
+
def overload_method_length(arg):
|
| 399 |
+
def imp(arg):
|
| 400 |
+
return len(arg)
|
| 401 |
+
|
| 402 |
+
return imp
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def cache_overload_method_usecase(x):
|
| 406 |
+
return x.length()
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def call_func1_nullary():
|
| 410 |
+
return func1()
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def call_func1_unary(x):
|
| 414 |
+
return func1(x)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def len_usecase(x):
|
| 418 |
+
return len(x)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def print_usecase(x):
|
| 422 |
+
print(x)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def getitem_usecase(x, key):
|
| 426 |
+
return x[key]
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def npyufunc_usecase(x):
|
| 430 |
+
return np.cos(np.sin(x))
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def get_data_usecase(x):
|
| 434 |
+
return x._data
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def get_index_usecase(x):
|
| 438 |
+
return x._index
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def is_monotonic_usecase(x):
|
| 442 |
+
return x.is_monotonic_increasing
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def make_series_usecase(data, index):
|
| 446 |
+
return Series(data, index)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def clip_usecase(x, lo, hi):
|
| 450 |
+
return x.clip(lo, hi)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
# -----------------------------------------------------------------------
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def return_non_boxable():
|
| 457 |
+
return np
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@overload(return_non_boxable)
|
| 461 |
+
def overload_return_non_boxable():
|
| 462 |
+
def imp():
|
| 463 |
+
return np
|
| 464 |
+
|
| 465 |
+
return imp
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def non_boxable_ok_usecase(sz):
|
| 469 |
+
mod = return_non_boxable()
|
| 470 |
+
return mod.arange(sz)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def non_boxable_bad_usecase():
|
| 474 |
+
return return_non_boxable()
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def mk_func_input(f):
|
| 478 |
+
pass
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
@infer_global(mk_func_input)
|
| 482 |
+
class MkFuncTyping(AbstractTemplate):
|
| 483 |
+
def generic(self, args, kws):
|
| 484 |
+
assert isinstance(args[0], types.MakeFunctionLiteral)
|
| 485 |
+
return signature(types.none, *args)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def mk_func_test_impl():
|
| 489 |
+
mk_func_input(lambda a: a)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
# -----------------------------------------------------------------------
|
| 493 |
+
# Define a types derived from types.Callable and overloads for them
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
class MyClass(object):
|
| 497 |
+
pass
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
class CallableTypeRef(types.Callable):
|
| 501 |
+
|
| 502 |
+
def __init__(self, instance_type):
|
| 503 |
+
self.instance_type = instance_type
|
| 504 |
+
self.sig_to_impl_key = {}
|
| 505 |
+
self.compiled_templates = []
|
| 506 |
+
super(CallableTypeRef, self).__init__('callable_type_ref'
|
| 507 |
+
'[{}]'.format(self.instance_type))
|
| 508 |
+
|
| 509 |
+
def get_call_type(self, context, args, kws):
|
| 510 |
+
|
| 511 |
+
res_sig = None
|
| 512 |
+
for template in context._functions[type(self)]:
|
| 513 |
+
try:
|
| 514 |
+
res_sig = template.apply(args, kws)
|
| 515 |
+
except Exception:
|
| 516 |
+
pass # for simplicity assume args must match exactly
|
| 517 |
+
else:
|
| 518 |
+
compiled_ovlds = getattr(template, '_compiled_overloads', {})
|
| 519 |
+
if args in compiled_ovlds:
|
| 520 |
+
self.sig_to_impl_key[res_sig] = compiled_ovlds[args]
|
| 521 |
+
self.compiled_templates.append(template)
|
| 522 |
+
break
|
| 523 |
+
|
| 524 |
+
return res_sig
|
| 525 |
+
|
| 526 |
+
def get_call_signatures(self):
|
| 527 |
+
sigs = list(self.sig_to_impl_key.keys())
|
| 528 |
+
return sigs, True
|
| 529 |
+
|
| 530 |
+
def get_impl_key(self, sig):
|
| 531 |
+
return self.sig_to_impl_key[sig]
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@register_model(CallableTypeRef)
|
| 535 |
+
class CallableTypeModel(models.OpaqueModel):
|
| 536 |
+
|
| 537 |
+
def __init__(self, dmm, fe_type):
|
| 538 |
+
|
| 539 |
+
models.OpaqueModel.__init__(self, dmm, fe_type)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
infer_global(MyClass, CallableTypeRef(MyClass))
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
@lower_constant(CallableTypeRef)
|
| 546 |
+
def constant_callable_typeref(context, builder, ty, pyval):
|
| 547 |
+
return context.get_dummy_value()
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
# -----------------------------------------------------------------------
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
@overload(np.exp)
|
| 554 |
+
def overload_np_exp(obj):
|
| 555 |
+
if isinstance(obj, MyDummyType):
|
| 556 |
+
|
| 557 |
+
def imp(obj):
|
| 558 |
+
# Returns a constant if a MyDummyType is seen
|
| 559 |
+
return 0xDEADBEEF
|
| 560 |
+
|
| 561 |
+
return imp
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class TestLowLevelExtending(TestCase):
|
| 565 |
+
"""
|
| 566 |
+
Test the low-level two-tier extension API.
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
# Check with `@jit` from within the test process and also in a new test
|
| 570 |
+
# process so as to check the registration mechanism.
|
| 571 |
+
|
| 572 |
+
def test_func1(self):
|
| 573 |
+
pyfunc = call_func1_nullary
|
| 574 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 575 |
+
self.assertPreciseEqual(cfunc(), 42)
|
| 576 |
+
pyfunc = call_func1_unary
|
| 577 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 578 |
+
self.assertPreciseEqual(cfunc(None), 42)
|
| 579 |
+
self.assertPreciseEqual(cfunc(18.0), 6.0)
|
| 580 |
+
|
| 581 |
+
@TestCase.run_test_in_subprocess
|
| 582 |
+
def test_func1_isolated(self):
|
| 583 |
+
self.test_func1()
|
| 584 |
+
|
| 585 |
+
def test_type_callable_keeps_function(self):
|
| 586 |
+
self.assertIs(type_func1, type_func1_)
|
| 587 |
+
self.assertIsNotNone(type_func1)
|
| 588 |
+
|
| 589 |
+
@TestCase.run_test_in_subprocess
|
| 590 |
+
def test_cast_mydummy(self):
|
| 591 |
+
pyfunc = get_dummy
|
| 592 |
+
cfunc = njit(types.float64(),)(pyfunc)
|
| 593 |
+
self.assertPreciseEqual(cfunc(), 42.0)
|
| 594 |
+
|
| 595 |
+
def test_mk_func_literal(self):
|
| 596 |
+
"""make sure make_function is passed to typer class as a literal
|
| 597 |
+
"""
|
| 598 |
+
test_ir = compiler.run_frontend(mk_func_test_impl)
|
| 599 |
+
typingctx = cpu_target.typing_context
|
| 600 |
+
targetctx = cpu_target.target_context
|
| 601 |
+
typingctx.refresh()
|
| 602 |
+
targetctx.refresh()
|
| 603 |
+
typing_res = type_inference_stage(typingctx, targetctx, test_ir, (),
|
| 604 |
+
None)
|
| 605 |
+
self.assertTrue(
|
| 606 |
+
any(
|
| 607 |
+
isinstance(a, types.MakeFunctionLiteral)
|
| 608 |
+
for a in typing_res.typemap.values()
|
| 609 |
+
)
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
class TestPandasLike(TestCase):
|
| 614 |
+
"""
|
| 615 |
+
Test implementing a pandas-like Index object.
|
| 616 |
+
Also stresses most of the high-level API.
|
| 617 |
+
"""
|
| 618 |
+
|
| 619 |
+
def test_index_len(self):
|
| 620 |
+
i = Index(np.arange(3))
|
| 621 |
+
cfunc = jit(nopython=True)(len_usecase)
|
| 622 |
+
self.assertPreciseEqual(cfunc(i), 3)
|
| 623 |
+
|
| 624 |
+
def test_index_getitem(self):
|
| 625 |
+
i = Index(np.int32([42, 8, -5]))
|
| 626 |
+
cfunc = jit(nopython=True)(getitem_usecase)
|
| 627 |
+
self.assertPreciseEqual(cfunc(i, 1), 8)
|
| 628 |
+
ii = cfunc(i, slice(1, None))
|
| 629 |
+
self.assertIsInstance(ii, Index)
|
| 630 |
+
self.assertEqual(list(ii), [8, -5])
|
| 631 |
+
|
| 632 |
+
def test_index_ufunc(self):
|
| 633 |
+
"""
|
| 634 |
+
Check Numpy ufunc on an Index object.
|
| 635 |
+
"""
|
| 636 |
+
i = Index(np.int32([42, 8, -5]))
|
| 637 |
+
cfunc = jit(nopython=True)(npyufunc_usecase)
|
| 638 |
+
ii = cfunc(i)
|
| 639 |
+
self.assertIsInstance(ii, Index)
|
| 640 |
+
self.assertPreciseEqual(ii._data, np.cos(np.sin(i._data)))
|
| 641 |
+
|
| 642 |
+
def test_index_get_data(self):
|
| 643 |
+
# The _data attribute is exposed with make_attribute_wrapper()
|
| 644 |
+
i = Index(np.int32([42, 8, -5]))
|
| 645 |
+
cfunc = jit(nopython=True)(get_data_usecase)
|
| 646 |
+
data = cfunc(i)
|
| 647 |
+
self.assertIs(data, i._data)
|
| 648 |
+
|
| 649 |
+
def test_index_is_monotonic(self):
|
| 650 |
+
# The is_monotonic_increasing attribute is exposed with
|
| 651 |
+
# overload_attribute()
|
| 652 |
+
cfunc = jit(nopython=True)(is_monotonic_usecase)
|
| 653 |
+
for values, expected in [
|
| 654 |
+
([8, 42, 5], False),
|
| 655 |
+
([5, 8, 42], True),
|
| 656 |
+
([], True),
|
| 657 |
+
]:
|
| 658 |
+
i = Index(np.int32(values))
|
| 659 |
+
got = cfunc(i)
|
| 660 |
+
self.assertEqual(got, expected)
|
| 661 |
+
|
| 662 |
+
def test_series_len(self):
|
| 663 |
+
i = Index(np.int32([2, 4, 3]))
|
| 664 |
+
s = Series(np.float64([1.5, 4.0, 2.5]), i)
|
| 665 |
+
cfunc = jit(nopython=True)(len_usecase)
|
| 666 |
+
self.assertPreciseEqual(cfunc(s), 3)
|
| 667 |
+
|
| 668 |
+
def test_series_get_index(self):
|
| 669 |
+
i = Index(np.int32([2, 4, 3]))
|
| 670 |
+
s = Series(np.float64([1.5, 4.0, 2.5]), i)
|
| 671 |
+
cfunc = jit(nopython=True)(get_index_usecase)
|
| 672 |
+
got = cfunc(s)
|
| 673 |
+
self.assertIsInstance(got, Index)
|
| 674 |
+
self.assertIs(got._data, i._data)
|
| 675 |
+
|
| 676 |
+
def test_series_ufunc(self):
|
| 677 |
+
"""
|
| 678 |
+
Check Numpy ufunc on an Series object.
|
| 679 |
+
"""
|
| 680 |
+
i = Index(np.int32([42, 8, -5]))
|
| 681 |
+
s = Series(np.int64([1, 2, 3]), i)
|
| 682 |
+
cfunc = jit(nopython=True)(npyufunc_usecase)
|
| 683 |
+
ss = cfunc(s)
|
| 684 |
+
self.assertIsInstance(ss, Series)
|
| 685 |
+
self.assertIsInstance(ss._index, Index)
|
| 686 |
+
self.assertIs(ss._index._data, i._data)
|
| 687 |
+
self.assertPreciseEqual(ss._values, np.cos(np.sin(s._values)))
|
| 688 |
+
|
| 689 |
+
def test_series_constructor(self):
|
| 690 |
+
i = Index(np.int32([42, 8, -5]))
|
| 691 |
+
d = np.float64([1.5, 4.0, 2.5])
|
| 692 |
+
cfunc = jit(nopython=True)(make_series_usecase)
|
| 693 |
+
got = cfunc(d, i)
|
| 694 |
+
self.assertIsInstance(got, Series)
|
| 695 |
+
self.assertIsInstance(got._index, Index)
|
| 696 |
+
self.assertIs(got._index._data, i._data)
|
| 697 |
+
self.assertIs(got._values, d)
|
| 698 |
+
|
| 699 |
+
def test_series_clip(self):
|
| 700 |
+
i = Index(np.int32([42, 8, -5]))
|
| 701 |
+
s = Series(np.float64([1.5, 4.0, 2.5]), i)
|
| 702 |
+
cfunc = jit(nopython=True)(clip_usecase)
|
| 703 |
+
ss = cfunc(s, 1.6, 3.0)
|
| 704 |
+
self.assertIsInstance(ss, Series)
|
| 705 |
+
self.assertIsInstance(ss._index, Index)
|
| 706 |
+
self.assertIs(ss._index._data, i._data)
|
| 707 |
+
self.assertPreciseEqual(ss._values, np.float64([1.6, 3.0, 2.5]))
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
class TestHighLevelExtending(TestCase):
|
| 711 |
+
"""
|
| 712 |
+
Test the high-level combined API.
|
| 713 |
+
"""
|
| 714 |
+
|
| 715 |
+
def test_where(self):
|
| 716 |
+
"""
|
| 717 |
+
Test implementing a function with @overload.
|
| 718 |
+
"""
|
| 719 |
+
pyfunc = call_where
|
| 720 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 721 |
+
|
| 722 |
+
def check(*args, **kwargs):
|
| 723 |
+
expected = np_where(*args, **kwargs)
|
| 724 |
+
got = cfunc(*args, **kwargs)
|
| 725 |
+
self.assertPreciseEqual(expected, got)
|
| 726 |
+
|
| 727 |
+
check(x=3, cond=True, y=8)
|
| 728 |
+
check(True, 3, 8)
|
| 729 |
+
check(
|
| 730 |
+
np.bool_([True, False, True]),
|
| 731 |
+
np.int32([1, 2, 3]),
|
| 732 |
+
np.int32([4, 5, 5]),
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# The typing error is propagated
|
| 736 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 737 |
+
cfunc(np.bool_([]), np.int32([]), np.int64([]))
|
| 738 |
+
self.assertIn(
|
| 739 |
+
"x and y should have the same dtype", str(raises.exception)
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
def test_len(self):
|
| 743 |
+
"""
|
| 744 |
+
Test re-implementing len() for a custom type with @overload.
|
| 745 |
+
"""
|
| 746 |
+
cfunc = jit(nopython=True)(len_usecase)
|
| 747 |
+
self.assertPreciseEqual(cfunc(MyDummy()), 13)
|
| 748 |
+
self.assertPreciseEqual(cfunc([4, 5]), 2)
|
| 749 |
+
|
| 750 |
+
def test_print(self):
|
| 751 |
+
"""
|
| 752 |
+
Test re-implementing print() for a custom type with @overload.
|
| 753 |
+
"""
|
| 754 |
+
cfunc = jit(nopython=True)(print_usecase)
|
| 755 |
+
with captured_stdout():
|
| 756 |
+
cfunc(MyDummy())
|
| 757 |
+
self.assertEqual(sys.stdout.getvalue(), "hello!\n")
|
| 758 |
+
|
| 759 |
+
def test_add_operator(self):
|
| 760 |
+
"""
|
| 761 |
+
Test re-implementing operator.add() for a custom type with @overload.
|
| 762 |
+
"""
|
| 763 |
+
pyfunc = call_add_operator
|
| 764 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 765 |
+
|
| 766 |
+
self.assertPreciseEqual(cfunc(1, 2), 3)
|
| 767 |
+
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
|
| 768 |
+
|
| 769 |
+
# this will call add(Number, Number) as MyDummy implicitly casts to
|
| 770 |
+
# Number
|
| 771 |
+
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
|
| 772 |
+
|
| 773 |
+
def test_add_binop(self):
|
| 774 |
+
"""
|
| 775 |
+
Test re-implementing '+' for a custom type via @overload(operator.add).
|
| 776 |
+
"""
|
| 777 |
+
pyfunc = call_add_binop
|
| 778 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 779 |
+
|
| 780 |
+
self.assertPreciseEqual(cfunc(1, 2), 3)
|
| 781 |
+
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
|
| 782 |
+
|
| 783 |
+
# this will call add(Number, Number) as MyDummy implicitly casts to
|
| 784 |
+
# Number
|
| 785 |
+
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
|
| 786 |
+
|
| 787 |
+
def test_iadd_operator(self):
|
| 788 |
+
"""
|
| 789 |
+
Test re-implementing operator.add() for a custom type with @overload.
|
| 790 |
+
"""
|
| 791 |
+
pyfunc = call_iadd_operator
|
| 792 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 793 |
+
|
| 794 |
+
self.assertPreciseEqual(cfunc(1, 2), 3)
|
| 795 |
+
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
|
| 796 |
+
|
| 797 |
+
# this will call add(Number, Number) as MyDummy implicitly casts to
|
| 798 |
+
# Number
|
| 799 |
+
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
|
| 800 |
+
|
| 801 |
+
def test_iadd_binop(self):
|
| 802 |
+
"""
|
| 803 |
+
Test re-implementing '+' for a custom type via @overload(operator.add).
|
| 804 |
+
"""
|
| 805 |
+
pyfunc = call_iadd_binop
|
| 806 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 807 |
+
|
| 808 |
+
self.assertPreciseEqual(cfunc(1, 2), 3)
|
| 809 |
+
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
|
| 810 |
+
|
| 811 |
+
# this will call add(Number, Number) as MyDummy implicitly casts to
|
| 812 |
+
# Number
|
| 813 |
+
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
|
| 814 |
+
|
| 815 |
+
def test_delitem(self):
|
| 816 |
+
pyfunc = call_delitem
|
| 817 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 818 |
+
obj = MyDummy()
|
| 819 |
+
e = None
|
| 820 |
+
|
| 821 |
+
with captured_stdout() as out:
|
| 822 |
+
try:
|
| 823 |
+
cfunc(obj, 321)
|
| 824 |
+
except Exception as exc:
|
| 825 |
+
e = exc
|
| 826 |
+
|
| 827 |
+
if e is not None:
|
| 828 |
+
raise e
|
| 829 |
+
self.assertEqual(out.getvalue(), "del hello! 321\n")
|
| 830 |
+
|
| 831 |
+
def test_getitem(self):
|
| 832 |
+
pyfunc = call_getitem
|
| 833 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 834 |
+
self.assertPreciseEqual(cfunc(MyDummy(), 321), 321 + 123)
|
| 835 |
+
|
| 836 |
+
def test_setitem(self):
|
| 837 |
+
pyfunc = call_setitem
|
| 838 |
+
cfunc = jit(nopython=True)(pyfunc)
|
| 839 |
+
obj = MyDummy()
|
| 840 |
+
e = None
|
| 841 |
+
|
| 842 |
+
with captured_stdout() as out:
|
| 843 |
+
try:
|
| 844 |
+
cfunc(obj, 321, 123)
|
| 845 |
+
except Exception as exc:
|
| 846 |
+
e = exc
|
| 847 |
+
|
| 848 |
+
if e is not None:
|
| 849 |
+
raise e
|
| 850 |
+
self.assertEqual(out.getvalue(), "321 123\n")
|
| 851 |
+
|
| 852 |
+
def test_no_cpython_wrapper(self):
|
| 853 |
+
"""
|
| 854 |
+
Test overloading whose return value cannot be represented in CPython.
|
| 855 |
+
"""
|
| 856 |
+
# Test passing Module type from a @overload implementation to ensure
|
| 857 |
+
# that the *no_cpython_wrapper* flag works
|
| 858 |
+
ok_cfunc = jit(nopython=True)(non_boxable_ok_usecase)
|
| 859 |
+
n = 10
|
| 860 |
+
got = ok_cfunc(n)
|
| 861 |
+
expect = non_boxable_ok_usecase(n)
|
| 862 |
+
np.testing.assert_equal(expect, got)
|
| 863 |
+
# Verify that the Module type cannot be returned to CPython
|
| 864 |
+
bad_cfunc = jit(nopython=True)(non_boxable_bad_usecase)
|
| 865 |
+
with self.assertRaises(TypeError) as raises:
|
| 866 |
+
bad_cfunc()
|
| 867 |
+
errmsg = str(raises.exception)
|
| 868 |
+
expectmsg = "cannot convert native Module"
|
| 869 |
+
self.assertIn(expectmsg, errmsg)
|
| 870 |
+
|
| 871 |
+
def test_typing_vs_impl_signature_mismatch_handling(self):
|
| 872 |
+
"""
|
| 873 |
+
Tests that an overload which has a differing typing and implementing
|
| 874 |
+
signature raises an exception.
|
| 875 |
+
"""
|
| 876 |
+
|
| 877 |
+
def gen_ol(impl=None):
|
| 878 |
+
def myoverload(a, b, c, kw=None):
|
| 879 |
+
pass
|
| 880 |
+
|
| 881 |
+
@overload(myoverload)
|
| 882 |
+
def _myoverload_impl(a, b, c, kw=None):
|
| 883 |
+
return impl
|
| 884 |
+
|
| 885 |
+
@jit(nopython=True)
|
| 886 |
+
def foo(a, b, c, d):
|
| 887 |
+
myoverload(a, b, c, kw=d)
|
| 888 |
+
|
| 889 |
+
return foo
|
| 890 |
+
|
| 891 |
+
sentinel = "Typing and implementation arguments differ in"
|
| 892 |
+
|
| 893 |
+
# kwarg value is different
|
| 894 |
+
def impl1(a, b, c, kw=12):
|
| 895 |
+
if a > 10:
|
| 896 |
+
return 1
|
| 897 |
+
else:
|
| 898 |
+
return -1
|
| 899 |
+
|
| 900 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 901 |
+
gen_ol(impl1)(1, 2, 3, 4)
|
| 902 |
+
msg = str(e.exception)
|
| 903 |
+
self.assertIn(sentinel, msg)
|
| 904 |
+
self.assertIn("keyword argument default values", msg)
|
| 905 |
+
self.assertIn('<Parameter "kw=12">', msg)
|
| 906 |
+
self.assertIn('<Parameter "kw=None">', msg)
|
| 907 |
+
|
| 908 |
+
# kwarg name is different
|
| 909 |
+
def impl2(a, b, c, kwarg=None):
|
| 910 |
+
if a > 10:
|
| 911 |
+
return 1
|
| 912 |
+
else:
|
| 913 |
+
return -1
|
| 914 |
+
|
| 915 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 916 |
+
gen_ol(impl2)(1, 2, 3, 4)
|
| 917 |
+
msg = str(e.exception)
|
| 918 |
+
self.assertIn(sentinel, msg)
|
| 919 |
+
self.assertIn("keyword argument names", msg)
|
| 920 |
+
self.assertIn('<Parameter "kwarg=None">', msg)
|
| 921 |
+
self.assertIn('<Parameter "kw=None">', msg)
|
| 922 |
+
|
| 923 |
+
# arg name is different
|
| 924 |
+
def impl3(z, b, c, kw=None):
|
| 925 |
+
if a > 10: # noqa: F821
|
| 926 |
+
return 1
|
| 927 |
+
else:
|
| 928 |
+
return -1
|
| 929 |
+
|
| 930 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 931 |
+
gen_ol(impl3)(1, 2, 3, 4)
|
| 932 |
+
msg = str(e.exception)
|
| 933 |
+
self.assertIn(sentinel, msg)
|
| 934 |
+
self.assertIn("argument names", msg)
|
| 935 |
+
self.assertFalse("keyword" in msg)
|
| 936 |
+
self.assertIn('<Parameter "a">', msg)
|
| 937 |
+
self.assertIn('<Parameter "z">', msg)
|
| 938 |
+
|
| 939 |
+
from .overload_usecases import impl4, impl5
|
| 940 |
+
|
| 941 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 942 |
+
gen_ol(impl4)(1, 2, 3, 4)
|
| 943 |
+
msg = str(e.exception)
|
| 944 |
+
self.assertIn(sentinel, msg)
|
| 945 |
+
self.assertIn("argument names", msg)
|
| 946 |
+
self.assertFalse("keyword" in msg)
|
| 947 |
+
self.assertIn("First difference: 'z'", msg)
|
| 948 |
+
|
| 949 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 950 |
+
gen_ol(impl5)(1, 2, 3, 4)
|
| 951 |
+
msg = str(e.exception)
|
| 952 |
+
self.assertIn(sentinel, msg)
|
| 953 |
+
self.assertIn("argument names", msg)
|
| 954 |
+
self.assertFalse("keyword" in msg)
|
| 955 |
+
self.assertIn('<Parameter "a">', msg)
|
| 956 |
+
self.assertIn('<Parameter "z">', msg)
|
| 957 |
+
|
| 958 |
+
# too many args
|
| 959 |
+
def impl6(a, b, c, d, e, kw=None):
|
| 960 |
+
if a > 10:
|
| 961 |
+
return 1
|
| 962 |
+
else:
|
| 963 |
+
return -1
|
| 964 |
+
|
| 965 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 966 |
+
gen_ol(impl6)(1, 2, 3, 4)
|
| 967 |
+
msg = str(e.exception)
|
| 968 |
+
self.assertIn(sentinel, msg)
|
| 969 |
+
self.assertIn("argument names", msg)
|
| 970 |
+
self.assertFalse("keyword" in msg)
|
| 971 |
+
self.assertIn('<Parameter "d">', msg)
|
| 972 |
+
self.assertIn('<Parameter "e">', msg)
|
| 973 |
+
|
| 974 |
+
# too few args
|
| 975 |
+
def impl7(a, b, kw=None):
|
| 976 |
+
if a > 10:
|
| 977 |
+
return 1
|
| 978 |
+
else:
|
| 979 |
+
return -1
|
| 980 |
+
|
| 981 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 982 |
+
gen_ol(impl7)(1, 2, 3, 4)
|
| 983 |
+
msg = str(e.exception)
|
| 984 |
+
self.assertIn(sentinel, msg)
|
| 985 |
+
self.assertIn("argument names", msg)
|
| 986 |
+
self.assertFalse("keyword" in msg)
|
| 987 |
+
self.assertIn('<Parameter "c">', msg)
|
| 988 |
+
|
| 989 |
+
# too many kwargs
|
| 990 |
+
def impl8(a, b, c, kw=None, extra_kwarg=None):
|
| 991 |
+
if a > 10:
|
| 992 |
+
return 1
|
| 993 |
+
else:
|
| 994 |
+
return -1
|
| 995 |
+
|
| 996 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 997 |
+
gen_ol(impl8)(1, 2, 3, 4)
|
| 998 |
+
msg = str(e.exception)
|
| 999 |
+
self.assertIn(sentinel, msg)
|
| 1000 |
+
self.assertIn("keyword argument names", msg)
|
| 1001 |
+
self.assertIn('<Parameter "extra_kwarg=None">', msg)
|
| 1002 |
+
|
| 1003 |
+
# too few kwargs
|
| 1004 |
+
def impl9(a, b, c):
|
| 1005 |
+
if a > 10:
|
| 1006 |
+
return 1
|
| 1007 |
+
else:
|
| 1008 |
+
return -1
|
| 1009 |
+
|
| 1010 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 1011 |
+
gen_ol(impl9)(1, 2, 3, 4)
|
| 1012 |
+
msg = str(e.exception)
|
| 1013 |
+
self.assertIn(sentinel, msg)
|
| 1014 |
+
self.assertIn("keyword argument names", msg)
|
| 1015 |
+
self.assertIn('<Parameter "kw=None">', msg)
|
| 1016 |
+
|
| 1017 |
+
def test_typing_vs_impl_signature_mismatch_handling_var_positional(self):
|
| 1018 |
+
"""
|
| 1019 |
+
Tests that an overload which has a differing typing and implementing
|
| 1020 |
+
signature raises an exception and uses VAR_POSITIONAL (*args) in typing
|
| 1021 |
+
"""
|
| 1022 |
+
|
| 1023 |
+
def myoverload(a, kw=None):
|
| 1024 |
+
pass
|
| 1025 |
+
|
| 1026 |
+
from .overload_usecases import var_positional_impl
|
| 1027 |
+
|
| 1028 |
+
overload(myoverload)(var_positional_impl)
|
| 1029 |
+
|
| 1030 |
+
@jit(nopython=True)
|
| 1031 |
+
def foo(a, b):
|
| 1032 |
+
return myoverload(a, b, 9, kw=11)
|
| 1033 |
+
|
| 1034 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 1035 |
+
foo(1, 5)
|
| 1036 |
+
msg = str(e.exception)
|
| 1037 |
+
self.assertIn("VAR_POSITIONAL (e.g. *args) argument kind", msg)
|
| 1038 |
+
self.assertIn("offending argument name is '*star_args_token'", msg)
|
| 1039 |
+
|
| 1040 |
+
def test_typing_vs_impl_signature_mismatch_handling_var_keyword(self):
|
| 1041 |
+
"""
|
| 1042 |
+
Tests that an overload which uses **kwargs (VAR_KEYWORD)
|
| 1043 |
+
"""
|
| 1044 |
+
|
| 1045 |
+
def gen_ol(impl, strict=True):
|
| 1046 |
+
def myoverload(a, kw=None):
|
| 1047 |
+
pass
|
| 1048 |
+
|
| 1049 |
+
overload(myoverload, strict=strict)(impl)
|
| 1050 |
+
|
| 1051 |
+
@jit(nopython=True)
|
| 1052 |
+
def foo(a, b):
|
| 1053 |
+
return myoverload(a, kw=11)
|
| 1054 |
+
|
| 1055 |
+
return foo
|
| 1056 |
+
|
| 1057 |
+
# **kwargs in typing
|
| 1058 |
+
def ol1(a, **kws):
|
| 1059 |
+
def impl(a, kw=10):
|
| 1060 |
+
return a
|
| 1061 |
+
|
| 1062 |
+
return impl
|
| 1063 |
+
|
| 1064 |
+
gen_ol(ol1, False)(1, 2) # no error if strictness not enforced
|
| 1065 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 1066 |
+
gen_ol(ol1)(1, 2)
|
| 1067 |
+
msg = str(e.exception)
|
| 1068 |
+
self.assertIn("use of VAR_KEYWORD (e.g. **kwargs) is unsupported", msg)
|
| 1069 |
+
self.assertIn("offending argument name is '**kws'", msg)
|
| 1070 |
+
|
| 1071 |
+
# **kwargs in implementation
|
| 1072 |
+
def ol2(a, kw=0):
|
| 1073 |
+
def impl(a, **kws):
|
| 1074 |
+
return a
|
| 1075 |
+
|
| 1076 |
+
return impl
|
| 1077 |
+
|
| 1078 |
+
with self.assertRaises(errors.TypingError) as e:
|
| 1079 |
+
gen_ol(ol2)(1, 2)
|
| 1080 |
+
msg = str(e.exception)
|
| 1081 |
+
self.assertIn("use of VAR_KEYWORD (e.g. **kwargs) is unsupported", msg)
|
| 1082 |
+
self.assertIn("offending argument name is '**kws'", msg)
|
| 1083 |
+
|
| 1084 |
+
def test_overload_method_kwargs(self):
|
| 1085 |
+
# Issue #3489
|
| 1086 |
+
@overload_method(types.Array, "foo")
|
| 1087 |
+
def fooimpl(arr, a_kwarg=10):
|
| 1088 |
+
def impl(arr, a_kwarg=10):
|
| 1089 |
+
return a_kwarg
|
| 1090 |
+
|
| 1091 |
+
return impl
|
| 1092 |
+
|
| 1093 |
+
@njit
|
| 1094 |
+
def bar(A):
|
| 1095 |
+
return A.foo(), A.foo(20), A.foo(a_kwarg=30)
|
| 1096 |
+
|
| 1097 |
+
Z = np.arange(5)
|
| 1098 |
+
|
| 1099 |
+
self.assertEqual(bar(Z), (10, 20, 30))
|
| 1100 |
+
|
| 1101 |
+
def test_overload_method_literal_unpack(self):
|
| 1102 |
+
# Issue #3683
|
| 1103 |
+
@overload_method(types.Array, "litfoo")
|
| 1104 |
+
def litfoo(arr, val):
|
| 1105 |
+
# Must be an integer
|
| 1106 |
+
if isinstance(val, types.Integer):
|
| 1107 |
+
# Must not be literal
|
| 1108 |
+
if not isinstance(val, types.Literal):
|
| 1109 |
+
|
| 1110 |
+
def impl(arr, val):
|
| 1111 |
+
return val
|
| 1112 |
+
|
| 1113 |
+
return impl
|
| 1114 |
+
|
| 1115 |
+
@njit
|
| 1116 |
+
def bar(A):
|
| 1117 |
+
return A.litfoo(0xCAFE)
|
| 1118 |
+
|
| 1119 |
+
A = np.zeros(1)
|
| 1120 |
+
bar(A)
|
| 1121 |
+
self.assertEqual(bar(A), 0xCAFE)
|
| 1122 |
+
|
| 1123 |
+
def test_overload_ufunc(self):
|
| 1124 |
+
# Issue #4133.
|
| 1125 |
+
# Use an extended type (MyDummyType) to use with a customized
|
| 1126 |
+
# ufunc (np.exp).
|
| 1127 |
+
@njit
|
| 1128 |
+
def test():
|
| 1129 |
+
return np.exp(mydummy)
|
| 1130 |
+
|
| 1131 |
+
self.assertEqual(test(), 0xDEADBEEF)
|
| 1132 |
+
|
| 1133 |
+
def test_overload_method_stararg(self):
|
| 1134 |
+
@overload_method(MyDummyType, "method_stararg")
|
| 1135 |
+
def _ov_method_stararg(obj, val, val2, *args):
|
| 1136 |
+
def get(obj, val, val2, *args):
|
| 1137 |
+
return (val, val2, args)
|
| 1138 |
+
|
| 1139 |
+
return get
|
| 1140 |
+
|
| 1141 |
+
@njit
|
| 1142 |
+
def foo(obj, *args):
|
| 1143 |
+
# Test with expanding stararg
|
| 1144 |
+
return obj.method_stararg(*args)
|
| 1145 |
+
|
| 1146 |
+
obj = MyDummy()
|
| 1147 |
+
self.assertEqual(foo(obj, 1, 2), (1, 2, ()))
|
| 1148 |
+
self.assertEqual(foo(obj, 1, 2, 3), (1, 2, (3,)))
|
| 1149 |
+
self.assertEqual(foo(obj, 1, 2, 3, 4), (1, 2, (3, 4)))
|
| 1150 |
+
|
| 1151 |
+
@njit
|
| 1152 |
+
def bar(obj):
|
| 1153 |
+
# Test with explicit argument
|
| 1154 |
+
return (
|
| 1155 |
+
obj.method_stararg(1, 2),
|
| 1156 |
+
obj.method_stararg(1, 2, 3),
|
| 1157 |
+
obj.method_stararg(1, 2, 3, 4),
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
self.assertEqual(
|
| 1161 |
+
bar(obj), ((1, 2, ()), (1, 2, (3,)), (1, 2, (3, 4))),
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
# Check cases that put tuple type into stararg
|
| 1165 |
+
# NOTE: the expected result has an extra tuple because of stararg.
|
| 1166 |
+
self.assertEqual(
|
| 1167 |
+
foo(obj, 1, 2, (3,)), (1, 2, ((3,),)),
|
| 1168 |
+
)
|
| 1169 |
+
self.assertEqual(
|
| 1170 |
+
foo(obj, 1, 2, (3, 4)), (1, 2, ((3, 4),)),
|
| 1171 |
+
)
|
| 1172 |
+
self.assertEqual(
|
| 1173 |
+
foo(obj, 1, 2, (3, (4, 5))), (1, 2, ((3, (4, 5)),)),
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
def test_overload_classmethod(self):
|
| 1177 |
+
# Add classmethod to a subclass of Array
|
| 1178 |
+
class MyArray(types.Array):
|
| 1179 |
+
pass
|
| 1180 |
+
|
| 1181 |
+
@overload_classmethod(MyArray, "array_alloc")
|
| 1182 |
+
def ol_array_alloc(cls, nitems):
|
| 1183 |
+
def impl(cls, nitems):
|
| 1184 |
+
arr = np.arange(nitems)
|
| 1185 |
+
return arr
|
| 1186 |
+
return impl
|
| 1187 |
+
|
| 1188 |
+
@njit
|
| 1189 |
+
def foo(nitems):
|
| 1190 |
+
return MyArray.array_alloc(nitems)
|
| 1191 |
+
|
| 1192 |
+
nitems = 13
|
| 1193 |
+
self.assertPreciseEqual(foo(nitems), np.arange(nitems))
|
| 1194 |
+
|
| 1195 |
+
# Check that the base type doesn't get the classmethod
|
| 1196 |
+
|
| 1197 |
+
@njit
|
| 1198 |
+
def no_classmethod_in_base(nitems):
|
| 1199 |
+
return types.Array.array_alloc(nitems)
|
| 1200 |
+
|
| 1201 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1202 |
+
no_classmethod_in_base(nitems)
|
| 1203 |
+
self.assertIn(
|
| 1204 |
+
"Unknown attribute 'array_alloc' of",
|
| 1205 |
+
str(raises.exception),
|
| 1206 |
+
)
|
| 1207 |
+
|
| 1208 |
+
def test_overload_callable_typeref(self):
|
| 1209 |
+
|
| 1210 |
+
@overload(CallableTypeRef)
|
| 1211 |
+
def callable_type_call_ovld1(x):
|
| 1212 |
+
if isinstance(x, types.Integer):
|
| 1213 |
+
def impl(x):
|
| 1214 |
+
return 42.5 + x
|
| 1215 |
+
return impl
|
| 1216 |
+
|
| 1217 |
+
@overload(CallableTypeRef)
|
| 1218 |
+
def callable_type_call_ovld2(x):
|
| 1219 |
+
if isinstance(x, types.UnicodeType):
|
| 1220 |
+
def impl(x):
|
| 1221 |
+
return '42.5' + x
|
| 1222 |
+
|
| 1223 |
+
return impl
|
| 1224 |
+
|
| 1225 |
+
@njit
|
| 1226 |
+
def foo(a, b):
|
| 1227 |
+
return MyClass(a), MyClass(b)
|
| 1228 |
+
|
| 1229 |
+
args = (4, '4')
|
| 1230 |
+
expected = (42.5 + args[0], '42.5' + args[1])
|
| 1231 |
+
self.assertPreciseEqual(foo(*args), expected)
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
def _assert_cache_stats(cfunc, expect_hit, expect_misses):
|
| 1235 |
+
hit = cfunc._cache_hits[cfunc.signatures[0]]
|
| 1236 |
+
if hit != expect_hit:
|
| 1237 |
+
raise AssertionError("cache not used")
|
| 1238 |
+
miss = cfunc._cache_misses[cfunc.signatures[0]]
|
| 1239 |
+
if miss != expect_misses:
|
| 1240 |
+
raise AssertionError("cache not used")
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
@skip_if_typeguard
|
| 1244 |
+
class TestOverloadMethodCaching(TestCase):
|
| 1245 |
+
# Nested multiprocessing.Pool raises AssertionError:
|
| 1246 |
+
# "daemonic processes are not allowed to have children"
|
| 1247 |
+
_numba_parallel_test_ = False
|
| 1248 |
+
|
| 1249 |
+
def test_caching_overload_method(self):
|
| 1250 |
+
self._cache_dir = temp_directory(self.__class__.__name__)
|
| 1251 |
+
with override_config("CACHE_DIR", self._cache_dir):
|
| 1252 |
+
self.run_caching_overload_method()
|
| 1253 |
+
|
| 1254 |
+
def run_caching_overload_method(self):
|
| 1255 |
+
cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase)
|
| 1256 |
+
self.assertPreciseEqual(cfunc(MyDummy()), 13)
|
| 1257 |
+
_assert_cache_stats(cfunc, 0, 1)
|
| 1258 |
+
llvmir = cfunc.inspect_llvm((mydummy_type,))
|
| 1259 |
+
# Ensure the inner method is not a declaration
|
| 1260 |
+
decls = [
|
| 1261 |
+
ln
|
| 1262 |
+
for ln in llvmir.splitlines()
|
| 1263 |
+
if ln.startswith("declare") and "overload_method_length" in ln
|
| 1264 |
+
]
|
| 1265 |
+
self.assertEqual(len(decls), 0)
|
| 1266 |
+
# Test in a separate process
|
| 1267 |
+
try:
|
| 1268 |
+
ctx = multiprocessing.get_context("spawn")
|
| 1269 |
+
except AttributeError:
|
| 1270 |
+
ctx = multiprocessing
|
| 1271 |
+
q = ctx.Queue()
|
| 1272 |
+
p = ctx.Process(
|
| 1273 |
+
target=run_caching_overload_method, args=(q, self._cache_dir)
|
| 1274 |
+
)
|
| 1275 |
+
p.start()
|
| 1276 |
+
q.put(MyDummy())
|
| 1277 |
+
p.join()
|
| 1278 |
+
# Ensure subprocess exited normally
|
| 1279 |
+
self.assertEqual(p.exitcode, 0)
|
| 1280 |
+
res = q.get(timeout=1)
|
| 1281 |
+
self.assertEqual(res, 13)
|
| 1282 |
+
|
| 1283 |
+
|
| 1284 |
+
def run_caching_overload_method(q, cache_dir):
|
| 1285 |
+
"""
|
| 1286 |
+
Used by TestOverloadMethodCaching.test_caching_overload_method
|
| 1287 |
+
"""
|
| 1288 |
+
with override_config("CACHE_DIR", cache_dir):
|
| 1289 |
+
arg = q.get()
|
| 1290 |
+
cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase)
|
| 1291 |
+
res = cfunc(arg)
|
| 1292 |
+
q.put(res)
|
| 1293 |
+
# Check cache stat
|
| 1294 |
+
_assert_cache_stats(cfunc, 1, 0)
|
| 1295 |
+
|
| 1296 |
+
|
| 1297 |
+
class TestIntrinsic(TestCase):
|
| 1298 |
+
def test_void_return(self):
|
| 1299 |
+
"""
|
| 1300 |
+
Verify that returning a None from codegen function is handled
|
| 1301 |
+
automatically for void functions, otherwise raise exception.
|
| 1302 |
+
"""
|
| 1303 |
+
|
| 1304 |
+
@intrinsic
|
| 1305 |
+
def void_func(typingctx, a):
|
| 1306 |
+
sig = types.void(types.int32)
|
| 1307 |
+
|
| 1308 |
+
def codegen(context, builder, signature, args):
|
| 1309 |
+
pass # do nothing, return None, should be turned into
|
| 1310 |
+
# dummy value
|
| 1311 |
+
|
| 1312 |
+
return sig, codegen
|
| 1313 |
+
|
| 1314 |
+
@intrinsic
|
| 1315 |
+
def non_void_func(typingctx, a):
|
| 1316 |
+
sig = types.int32(types.int32)
|
| 1317 |
+
|
| 1318 |
+
def codegen(context, builder, signature, args):
|
| 1319 |
+
pass # oops, should be returning a value here, raise exception
|
| 1320 |
+
|
| 1321 |
+
return sig, codegen
|
| 1322 |
+
|
| 1323 |
+
@jit(nopython=True)
|
| 1324 |
+
def call_void_func():
|
| 1325 |
+
void_func(1)
|
| 1326 |
+
return 0
|
| 1327 |
+
|
| 1328 |
+
@jit(nopython=True)
|
| 1329 |
+
def call_non_void_func():
|
| 1330 |
+
non_void_func(1)
|
| 1331 |
+
return 0
|
| 1332 |
+
|
| 1333 |
+
# void func should work
|
| 1334 |
+
self.assertEqual(call_void_func(), 0)
|
| 1335 |
+
# not void function should raise exception
|
| 1336 |
+
with self.assertRaises(LoweringError) as e:
|
| 1337 |
+
call_non_void_func()
|
| 1338 |
+
self.assertIn("non-void function returns None", e.exception.msg)
|
| 1339 |
+
|
| 1340 |
+
def test_ll_pointer_cast(self):
|
| 1341 |
+
"""
|
| 1342 |
+
Usecase test: custom reinterpret cast to turn int values to pointers
|
| 1343 |
+
"""
|
| 1344 |
+
from ctypes import CFUNCTYPE, POINTER, c_float, c_int
|
| 1345 |
+
|
| 1346 |
+
# Use intrinsic to make a reinterpret_cast operation
|
| 1347 |
+
def unsafe_caster(result_type):
|
| 1348 |
+
assert isinstance(result_type, types.CPointer)
|
| 1349 |
+
|
| 1350 |
+
@intrinsic
|
| 1351 |
+
def unsafe_cast(typingctx, src):
|
| 1352 |
+
self.assertIsInstance(typingctx, typing.Context)
|
| 1353 |
+
if isinstance(src, types.Integer):
|
| 1354 |
+
sig = result_type(types.uintp)
|
| 1355 |
+
|
| 1356 |
+
# defines the custom code generation
|
| 1357 |
+
def codegen(context, builder, signature, args):
|
| 1358 |
+
[src] = args
|
| 1359 |
+
rtype = signature.return_type
|
| 1360 |
+
llrtype = context.get_value_type(rtype)
|
| 1361 |
+
return builder.inttoptr(src, llrtype)
|
| 1362 |
+
|
| 1363 |
+
return sig, codegen
|
| 1364 |
+
|
| 1365 |
+
return unsafe_cast
|
| 1366 |
+
|
| 1367 |
+
# make a nopython function to use our cast op.
|
| 1368 |
+
# this is not usable from cpython due to the returning of a pointer.
|
| 1369 |
+
def unsafe_get_ctypes_pointer(src):
|
| 1370 |
+
raise NotImplementedError("not callable from python")
|
| 1371 |
+
|
| 1372 |
+
@overload(unsafe_get_ctypes_pointer, strict=False)
|
| 1373 |
+
def array_impl_unsafe_get_ctypes_pointer(arrtype):
|
| 1374 |
+
if isinstance(arrtype, types.Array):
|
| 1375 |
+
unsafe_cast = unsafe_caster(types.CPointer(arrtype.dtype))
|
| 1376 |
+
|
| 1377 |
+
def array_impl(arr):
|
| 1378 |
+
return unsafe_cast(src=arr.ctypes.data)
|
| 1379 |
+
|
| 1380 |
+
return array_impl
|
| 1381 |
+
|
| 1382 |
+
# the ctype wrapped function for use in nopython mode
|
| 1383 |
+
def my_c_fun_raw(ptr, n):
|
| 1384 |
+
for i in range(n):
|
| 1385 |
+
print(ptr[i])
|
| 1386 |
+
|
| 1387 |
+
prototype = CFUNCTYPE(None, POINTER(c_float), c_int)
|
| 1388 |
+
my_c_fun = prototype(my_c_fun_raw)
|
| 1389 |
+
|
| 1390 |
+
# Call our pointer-cast in a @jit compiled function and use
|
| 1391 |
+
# the pointer in a ctypes function
|
| 1392 |
+
@jit(nopython=True)
|
| 1393 |
+
def foo(arr):
|
| 1394 |
+
ptr = unsafe_get_ctypes_pointer(arr)
|
| 1395 |
+
my_c_fun(ptr, arr.size)
|
| 1396 |
+
|
| 1397 |
+
# Test
|
| 1398 |
+
arr = np.arange(10, dtype=np.float32)
|
| 1399 |
+
with captured_stdout() as buf:
|
| 1400 |
+
foo(arr)
|
| 1401 |
+
got = buf.getvalue().splitlines()
|
| 1402 |
+
buf.close()
|
| 1403 |
+
expect = list(map(str, arr))
|
| 1404 |
+
self.assertEqual(expect, got)
|
| 1405 |
+
|
| 1406 |
+
def test_serialization(self):
|
| 1407 |
+
"""
|
| 1408 |
+
Test serialization of intrinsic objects
|
| 1409 |
+
"""
|
| 1410 |
+
# define a intrinsic
|
| 1411 |
+
@intrinsic
|
| 1412 |
+
def identity(context, x):
|
| 1413 |
+
def codegen(context, builder, signature, args):
|
| 1414 |
+
return args[0]
|
| 1415 |
+
|
| 1416 |
+
sig = x(x)
|
| 1417 |
+
return sig, codegen
|
| 1418 |
+
|
| 1419 |
+
# use in a jit function
|
| 1420 |
+
@jit(nopython=True)
|
| 1421 |
+
def foo(x):
|
| 1422 |
+
return identity(x)
|
| 1423 |
+
|
| 1424 |
+
self.assertEqual(foo(1), 1)
|
| 1425 |
+
|
| 1426 |
+
# get serialization memo
|
| 1427 |
+
memo = _Intrinsic._memo
|
| 1428 |
+
memo_size = len(memo)
|
| 1429 |
+
|
| 1430 |
+
# pickle foo and check memo size
|
| 1431 |
+
serialized_foo = pickle.dumps(foo)
|
| 1432 |
+
# increases the memo size
|
| 1433 |
+
memo_size += 1
|
| 1434 |
+
self.assertEqual(memo_size, len(memo))
|
| 1435 |
+
# unpickle
|
| 1436 |
+
foo_rebuilt = pickle.loads(serialized_foo)
|
| 1437 |
+
self.assertEqual(memo_size, len(memo))
|
| 1438 |
+
# check rebuilt foo
|
| 1439 |
+
self.assertEqual(foo(1), foo_rebuilt(1))
|
| 1440 |
+
|
| 1441 |
+
# pickle identity directly
|
| 1442 |
+
serialized_identity = pickle.dumps(identity)
|
| 1443 |
+
# memo size unchanged
|
| 1444 |
+
self.assertEqual(memo_size, len(memo))
|
| 1445 |
+
# unpickle
|
| 1446 |
+
identity_rebuilt = pickle.loads(serialized_identity)
|
| 1447 |
+
# must be the same object
|
| 1448 |
+
self.assertIs(identity, identity_rebuilt)
|
| 1449 |
+
# memo size unchanged
|
| 1450 |
+
self.assertEqual(memo_size, len(memo))
|
| 1451 |
+
|
| 1452 |
+
def test_deserialization(self):
|
| 1453 |
+
"""
|
| 1454 |
+
Test deserialization of intrinsic
|
| 1455 |
+
"""
|
| 1456 |
+
|
| 1457 |
+
def defn(context, x):
|
| 1458 |
+
def codegen(context, builder, signature, args):
|
| 1459 |
+
return args[0]
|
| 1460 |
+
|
| 1461 |
+
return x(x), codegen
|
| 1462 |
+
|
| 1463 |
+
memo = _Intrinsic._memo
|
| 1464 |
+
memo_size = len(memo)
|
| 1465 |
+
# invoke _Intrinsic indirectly to avoid registration which keeps an
|
| 1466 |
+
# internal reference inside the compiler
|
| 1467 |
+
original = _Intrinsic("foo", defn)
|
| 1468 |
+
self.assertIs(original._defn, defn)
|
| 1469 |
+
pickled = pickle.dumps(original)
|
| 1470 |
+
# by pickling, a new memo entry is created
|
| 1471 |
+
memo_size += 1
|
| 1472 |
+
self.assertEqual(memo_size, len(memo))
|
| 1473 |
+
del original # remove original before unpickling
|
| 1474 |
+
|
| 1475 |
+
# by deleting, the memo entry is NOT removed due to recent
|
| 1476 |
+
# function queue
|
| 1477 |
+
self.assertEqual(memo_size, len(memo))
|
| 1478 |
+
|
| 1479 |
+
# Manually force clear of _recent queue
|
| 1480 |
+
_Intrinsic._recent.clear()
|
| 1481 |
+
memo_size -= 1
|
| 1482 |
+
self.assertEqual(memo_size, len(memo))
|
| 1483 |
+
|
| 1484 |
+
rebuilt = pickle.loads(pickled)
|
| 1485 |
+
# verify that the rebuilt object is different
|
| 1486 |
+
self.assertIsNot(rebuilt._defn, defn)
|
| 1487 |
+
|
| 1488 |
+
# the second rebuilt object is the same as the first
|
| 1489 |
+
second = pickle.loads(pickled)
|
| 1490 |
+
self.assertIs(rebuilt._defn, second._defn)
|
| 1491 |
+
|
| 1492 |
+
def test_docstring(self):
|
| 1493 |
+
|
| 1494 |
+
@intrinsic
|
| 1495 |
+
def void_func(typingctx, a: int):
|
| 1496 |
+
"""void_func docstring"""
|
| 1497 |
+
sig = types.void(types.int32)
|
| 1498 |
+
|
| 1499 |
+
def codegen(context, builder, signature, args):
|
| 1500 |
+
pass # do nothing, return None, should be turned into
|
| 1501 |
+
# dummy value
|
| 1502 |
+
|
| 1503 |
+
return sig, codegen
|
| 1504 |
+
|
| 1505 |
+
self.assertEqual("numba.tests.test_extending", void_func.__module__)
|
| 1506 |
+
self.assertEqual("void_func", void_func.__name__)
|
| 1507 |
+
self.assertEqual("TestIntrinsic.test_docstring.<locals>.void_func",
|
| 1508 |
+
void_func.__qualname__)
|
| 1509 |
+
self.assertDictEqual({'a': int}, void_func.__annotations__)
|
| 1510 |
+
self.assertEqual("void_func docstring", void_func.__doc__)
|
| 1511 |
+
|
| 1512 |
+
|
| 1513 |
+
class TestRegisterJitable(unittest.TestCase):
|
| 1514 |
+
def test_no_flags(self):
|
| 1515 |
+
@register_jitable
|
| 1516 |
+
def foo(x, y):
|
| 1517 |
+
return x + y
|
| 1518 |
+
|
| 1519 |
+
def bar(x, y):
|
| 1520 |
+
return foo(x, y)
|
| 1521 |
+
|
| 1522 |
+
cbar = jit(nopython=True)(bar)
|
| 1523 |
+
|
| 1524 |
+
expect = bar(1, 2)
|
| 1525 |
+
got = cbar(1, 2)
|
| 1526 |
+
self.assertEqual(expect, got)
|
| 1527 |
+
|
| 1528 |
+
def test_flags_no_nrt(self):
|
| 1529 |
+
@register_jitable(_nrt=False)
|
| 1530 |
+
def foo(n):
|
| 1531 |
+
return np.arange(n)
|
| 1532 |
+
|
| 1533 |
+
def bar(n):
|
| 1534 |
+
return foo(n)
|
| 1535 |
+
|
| 1536 |
+
self.assertEqual(bar(3).tolist(), [0, 1, 2])
|
| 1537 |
+
|
| 1538 |
+
cbar = jit(nopython=True)(bar)
|
| 1539 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1540 |
+
cbar(2)
|
| 1541 |
+
msg = (
|
| 1542 |
+
"Only accept returning of array passed into the function as "
|
| 1543 |
+
"argument"
|
| 1544 |
+
)
|
| 1545 |
+
self.assertIn(msg, str(raises.exception))
|
| 1546 |
+
|
| 1547 |
+
|
| 1548 |
+
class TestImportCythonFunction(unittest.TestCase):
|
| 1549 |
+
@unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed")
|
| 1550 |
+
def test_getting_function(self):
|
| 1551 |
+
addr = get_cython_function_address(
|
| 1552 |
+
"scipy.special.cython_special", "j0"
|
| 1553 |
+
)
|
| 1554 |
+
functype = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double)
|
| 1555 |
+
_j0 = functype(addr)
|
| 1556 |
+
j0 = jit(nopython=True)(lambda x: _j0(x))
|
| 1557 |
+
self.assertEqual(j0(0), 1)
|
| 1558 |
+
|
| 1559 |
+
def test_missing_module(self):
|
| 1560 |
+
with self.assertRaises(ImportError) as raises:
|
| 1561 |
+
get_cython_function_address("fakemodule", "fakefunction")
|
| 1562 |
+
# The quotes are not there in Python 2
|
| 1563 |
+
msg = "No module named '?fakemodule'?"
|
| 1564 |
+
match = re.match(msg, str(raises.exception))
|
| 1565 |
+
self.assertIsNotNone(match)
|
| 1566 |
+
|
| 1567 |
+
@unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed")
|
| 1568 |
+
def test_missing_function(self):
|
| 1569 |
+
with self.assertRaises(ValueError) as raises:
|
| 1570 |
+
get_cython_function_address(
|
| 1571 |
+
"scipy.special.cython_special", "foo"
|
| 1572 |
+
)
|
| 1573 |
+
msg = (
|
| 1574 |
+
"No function 'foo' found in __pyx_capi__ of "
|
| 1575 |
+
"'scipy.special.cython_special'"
|
| 1576 |
+
)
|
| 1577 |
+
self.assertEqual(msg, str(raises.exception))
|
| 1578 |
+
|
| 1579 |
+
|
| 1580 |
+
@overload_method(
|
| 1581 |
+
MyDummyType, "method_jit_option_check_nrt", jit_options={"_nrt": True}
|
| 1582 |
+
)
|
| 1583 |
+
def ov_method_jit_option_check_nrt(obj):
|
| 1584 |
+
def imp(obj):
|
| 1585 |
+
return np.arange(10)
|
| 1586 |
+
|
| 1587 |
+
return imp
|
| 1588 |
+
|
| 1589 |
+
|
| 1590 |
+
@overload_method(
|
| 1591 |
+
MyDummyType, "method_jit_option_check_no_nrt", jit_options={"_nrt": False}
|
| 1592 |
+
)
|
| 1593 |
+
def ov_method_jit_option_check_no_nrt(obj):
|
| 1594 |
+
def imp(obj):
|
| 1595 |
+
return np.arange(10)
|
| 1596 |
+
|
| 1597 |
+
return imp
|
| 1598 |
+
|
| 1599 |
+
|
| 1600 |
+
@overload_attribute(
|
| 1601 |
+
MyDummyType, "attr_jit_option_check_nrt", jit_options={"_nrt": True}
|
| 1602 |
+
)
|
| 1603 |
+
def ov_attr_jit_option_check_nrt(obj):
|
| 1604 |
+
def imp(obj):
|
| 1605 |
+
return np.arange(10)
|
| 1606 |
+
|
| 1607 |
+
return imp
|
| 1608 |
+
|
| 1609 |
+
|
| 1610 |
+
@overload_attribute(
|
| 1611 |
+
MyDummyType, "attr_jit_option_check_no_nrt", jit_options={"_nrt": False}
|
| 1612 |
+
)
|
| 1613 |
+
def ov_attr_jit_option_check_no_nrt(obj):
|
| 1614 |
+
def imp(obj):
|
| 1615 |
+
return np.arange(10)
|
| 1616 |
+
|
| 1617 |
+
return imp
|
| 1618 |
+
|
| 1619 |
+
|
| 1620 |
+
class TestJitOptionsNoNRT(TestCase):
|
| 1621 |
+
# Test overload*(jit_options={...}) by turning off _nrt
|
| 1622 |
+
|
| 1623 |
+
def check_error_no_nrt(self, func, *args, **kwargs):
|
| 1624 |
+
# Check that the compilation fails with a complaint about dynamic array
|
| 1625 |
+
msg = (
|
| 1626 |
+
"Only accept returning of array passed into "
|
| 1627 |
+
"the function as argument"
|
| 1628 |
+
)
|
| 1629 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 1630 |
+
func(*args, **kwargs)
|
| 1631 |
+
self.assertIn(msg, str(raises.exception))
|
| 1632 |
+
|
| 1633 |
+
def no_nrt_overload_check(self, flag):
|
| 1634 |
+
def dummy():
|
| 1635 |
+
return np.arange(10)
|
| 1636 |
+
|
| 1637 |
+
@overload(dummy, jit_options={"_nrt": flag})
|
| 1638 |
+
def ov_dummy():
|
| 1639 |
+
def dummy():
|
| 1640 |
+
return np.arange(10)
|
| 1641 |
+
|
| 1642 |
+
return dummy
|
| 1643 |
+
|
| 1644 |
+
@njit
|
| 1645 |
+
def foo():
|
| 1646 |
+
return dummy()
|
| 1647 |
+
|
| 1648 |
+
if flag:
|
| 1649 |
+
self.assertPreciseEqual(foo(), np.arange(10))
|
| 1650 |
+
else:
|
| 1651 |
+
self.check_error_no_nrt(foo)
|
| 1652 |
+
|
| 1653 |
+
def test_overload_no_nrt(self):
|
| 1654 |
+
self.no_nrt_overload_check(True)
|
| 1655 |
+
self.no_nrt_overload_check(False)
|
| 1656 |
+
|
| 1657 |
+
def test_overload_method_no_nrt(self):
|
| 1658 |
+
@njit
|
| 1659 |
+
def udt(x):
|
| 1660 |
+
return x.method_jit_option_check_nrt()
|
| 1661 |
+
|
| 1662 |
+
self.assertPreciseEqual(udt(mydummy), np.arange(10))
|
| 1663 |
+
|
| 1664 |
+
@njit
|
| 1665 |
+
def udt(x):
|
| 1666 |
+
return x.method_jit_option_check_no_nrt()
|
| 1667 |
+
|
| 1668 |
+
self.check_error_no_nrt(udt, mydummy)
|
| 1669 |
+
|
| 1670 |
+
def test_overload_attribute_no_nrt(self):
|
| 1671 |
+
@njit
|
| 1672 |
+
def udt(x):
|
| 1673 |
+
return x.attr_jit_option_check_nrt
|
| 1674 |
+
|
| 1675 |
+
self.assertPreciseEqual(udt(mydummy), np.arange(10))
|
| 1676 |
+
|
| 1677 |
+
@njit
|
| 1678 |
+
def udt(x):
|
| 1679 |
+
return x.attr_jit_option_check_no_nrt
|
| 1680 |
+
|
| 1681 |
+
self.check_error_no_nrt(udt, mydummy)
|
| 1682 |
+
|
| 1683 |
+
|
| 1684 |
+
class TestBoxingCallingJIT(TestCase):
|
| 1685 |
+
def setUp(self):
|
| 1686 |
+
super().setUp()
|
| 1687 |
+
many = base_dummy_type_factory("mydummy2")
|
| 1688 |
+
self.DynTypeType, self.DynType, self.dyn_type_type = many
|
| 1689 |
+
self.dyn_type = self.DynType()
|
| 1690 |
+
|
| 1691 |
+
def test_unboxer_basic(self):
|
| 1692 |
+
# Implements an unboxer on DynType that calls an intrinsic into the
|
| 1693 |
+
# unboxer code.
|
| 1694 |
+
magic_token = 0xCAFE
|
| 1695 |
+
magic_offset = 123
|
| 1696 |
+
|
| 1697 |
+
@intrinsic
|
| 1698 |
+
def my_intrinsic(typingctx, val):
|
| 1699 |
+
# An intrinsic that returns `val + magic_offset`
|
| 1700 |
+
def impl(context, builder, sig, args):
|
| 1701 |
+
[val] = args
|
| 1702 |
+
return builder.add(val, val.type(magic_offset))
|
| 1703 |
+
|
| 1704 |
+
sig = signature(val, val)
|
| 1705 |
+
return sig, impl
|
| 1706 |
+
|
| 1707 |
+
@unbox(self.DynTypeType)
|
| 1708 |
+
def unboxer(typ, obj, c):
|
| 1709 |
+
# The unboxer that calls some jitcode
|
| 1710 |
+
def bridge(x):
|
| 1711 |
+
# proof that this is a jit'ed context by calling jit only
|
| 1712 |
+
# intrinsic
|
| 1713 |
+
return my_intrinsic(x)
|
| 1714 |
+
|
| 1715 |
+
args = [c.context.get_constant(types.intp, magic_token)]
|
| 1716 |
+
sig = signature(types.voidptr, types.intp)
|
| 1717 |
+
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
|
| 1718 |
+
return NativeValue(res, is_error=is_error)
|
| 1719 |
+
|
| 1720 |
+
@box(self.DynTypeType)
|
| 1721 |
+
def boxer(typ, val, c):
|
| 1722 |
+
# The boxer that returns an integer representation
|
| 1723 |
+
res = c.builder.ptrtoint(val, cgutils.intp_t)
|
| 1724 |
+
return c.pyapi.long_from_ssize_t(res)
|
| 1725 |
+
|
| 1726 |
+
@njit
|
| 1727 |
+
def passthru(x):
|
| 1728 |
+
return x
|
| 1729 |
+
|
| 1730 |
+
out = passthru(self.dyn_type)
|
| 1731 |
+
self.assertEqual(out, magic_token + magic_offset)
|
| 1732 |
+
|
| 1733 |
+
def test_unboxer_raise(self):
|
| 1734 |
+
# Testing exception raising in jitcode called from unboxing.
|
| 1735 |
+
@unbox(self.DynTypeType)
|
| 1736 |
+
def unboxer(typ, obj, c):
|
| 1737 |
+
# The unboxer that calls some jitcode
|
| 1738 |
+
def bridge(x):
|
| 1739 |
+
if x > 0:
|
| 1740 |
+
raise ValueError("cannot be x > 0")
|
| 1741 |
+
return x
|
| 1742 |
+
|
| 1743 |
+
args = [c.context.get_constant(types.intp, 1)]
|
| 1744 |
+
sig = signature(types.voidptr, types.intp)
|
| 1745 |
+
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
|
| 1746 |
+
return NativeValue(res, is_error=is_error)
|
| 1747 |
+
|
| 1748 |
+
@box(self.DynTypeType)
|
| 1749 |
+
def boxer(typ, val, c):
|
| 1750 |
+
# The boxer that returns an integer representation
|
| 1751 |
+
res = c.builder.ptrtoint(val, cgutils.intp_t)
|
| 1752 |
+
return c.pyapi.long_from_ssize_t(res)
|
| 1753 |
+
|
| 1754 |
+
@njit
|
| 1755 |
+
def passthru(x):
|
| 1756 |
+
return x
|
| 1757 |
+
|
| 1758 |
+
with self.assertRaises(ValueError) as raises:
|
| 1759 |
+
passthru(self.dyn_type)
|
| 1760 |
+
self.assertIn(
|
| 1761 |
+
"cannot be x > 0", str(raises.exception),
|
| 1762 |
+
)
|
| 1763 |
+
|
| 1764 |
+
def test_boxer(self):
|
| 1765 |
+
# Call jitcode inside the boxer
|
| 1766 |
+
magic_token = 0xCAFE
|
| 1767 |
+
magic_offset = 312
|
| 1768 |
+
|
| 1769 |
+
@intrinsic
|
| 1770 |
+
def my_intrinsic(typingctx, val):
|
| 1771 |
+
# An intrinsic that returns `val + magic_offset`
|
| 1772 |
+
def impl(context, builder, sig, args):
|
| 1773 |
+
[val] = args
|
| 1774 |
+
return builder.add(val, val.type(magic_offset))
|
| 1775 |
+
|
| 1776 |
+
sig = signature(val, val)
|
| 1777 |
+
return sig, impl
|
| 1778 |
+
|
| 1779 |
+
@unbox(self.DynTypeType)
|
| 1780 |
+
def unboxer(typ, obj, c):
|
| 1781 |
+
return NativeValue(c.context.get_dummy_value())
|
| 1782 |
+
|
| 1783 |
+
@box(self.DynTypeType)
|
| 1784 |
+
def boxer(typ, val, c):
|
| 1785 |
+
# Note: this doesn't do proper error handling
|
| 1786 |
+
def bridge(x):
|
| 1787 |
+
return my_intrinsic(x)
|
| 1788 |
+
|
| 1789 |
+
args = [c.context.get_constant(types.intp, magic_token)]
|
| 1790 |
+
sig = signature(types.intp, types.intp)
|
| 1791 |
+
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
|
| 1792 |
+
return c.pyapi.long_from_ssize_t(res)
|
| 1793 |
+
|
| 1794 |
+
@njit
|
| 1795 |
+
def passthru(x):
|
| 1796 |
+
return x
|
| 1797 |
+
|
| 1798 |
+
r = passthru(self.dyn_type)
|
| 1799 |
+
self.assertEqual(r, magic_token + magic_offset)
|
| 1800 |
+
|
| 1801 |
+
def test_boxer_raise(self):
|
| 1802 |
+
# Call jitcode inside the boxer
|
| 1803 |
+
@unbox(self.DynTypeType)
|
| 1804 |
+
def unboxer(typ, obj, c):
|
| 1805 |
+
return NativeValue(c.context.get_dummy_value())
|
| 1806 |
+
|
| 1807 |
+
@box(self.DynTypeType)
|
| 1808 |
+
def boxer(typ, val, c):
|
| 1809 |
+
def bridge(x):
|
| 1810 |
+
if x > 0:
|
| 1811 |
+
raise ValueError("cannot do x > 0")
|
| 1812 |
+
return x
|
| 1813 |
+
|
| 1814 |
+
args = [c.context.get_constant(types.intp, 1)]
|
| 1815 |
+
sig = signature(types.intp, types.intp)
|
| 1816 |
+
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
|
| 1817 |
+
# The error handling
|
| 1818 |
+
retval = cgutils.alloca_once(c.builder, c.pyapi.pyobj, zfill=True)
|
| 1819 |
+
with c.builder.if_then(c.builder.not_(is_error)):
|
| 1820 |
+
obj = c.pyapi.long_from_ssize_t(res)
|
| 1821 |
+
c.builder.store(obj, retval)
|
| 1822 |
+
return c.builder.load(retval)
|
| 1823 |
+
|
| 1824 |
+
@njit
|
| 1825 |
+
def passthru(x):
|
| 1826 |
+
return x
|
| 1827 |
+
|
| 1828 |
+
with self.assertRaises(ValueError) as raises:
|
| 1829 |
+
passthru(self.dyn_type)
|
| 1830 |
+
self.assertIn(
|
| 1831 |
+
"cannot do x > 0", str(raises.exception),
|
| 1832 |
+
)
|
| 1833 |
+
|
| 1834 |
+
|
| 1835 |
+
def with_objmode_cache_ov_example(x):
|
| 1836 |
+
# This is the function stub for overloading inside
|
| 1837 |
+
# TestCachingOverloadObjmode.test_caching_overload_objmode
|
| 1838 |
+
pass
|
| 1839 |
+
|
| 1840 |
+
|
| 1841 |
+
@skip_if_typeguard
|
| 1842 |
+
class TestCachingOverloadObjmode(TestCase):
|
| 1843 |
+
"""Test caching of the use of overload implementations that use
|
| 1844 |
+
`with objmode`
|
| 1845 |
+
"""
|
| 1846 |
+
_numba_parallel_test_ = False
|
| 1847 |
+
|
| 1848 |
+
def setUp(self):
|
| 1849 |
+
warnings.simplefilter("error", errors.NumbaWarning)
|
| 1850 |
+
|
| 1851 |
+
def tearDown(self):
|
| 1852 |
+
warnings.resetwarnings()
|
| 1853 |
+
|
| 1854 |
+
def test_caching_overload_objmode(self):
|
| 1855 |
+
cache_dir = temp_directory(self.__class__.__name__)
|
| 1856 |
+
with override_config("CACHE_DIR", cache_dir):
|
| 1857 |
+
|
| 1858 |
+
def realwork(x):
|
| 1859 |
+
# uses numpy code
|
| 1860 |
+
arr = np.arange(x) / x
|
| 1861 |
+
return np.linalg.norm(arr)
|
| 1862 |
+
|
| 1863 |
+
def python_code(x):
|
| 1864 |
+
# create indirections
|
| 1865 |
+
return realwork(x)
|
| 1866 |
+
|
| 1867 |
+
@overload(with_objmode_cache_ov_example)
|
| 1868 |
+
def _ov_with_objmode_cache_ov_example(x):
|
| 1869 |
+
def impl(x):
|
| 1870 |
+
with objmode(y="float64"):
|
| 1871 |
+
y = python_code(x)
|
| 1872 |
+
return y
|
| 1873 |
+
|
| 1874 |
+
return impl
|
| 1875 |
+
|
| 1876 |
+
@njit(cache=True)
|
| 1877 |
+
def testcase(x):
|
| 1878 |
+
return with_objmode_cache_ov_example(x)
|
| 1879 |
+
|
| 1880 |
+
expect = realwork(123)
|
| 1881 |
+
got = testcase(123)
|
| 1882 |
+
self.assertEqual(got, expect)
|
| 1883 |
+
|
| 1884 |
+
testcase_cached = njit(cache=True)(testcase.py_func)
|
| 1885 |
+
got = testcase_cached(123)
|
| 1886 |
+
self.assertEqual(got, expect)
|
| 1887 |
+
|
| 1888 |
+
@classmethod
|
| 1889 |
+
def check_objmode_cache_ndarray(cls):
|
| 1890 |
+
def do_this(a, b):
|
| 1891 |
+
return np.sum(a + b)
|
| 1892 |
+
|
| 1893 |
+
def do_something(a, b):
|
| 1894 |
+
return np.sum(a + b)
|
| 1895 |
+
|
| 1896 |
+
@overload(do_something)
|
| 1897 |
+
def overload_do_something(a, b):
|
| 1898 |
+
def _do_something_impl(a, b):
|
| 1899 |
+
with objmode(y='float64'):
|
| 1900 |
+
y = do_this(a, b)
|
| 1901 |
+
return y
|
| 1902 |
+
return _do_something_impl
|
| 1903 |
+
|
| 1904 |
+
@njit(cache=True)
|
| 1905 |
+
def test_caching():
|
| 1906 |
+
a = np.arange(20)
|
| 1907 |
+
b = np.arange(20)
|
| 1908 |
+
return do_something(a, b)
|
| 1909 |
+
|
| 1910 |
+
got = test_caching()
|
| 1911 |
+
expect = test_caching.py_func()
|
| 1912 |
+
|
| 1913 |
+
# Check result
|
| 1914 |
+
if got != expect:
|
| 1915 |
+
raise AssertionError("incorrect result")
|
| 1916 |
+
return test_caching
|
| 1917 |
+
|
| 1918 |
+
@classmethod
|
| 1919 |
+
def populate_objmode_cache_ndarray_check_cache(cls):
|
| 1920 |
+
cls.check_objmode_cache_ndarray()
|
| 1921 |
+
|
| 1922 |
+
@classmethod
|
| 1923 |
+
def check_objmode_cache_ndarray_check_cache(cls):
|
| 1924 |
+
disp = cls.check_objmode_cache_ndarray()
|
| 1925 |
+
if len(disp.stats.cache_misses) != 0:
|
| 1926 |
+
raise AssertionError('unexpected cache miss')
|
| 1927 |
+
if len(disp.stats.cache_hits) <= 0:
|
| 1928 |
+
raise AssertionError("unexpected missing cache hit")
|
| 1929 |
+
|
| 1930 |
+
def test_check_objmode_cache_ndarray(self):
|
| 1931 |
+
# See issue #6130.
|
| 1932 |
+
# Env is missing after cache load.
|
| 1933 |
+
cache_dir = temp_directory(self.__class__.__name__)
|
| 1934 |
+
with override_config("CACHE_DIR", cache_dir):
|
| 1935 |
+
# Run in new process to populate the cache
|
| 1936 |
+
run_in_new_process_in_cache_dir(
|
| 1937 |
+
self.populate_objmode_cache_ndarray_check_cache, cache_dir
|
| 1938 |
+
)
|
| 1939 |
+
# Run in new process to use the cache in a fresh process.
|
| 1940 |
+
res = run_in_new_process_in_cache_dir(
|
| 1941 |
+
self.check_objmode_cache_ndarray_check_cache, cache_dir
|
| 1942 |
+
)
|
| 1943 |
+
self.assertEqual(res['exitcode'], 0)
|
| 1944 |
+
|
| 1945 |
+
|
| 1946 |
+
class TestMisc(TestCase):
|
| 1947 |
+
def test_is_jitted(self):
|
| 1948 |
+
def foo(x):
|
| 1949 |
+
pass
|
| 1950 |
+
|
| 1951 |
+
self.assertFalse(is_jitted(foo))
|
| 1952 |
+
self.assertTrue(is_jitted(njit(foo)))
|
| 1953 |
+
self.assertFalse(is_jitted(vectorize(foo)))
|
| 1954 |
+
self.assertFalse(is_jitted(vectorize(parallel=True)(foo)))
|
| 1955 |
+
self.assertFalse(
|
| 1956 |
+
is_jitted(guvectorize("void(float64[:])", "(m)")(foo))
|
| 1957 |
+
)
|
| 1958 |
+
|
| 1959 |
+
def test_overload_arg_binding(self):
|
| 1960 |
+
# See issue #7982, checks that calling a function with named args works
|
| 1961 |
+
# correctly irrespective of the order in which the names are supplied.
|
| 1962 |
+
@njit
|
| 1963 |
+
def standard_order():
|
| 1964 |
+
return np.full(shape=123, fill_value=456).shape
|
| 1965 |
+
|
| 1966 |
+
@njit
|
| 1967 |
+
def reversed_order():
|
| 1968 |
+
return np.full(fill_value=456, shape=123).shape
|
| 1969 |
+
|
| 1970 |
+
self.assertPreciseEqual(standard_order(), standard_order.py_func())
|
| 1971 |
+
self.assertPreciseEqual(reversed_order(), reversed_order.py_func())
|
| 1972 |
+
|
| 1973 |
+
|
| 1974 |
+
class TestOverloadPreferLiteral(TestCase):
|
| 1975 |
+
def test_overload(self):
|
| 1976 |
+
def prefer_lit(x):
|
| 1977 |
+
pass
|
| 1978 |
+
|
| 1979 |
+
def non_lit(x):
|
| 1980 |
+
pass
|
| 1981 |
+
|
| 1982 |
+
def ov(x):
|
| 1983 |
+
if isinstance(x, types.IntegerLiteral):
|
| 1984 |
+
# With prefer_literal=False, this branch will not be reached.
|
| 1985 |
+
if x.literal_value == 1:
|
| 1986 |
+
def impl(x):
|
| 1987 |
+
return 0xcafe
|
| 1988 |
+
return impl
|
| 1989 |
+
else:
|
| 1990 |
+
raise errors.TypingError('literal value')
|
| 1991 |
+
else:
|
| 1992 |
+
def impl(x):
|
| 1993 |
+
return x * 100
|
| 1994 |
+
return impl
|
| 1995 |
+
|
| 1996 |
+
overload(prefer_lit, prefer_literal=True)(ov)
|
| 1997 |
+
overload(non_lit)(ov)
|
| 1998 |
+
|
| 1999 |
+
@njit
|
| 2000 |
+
def check_prefer_lit(x):
|
| 2001 |
+
return prefer_lit(1), prefer_lit(2), prefer_lit(x)
|
| 2002 |
+
|
| 2003 |
+
a, b, c = check_prefer_lit(3)
|
| 2004 |
+
self.assertEqual(a, 0xcafe)
|
| 2005 |
+
self.assertEqual(b, 200)
|
| 2006 |
+
self.assertEqual(c, 300)
|
| 2007 |
+
|
| 2008 |
+
@njit
|
| 2009 |
+
def check_non_lit(x):
|
| 2010 |
+
return non_lit(1), non_lit(2), non_lit(x)
|
| 2011 |
+
|
| 2012 |
+
a, b, c = check_non_lit(3)
|
| 2013 |
+
self.assertEqual(a, 100)
|
| 2014 |
+
self.assertEqual(b, 200)
|
| 2015 |
+
self.assertEqual(c, 300)
|
| 2016 |
+
|
| 2017 |
+
def test_overload_method(self):
|
| 2018 |
+
def ov(self, x):
|
| 2019 |
+
if isinstance(x, types.IntegerLiteral):
|
| 2020 |
+
# With prefer_literal=False, this branch will not be reached.
|
| 2021 |
+
if x.literal_value == 1:
|
| 2022 |
+
def impl(self, x):
|
| 2023 |
+
return 0xcafe
|
| 2024 |
+
return impl
|
| 2025 |
+
else:
|
| 2026 |
+
raise errors.TypingError('literal value')
|
| 2027 |
+
else:
|
| 2028 |
+
def impl(self, x):
|
| 2029 |
+
return x * 100
|
| 2030 |
+
return impl
|
| 2031 |
+
|
| 2032 |
+
overload_method(
|
| 2033 |
+
MyDummyType, "method_prefer_literal",
|
| 2034 |
+
prefer_literal=True,
|
| 2035 |
+
)(ov)
|
| 2036 |
+
|
| 2037 |
+
overload_method(
|
| 2038 |
+
MyDummyType, "method_non_literal",
|
| 2039 |
+
prefer_literal=False,
|
| 2040 |
+
)(ov)
|
| 2041 |
+
|
| 2042 |
+
@njit
|
| 2043 |
+
def check_prefer_lit(dummy, x):
|
| 2044 |
+
return (
|
| 2045 |
+
dummy.method_prefer_literal(1),
|
| 2046 |
+
dummy.method_prefer_literal(2),
|
| 2047 |
+
dummy.method_prefer_literal(x),
|
| 2048 |
+
)
|
| 2049 |
+
|
| 2050 |
+
a, b, c = check_prefer_lit(MyDummy(), 3)
|
| 2051 |
+
self.assertEqual(a, 0xcafe)
|
| 2052 |
+
self.assertEqual(b, 200)
|
| 2053 |
+
self.assertEqual(c, 300)
|
| 2054 |
+
|
| 2055 |
+
@njit
|
| 2056 |
+
def check_non_lit(dummy, x):
|
| 2057 |
+
return (
|
| 2058 |
+
dummy.method_non_literal(1),
|
| 2059 |
+
dummy.method_non_literal(2),
|
| 2060 |
+
dummy.method_non_literal(x),
|
| 2061 |
+
)
|
| 2062 |
+
|
| 2063 |
+
a, b, c = check_non_lit(MyDummy(), 3)
|
| 2064 |
+
self.assertEqual(a, 100)
|
| 2065 |
+
self.assertEqual(b, 200)
|
| 2066 |
+
self.assertEqual(c, 300)
|
| 2067 |
+
|
| 2068 |
+
|
| 2069 |
+
class TestIntrinsicPreferLiteral(TestCase):
|
| 2070 |
+
def test_intrinsic(self):
|
| 2071 |
+
def intrin(context, x):
|
| 2072 |
+
# This intrinsic will return 0xcafe if `x` is a literal `1`.
|
| 2073 |
+
sig = signature(types.intp, x)
|
| 2074 |
+
if isinstance(x, types.IntegerLiteral):
|
| 2075 |
+
# With prefer_literal=False, this branch will not be reached
|
| 2076 |
+
if x.literal_value == 1:
|
| 2077 |
+
def codegen(context, builder, signature, args):
|
| 2078 |
+
atype = signature.args[0]
|
| 2079 |
+
llrtype = context.get_value_type(atype)
|
| 2080 |
+
return ir.Constant(llrtype, 0xcafe)
|
| 2081 |
+
return sig, codegen
|
| 2082 |
+
else:
|
| 2083 |
+
raise errors.TypingError('literal value')
|
| 2084 |
+
else:
|
| 2085 |
+
def codegen(context, builder, signature, args):
|
| 2086 |
+
atype = signature.return_type
|
| 2087 |
+
llrtype = context.get_value_type(atype)
|
| 2088 |
+
int_100 = ir.Constant(llrtype, 100)
|
| 2089 |
+
return builder.mul(args[0], int_100)
|
| 2090 |
+
return sig, codegen
|
| 2091 |
+
|
| 2092 |
+
prefer_lit = intrinsic(prefer_literal=True)(intrin)
|
| 2093 |
+
non_lit = intrinsic(prefer_literal=False)(intrin)
|
| 2094 |
+
|
| 2095 |
+
@njit
|
| 2096 |
+
def check_prefer_lit(x):
|
| 2097 |
+
return prefer_lit(1), prefer_lit(2), prefer_lit(x)
|
| 2098 |
+
|
| 2099 |
+
a, b, c = check_prefer_lit(3)
|
| 2100 |
+
self.assertEqual(a, 0xcafe)
|
| 2101 |
+
self.assertEqual(b, 200)
|
| 2102 |
+
self.assertEqual(c, 300)
|
| 2103 |
+
|
| 2104 |
+
@njit
|
| 2105 |
+
def check_non_lit(x):
|
| 2106 |
+
return non_lit(1), non_lit(2), non_lit(x)
|
| 2107 |
+
|
| 2108 |
+
a, b, c = check_non_lit(3)
|
| 2109 |
+
self.assertEqual(a, 100)
|
| 2110 |
+
self.assertEqual(b, 200)
|
| 2111 |
+
self.assertEqual(c, 300)
|
| 2112 |
+
|
| 2113 |
+
|
| 2114 |
+
class TestNumbaInternalOverloads(TestCase):
|
| 2115 |
+
|
| 2116 |
+
def test_signatures_match_overloaded_api(self):
|
| 2117 |
+
# This is a "best-effort" test to try and ensure that Numba's internal
|
| 2118 |
+
# overload declarations have signatures with argument names that match
|
| 2119 |
+
# the API they are overloading. The purpose of ensuring there is a
|
| 2120 |
+
# match is so that users can use call-by-name for positional arguments.
|
| 2121 |
+
|
| 2122 |
+
# Set this to:
|
| 2123 |
+
# 0 to make violations raise a ValueError (default).
|
| 2124 |
+
# 1 to get violations reported to STDOUT
|
| 2125 |
+
# 2 to get a verbose output of everything that was checked and its state
|
| 2126 |
+
# reported to STDOUT.
|
| 2127 |
+
DEBUG = 0
|
| 2128 |
+
|
| 2129 |
+
# np.random.* does not have a signature exposed to `inspect`... so
|
| 2130 |
+
# custom parse the docstrings.
|
| 2131 |
+
def sig_from_np_random(x):
|
| 2132 |
+
if not x.startswith('_'):
|
| 2133 |
+
thing = getattr(np.random, x)
|
| 2134 |
+
if inspect.isbuiltin(thing):
|
| 2135 |
+
docstr = thing.__doc__.splitlines()
|
| 2136 |
+
for l in docstr:
|
| 2137 |
+
if l:
|
| 2138 |
+
sl = l.strip()
|
| 2139 |
+
if sl.startswith(x): # its the signature
|
| 2140 |
+
# special case np.random.seed, it has `self` in
|
| 2141 |
+
# the signature whereas all the other functions
|
| 2142 |
+
# do not!?
|
| 2143 |
+
if x == "seed":
|
| 2144 |
+
sl = "seed(seed)"
|
| 2145 |
+
|
| 2146 |
+
fake_impl = f"def {sl}:\n\tpass"
|
| 2147 |
+
l = {}
|
| 2148 |
+
try:
|
| 2149 |
+
exec(fake_impl, {}, l)
|
| 2150 |
+
except SyntaxError:
|
| 2151 |
+
# likely elipsis, e.g. rand(d0, d1, ..., dn)
|
| 2152 |
+
if DEBUG == 2:
|
| 2153 |
+
print("... skipped as cannot parse "
|
| 2154 |
+
"signature")
|
| 2155 |
+
return None
|
| 2156 |
+
else:
|
| 2157 |
+
fn = l.get(x)
|
| 2158 |
+
return inspect.signature(fn)
|
| 2159 |
+
|
| 2160 |
+
def checker(func, overload_func):
|
| 2161 |
+
if DEBUG == 2:
|
| 2162 |
+
print(f"Checking: {func}")
|
| 2163 |
+
|
| 2164 |
+
def create_message(func, overload_func, func_sig, ol_sig):
|
| 2165 |
+
msg = []
|
| 2166 |
+
s = (f"{func} from module '{getattr(func, '__module__')}' "
|
| 2167 |
+
"has mismatched sig.")
|
| 2168 |
+
msg.append(s)
|
| 2169 |
+
msg.append(f" - expected: {func_sig}")
|
| 2170 |
+
msg.append(f" - got: {ol_sig}")
|
| 2171 |
+
lineno = inspect.getsourcelines(overload_func)[1]
|
| 2172 |
+
tmpsrcfile = inspect.getfile(overload_func)
|
| 2173 |
+
srcfile = tmpsrcfile.replace(numba.__path__[0], '')
|
| 2174 |
+
msg.append(f"from {srcfile}:{lineno}")
|
| 2175 |
+
msgstr = '\n' + '\n'.join(msg)
|
| 2176 |
+
return msgstr
|
| 2177 |
+
|
| 2178 |
+
func_sig = None
|
| 2179 |
+
try:
|
| 2180 |
+
func_sig = inspect.signature(func)
|
| 2181 |
+
except ValueError:
|
| 2182 |
+
# probably a built-in/C code, see if it's a np.random function
|
| 2183 |
+
if fname := getattr(func, '__name__', False):
|
| 2184 |
+
if maybe_func := getattr(np.random, fname, False):
|
| 2185 |
+
if maybe_func == func:
|
| 2186 |
+
# it's a built-in from np.random
|
| 2187 |
+
func_sig = sig_from_np_random(fname)
|
| 2188 |
+
|
| 2189 |
+
if func_sig is not None:
|
| 2190 |
+
ol_sig = inspect.signature(overload_func)
|
| 2191 |
+
x = list(func_sig.parameters.keys())
|
| 2192 |
+
y = list(ol_sig.parameters.keys())
|
| 2193 |
+
for a, b in zip(x[:len(y)], y):
|
| 2194 |
+
if a != b:
|
| 2195 |
+
p = func_sig.parameters[a]
|
| 2196 |
+
if p.kind == p.POSITIONAL_ONLY:
|
| 2197 |
+
# probably a built-in/C code
|
| 2198 |
+
if DEBUG == 2:
|
| 2199 |
+
print("... skipped as positional only "
|
| 2200 |
+
"arguments found")
|
| 2201 |
+
break
|
| 2202 |
+
elif '*' in str(p): # probably *args or similar
|
| 2203 |
+
if DEBUG == 2:
|
| 2204 |
+
print("... skipped as contains *args")
|
| 2205 |
+
break
|
| 2206 |
+
else:
|
| 2207 |
+
# Only error/report on functions that have a module
|
| 2208 |
+
# or are from somewhere other than Numba.
|
| 2209 |
+
if (not func.__module__ or
|
| 2210 |
+
not func.__module__.startswith("numba")):
|
| 2211 |
+
msgstr = create_message(func, overload_func,
|
| 2212 |
+
func_sig, ol_sig)
|
| 2213 |
+
if DEBUG != 0:
|
| 2214 |
+
if DEBUG == 2:
|
| 2215 |
+
print("... INVALID")
|
| 2216 |
+
if msgstr:
|
| 2217 |
+
print(msgstr)
|
| 2218 |
+
break
|
| 2219 |
+
else:
|
| 2220 |
+
raise ValueError(msgstr)
|
| 2221 |
+
else:
|
| 2222 |
+
if DEBUG == 2:
|
| 2223 |
+
if not func.__module__:
|
| 2224 |
+
print("... skipped as no __module__ "
|
| 2225 |
+
"present")
|
| 2226 |
+
else:
|
| 2227 |
+
print("... skipped as Numba internal")
|
| 2228 |
+
break
|
| 2229 |
+
else:
|
| 2230 |
+
if DEBUG == 2:
|
| 2231 |
+
print("... OK")
|
| 2232 |
+
|
| 2233 |
+
# Compile something to make sure that the typing context registries
|
| 2234 |
+
# are populated with everything from the CPU target.
|
| 2235 |
+
njit(lambda : None).compile(())
|
| 2236 |
+
tyctx = numba.core.typing.context.Context()
|
| 2237 |
+
tyctx.refresh()
|
| 2238 |
+
|
| 2239 |
+
# Walk the registries and check each function that is an overload
|
| 2240 |
+
regs = tyctx._registries
|
| 2241 |
+
for k, v in regs.items():
|
| 2242 |
+
for item in k.functions:
|
| 2243 |
+
if getattr(item, '_overload_func', False):
|
| 2244 |
+
checker(item.key, item._overload_func)
|
| 2245 |
+
|
| 2246 |
+
|
| 2247 |
+
if __name__ == "__main__":
|
| 2248 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_extending_types.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test extending types via the numba.extending.* API.
|
| 3 |
+
"""
|
| 4 |
+
import operator
|
| 5 |
+
|
| 6 |
+
from numba import njit, literally
|
| 7 |
+
from numba.core import types, cgutils
|
| 8 |
+
from numba.core.errors import TypingError, NumbaTypeError
|
| 9 |
+
from numba.core.extending import lower_builtin
|
| 10 |
+
from numba.core.extending import models, register_model
|
| 11 |
+
from numba.core.extending import make_attribute_wrapper
|
| 12 |
+
from numba.core.extending import type_callable
|
| 13 |
+
from numba.core.extending import overload
|
| 14 |
+
from numba.core.extending import typeof_impl
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def gen_mock_float():
|
| 20 |
+
# Stub to overload, pretending to be `float`. The real `float` function is
|
| 21 |
+
# not used as multiple registrations can collide.
|
| 22 |
+
def mock_float(x):
|
| 23 |
+
pass
|
| 24 |
+
return mock_float
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TestExtTypDummy(unittest.TestCase):
|
| 28 |
+
|
| 29 |
+
def setUp(self):
|
| 30 |
+
class Dummy(object):
|
| 31 |
+
def __init__(self, value):
|
| 32 |
+
self.value = value
|
| 33 |
+
|
| 34 |
+
class DummyType(types.Type):
|
| 35 |
+
def __init__(self):
|
| 36 |
+
super(DummyType, self).__init__(name='Dummy')
|
| 37 |
+
|
| 38 |
+
dummy_type = DummyType()
|
| 39 |
+
|
| 40 |
+
@register_model(DummyType)
|
| 41 |
+
class DummyModel(models.StructModel):
|
| 42 |
+
def __init__(self, dmm, fe_type):
|
| 43 |
+
members = [
|
| 44 |
+
('value', types.intp),
|
| 45 |
+
]
|
| 46 |
+
models.StructModel.__init__(self, dmm, fe_type, members)
|
| 47 |
+
|
| 48 |
+
make_attribute_wrapper(DummyType, 'value', 'value')
|
| 49 |
+
|
| 50 |
+
@type_callable(Dummy)
|
| 51 |
+
def type_dummy(context):
|
| 52 |
+
def typer(value):
|
| 53 |
+
return dummy_type
|
| 54 |
+
return typer
|
| 55 |
+
|
| 56 |
+
@lower_builtin(Dummy, types.intp)
|
| 57 |
+
def impl_dummy(context, builder, sig, args):
|
| 58 |
+
typ = sig.return_type
|
| 59 |
+
[value] = args
|
| 60 |
+
dummy = cgutils.create_struct_proxy(typ)(context, builder)
|
| 61 |
+
dummy.value = value
|
| 62 |
+
return dummy._getvalue()
|
| 63 |
+
|
| 64 |
+
@typeof_impl.register(Dummy)
|
| 65 |
+
def typeof_dummy(val, c):
|
| 66 |
+
return DummyType()
|
| 67 |
+
|
| 68 |
+
# Store attributes
|
| 69 |
+
self.Dummy = Dummy
|
| 70 |
+
self.DummyType = DummyType
|
| 71 |
+
|
| 72 |
+
def _add_float_overload(self, mock_float_inst):
|
| 73 |
+
@overload(mock_float_inst)
|
| 74 |
+
def dummy_to_float(x):
|
| 75 |
+
if isinstance(x, self.DummyType):
|
| 76 |
+
def codegen(x):
|
| 77 |
+
return float(x.value)
|
| 78 |
+
return codegen
|
| 79 |
+
else:
|
| 80 |
+
raise NumbaTypeError('cannot type float({})'.format(x))
|
| 81 |
+
|
| 82 |
+
def test_overload_float(self):
|
| 83 |
+
mock_float = gen_mock_float()
|
| 84 |
+
self._add_float_overload(mock_float)
|
| 85 |
+
Dummy = self.Dummy
|
| 86 |
+
|
| 87 |
+
@njit
|
| 88 |
+
def foo(x):
|
| 89 |
+
return mock_float(Dummy(x))
|
| 90 |
+
|
| 91 |
+
self.assertEqual(foo(123), float(123))
|
| 92 |
+
|
| 93 |
+
def test_overload_float_error_msg(self):
|
| 94 |
+
mock_float = gen_mock_float()
|
| 95 |
+
self._add_float_overload(mock_float)
|
| 96 |
+
|
| 97 |
+
@njit
|
| 98 |
+
def foo(x):
|
| 99 |
+
return mock_float(x)
|
| 100 |
+
|
| 101 |
+
with self.assertRaises(TypingError) as raises:
|
| 102 |
+
foo(1j)
|
| 103 |
+
|
| 104 |
+
self.assertIn("cannot type float(complex128)",
|
| 105 |
+
str(raises.exception))
|
| 106 |
+
|
| 107 |
+
def test_unboxing(self):
|
| 108 |
+
"""A test for the unboxing logic on unknown type
|
| 109 |
+
"""
|
| 110 |
+
Dummy = self.Dummy
|
| 111 |
+
|
| 112 |
+
@njit
|
| 113 |
+
def foo(x):
|
| 114 |
+
# pass a dummy object into another function
|
| 115 |
+
bar(Dummy(x))
|
| 116 |
+
|
| 117 |
+
# make sure a cpython wrapper is created
|
| 118 |
+
@njit(no_cpython_wrapper=False)
|
| 119 |
+
def bar(dummy_obj):
|
| 120 |
+
pass
|
| 121 |
+
|
| 122 |
+
foo(123)
|
| 123 |
+
with self.assertRaises(TypeError) as raises:
|
| 124 |
+
bar(Dummy(123))
|
| 125 |
+
self.assertIn("can't unbox Dummy type", str(raises.exception))
|
| 126 |
+
|
| 127 |
+
def test_boxing(self):
|
| 128 |
+
"""A test for the boxing logic on unknown type
|
| 129 |
+
"""
|
| 130 |
+
Dummy = self.Dummy
|
| 131 |
+
|
| 132 |
+
@njit
|
| 133 |
+
def foo(x):
|
| 134 |
+
return Dummy(x)
|
| 135 |
+
|
| 136 |
+
with self.assertRaises(TypeError) as raises:
|
| 137 |
+
foo(123)
|
| 138 |
+
self.assertIn("cannot convert native Dummy to Python object",
|
| 139 |
+
str(raises.exception))
|
| 140 |
+
|
| 141 |
+
def test_issue5565_literal_getitem(self):
|
| 142 |
+
# the following test is adapted from
|
| 143 |
+
# https://github.com/numba/numba/issues/5565
|
| 144 |
+
Dummy, DummyType = self.Dummy, self.DummyType
|
| 145 |
+
|
| 146 |
+
MAGIC_NUMBER = 12321
|
| 147 |
+
|
| 148 |
+
@overload(operator.getitem)
|
| 149 |
+
def dummy_getitem_ovld(self, idx):
|
| 150 |
+
if not isinstance(self, DummyType):
|
| 151 |
+
return None
|
| 152 |
+
# suppose we can only support idx as literal argument
|
| 153 |
+
if isinstance(idx, types.StringLiteral):
|
| 154 |
+
def dummy_getitem_impl(self, idx):
|
| 155 |
+
return MAGIC_NUMBER
|
| 156 |
+
return dummy_getitem_impl
|
| 157 |
+
|
| 158 |
+
if isinstance(idx, types.UnicodeType):
|
| 159 |
+
def dummy_getitem_impl(self, idx):
|
| 160 |
+
return literally(idx)
|
| 161 |
+
return dummy_getitem_impl
|
| 162 |
+
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
@njit
|
| 166 |
+
def test_impl(x, y):
|
| 167 |
+
return Dummy(x)[y]
|
| 168 |
+
|
| 169 |
+
var = 'abc'
|
| 170 |
+
self.assertEqual(test_impl(1, var), MAGIC_NUMBER)
|
lib/python3.10/site-packages/numba/tests/test_findlib.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numba.tests.support import TestCase, unittest
|
| 2 |
+
from numba.misc import findlib
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestFindlib(TestCase):
|
| 6 |
+
def test_find_file_nonexistent_path(self):
|
| 7 |
+
candidates = findlib.find_file('libirrelevant.so', 'NONEXISTENT')
|
| 8 |
+
self.assertEqual(candidates, [])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if __name__ == '__main__':
|
| 12 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_firstlinefinder.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
import inspect
|
| 3 |
+
|
| 4 |
+
from numba import njit
|
| 5 |
+
from numba.tests.support import TestCase
|
| 6 |
+
from numba.misc.firstlinefinder import get_func_body_first_lineno
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestFirstLineFinder(TestCase):
|
| 10 |
+
"""
|
| 11 |
+
The following methods contains tests that are sensitive to the source
|
| 12 |
+
locations w.r.t. the beginning of each method.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def _get_grandparent_caller_code(self):
|
| 16 |
+
frame = inspect.currentframe()
|
| 17 |
+
caller_frame = inspect.getouterframes(frame)
|
| 18 |
+
return caller_frame[2].frame.f_code
|
| 19 |
+
|
| 20 |
+
def assert_line_location(self, expected, offset_from_caller):
|
| 21 |
+
grandparent_co = self._get_grandparent_caller_code()
|
| 22 |
+
lno = grandparent_co.co_firstlineno
|
| 23 |
+
self.assertEqual(expected, lno + offset_from_caller)
|
| 24 |
+
|
| 25 |
+
def test_decorated_odd_comment_indent(self):
|
| 26 |
+
@njit
|
| 27 |
+
def foo():
|
| 28 |
+
# NOTE: THIS COMMENT MUST START AT COLUMN 0 FOR THIS SAMPLE CODE TO BE VALID # noqa: E115, E501
|
| 29 |
+
return 1
|
| 30 |
+
|
| 31 |
+
first_def_line = get_func_body_first_lineno(foo)
|
| 32 |
+
self.assert_line_location(first_def_line, 4)
|
| 33 |
+
|
| 34 |
+
def test_undecorated_odd_comment_indent(self):
|
| 35 |
+
def foo():
|
| 36 |
+
# NOTE: THIS COMMENT MUST START AT COLUMN 0 FOR THIS SAMPLE CODE TO BE VALID # noqa: E115, E501
|
| 37 |
+
return 1
|
| 38 |
+
|
| 39 |
+
first_def_line = get_func_body_first_lineno(njit(foo))
|
| 40 |
+
self.assert_line_location(first_def_line, 3)
|
| 41 |
+
|
| 42 |
+
def test_unnamed_lambda(self):
|
| 43 |
+
foo = lambda: 1
|
| 44 |
+
first_def_line = get_func_body_first_lineno(njit(foo))
|
| 45 |
+
# Cannot determine first line of lambda function
|
| 46 |
+
self.assertIsNone(first_def_line)
|
| 47 |
+
|
| 48 |
+
def test_nested_function(self):
|
| 49 |
+
def foo():
|
| 50 |
+
@njit
|
| 51 |
+
def foo():
|
| 52 |
+
# This function is intentionally named the same as the parent
|
| 53 |
+
return 1
|
| 54 |
+
|
| 55 |
+
return foo
|
| 56 |
+
|
| 57 |
+
inner = foo()
|
| 58 |
+
first_def_line = get_func_body_first_lineno(inner)
|
| 59 |
+
self.assert_line_location(first_def_line, 5)
|
| 60 |
+
|
| 61 |
+
def test_pass_statement(self):
|
| 62 |
+
@njit
|
| 63 |
+
def foo():
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
first_def_line = get_func_body_first_lineno(foo)
|
| 67 |
+
self.assert_line_location(first_def_line, 3)
|
| 68 |
+
|
| 69 |
+
def test_string_eval(self):
|
| 70 |
+
source = """def foo():
|
| 71 |
+
pass
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
globalns = {}
|
| 75 |
+
exec(source, globalns)
|
| 76 |
+
foo = globalns['foo']
|
| 77 |
+
|
| 78 |
+
first_def_line = get_func_body_first_lineno(foo)
|
| 79 |
+
# Cannot determine first line of string evaled functions
|
| 80 |
+
self.assertIsNone(first_def_line)
|
| 81 |
+
|
| 82 |
+
def test_single_line_function(self):
|
| 83 |
+
@njit
|
| 84 |
+
def foo(): pass # noqa: E704
|
| 85 |
+
|
| 86 |
+
first_def_line = get_func_body_first_lineno(foo)
|
| 87 |
+
self.assert_line_location(first_def_line, 2)
|
| 88 |
+
|
| 89 |
+
def test_docstring(self):
|
| 90 |
+
@njit
|
| 91 |
+
def foo():
|
| 92 |
+
"""Docstring
|
| 93 |
+
"""
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
first_def_line = get_func_body_first_lineno(foo)
|
| 97 |
+
self.assert_line_location(first_def_line, 5)
|
| 98 |
+
|
| 99 |
+
def test_docstring_2(self):
|
| 100 |
+
@njit
|
| 101 |
+
def foo():
|
| 102 |
+
"""Docstring
|
| 103 |
+
"""
|
| 104 |
+
"""Not Docstring, but a bare string literal
|
| 105 |
+
"""
|
| 106 |
+
pass
|
| 107 |
+
# Variation on test_docstring but with a "fake" docstring following
|
| 108 |
+
# the true docstring.
|
| 109 |
+
first_def_line = get_func_body_first_lineno(foo)
|
| 110 |
+
self.assert_line_location(first_def_line, 5)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_flow_control.py
ADDED
|
@@ -0,0 +1,1280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from numba import jit
|
| 5 |
+
from numba.core.controlflow import CFGraph, ControlFlowAnalysis
|
| 6 |
+
from numba.core import types
|
| 7 |
+
from numba.core.bytecode import FunctionIdentity, ByteCode, _fix_LOAD_GLOBAL_arg
|
| 8 |
+
from numba.tests.support import TestCase
|
| 9 |
+
|
| 10 |
+
enable_pyobj_flags = {}
|
| 11 |
+
|
| 12 |
+
no_pyobj_flags = {'_nrt': True, 'nopython': True}
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def for_loop_usecase1(x, y):
|
| 16 |
+
result = 0
|
| 17 |
+
for i in range(x):
|
| 18 |
+
result += i
|
| 19 |
+
return result
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def for_loop_usecase2(x, y):
|
| 23 |
+
result = 0
|
| 24 |
+
for i, j in enumerate(range(x, y, -1)):
|
| 25 |
+
result += i * j
|
| 26 |
+
return result
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def for_loop_usecase3(x, y):
|
| 30 |
+
result = 0
|
| 31 |
+
lst = [x, y]
|
| 32 |
+
for i in lst:
|
| 33 |
+
result += i
|
| 34 |
+
return result
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def for_loop_usecase4(x, y):
|
| 38 |
+
result = 0
|
| 39 |
+
for i in range(10):
|
| 40 |
+
for j in range(10):
|
| 41 |
+
result += 1
|
| 42 |
+
return result
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def for_loop_usecase5(x, y):
|
| 46 |
+
result = 0
|
| 47 |
+
for i in range(x):
|
| 48 |
+
result += 1
|
| 49 |
+
if result > y:
|
| 50 |
+
break
|
| 51 |
+
return result
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def for_loop_usecase6(x, y):
|
| 55 |
+
result = 0
|
| 56 |
+
for i in range(x):
|
| 57 |
+
if i > y:
|
| 58 |
+
continue
|
| 59 |
+
result += 1
|
| 60 |
+
return result
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def for_loop_usecase7(x, y):
|
| 64 |
+
for i in range(x):
|
| 65 |
+
x = 0
|
| 66 |
+
for j in range(x):
|
| 67 |
+
return 1
|
| 68 |
+
else:
|
| 69 |
+
pass
|
| 70 |
+
return 0
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def for_loop_usecase8(x, y):
|
| 74 |
+
result = 0
|
| 75 |
+
for i in range(x, y, y - x + 1):
|
| 76 |
+
result += 1
|
| 77 |
+
return result
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def for_loop_usecase9(x, y):
|
| 81 |
+
z = 0
|
| 82 |
+
for i in range(x):
|
| 83 |
+
x = 0
|
| 84 |
+
for j in range(x):
|
| 85 |
+
if j == x / 2:
|
| 86 |
+
z += j
|
| 87 |
+
break
|
| 88 |
+
else:
|
| 89 |
+
z += y
|
| 90 |
+
|
| 91 |
+
return z
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def for_loop_usecase10(x, y):
|
| 95 |
+
for i in range(x):
|
| 96 |
+
if i == y:
|
| 97 |
+
z = y
|
| 98 |
+
break
|
| 99 |
+
else:
|
| 100 |
+
z = i * 2
|
| 101 |
+
return z
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def while_loop_usecase1(x, y):
|
| 105 |
+
result = 0
|
| 106 |
+
i = 0
|
| 107 |
+
while i < x:
|
| 108 |
+
result += i
|
| 109 |
+
i += 1
|
| 110 |
+
return result
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def while_loop_usecase2(x, y):
|
| 114 |
+
result = 0
|
| 115 |
+
while result != x:
|
| 116 |
+
result += 1
|
| 117 |
+
return result
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def while_loop_usecase3(x, y):
|
| 121 |
+
result = 0
|
| 122 |
+
i = 0
|
| 123 |
+
j = 0
|
| 124 |
+
while i < x:
|
| 125 |
+
while j < y:
|
| 126 |
+
result += i + j
|
| 127 |
+
i += 1
|
| 128 |
+
j += 1
|
| 129 |
+
return result
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def while_loop_usecase4(x, y):
|
| 133 |
+
result = 0
|
| 134 |
+
while True:
|
| 135 |
+
result += 1
|
| 136 |
+
if result > x:
|
| 137 |
+
break
|
| 138 |
+
return result
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def while_loop_usecase5(x, y):
|
| 142 |
+
result = 0
|
| 143 |
+
while result < x:
|
| 144 |
+
if result > y:
|
| 145 |
+
result += 2
|
| 146 |
+
continue
|
| 147 |
+
result += 1
|
| 148 |
+
return result
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def ifelse_usecase1(x, y):
|
| 152 |
+
if x > 0:
|
| 153 |
+
pass
|
| 154 |
+
elif y > 0:
|
| 155 |
+
pass
|
| 156 |
+
else:
|
| 157 |
+
pass
|
| 158 |
+
return True
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def ifelse_usecase2(x, y):
|
| 162 |
+
if x > y:
|
| 163 |
+
return 1
|
| 164 |
+
elif x == 0 or y == 0:
|
| 165 |
+
return 2
|
| 166 |
+
else:
|
| 167 |
+
return 3
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def ifelse_usecase3(x, y):
|
| 171 |
+
if x > 0:
|
| 172 |
+
if y > 0:
|
| 173 |
+
return 1
|
| 174 |
+
elif y < 0:
|
| 175 |
+
return 1
|
| 176 |
+
else:
|
| 177 |
+
return 0
|
| 178 |
+
elif x < 0:
|
| 179 |
+
return 1
|
| 180 |
+
else:
|
| 181 |
+
return 0
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def ifelse_usecase4(x, y):
|
| 185 |
+
if x == y:
|
| 186 |
+
return 1
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def ternary_ifelse_usecase1(x, y):
|
| 190 |
+
return True if x > y else False
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def double_infinite_loop(x, y):
|
| 194 |
+
L = x
|
| 195 |
+
i = y
|
| 196 |
+
|
| 197 |
+
while True:
|
| 198 |
+
while True:
|
| 199 |
+
if i == L - 1:
|
| 200 |
+
break
|
| 201 |
+
i += 1
|
| 202 |
+
i += 1
|
| 203 |
+
if i >= L:
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
return i, L
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def try_except_usecase():
|
| 210 |
+
try:
|
| 211 |
+
pass
|
| 212 |
+
except Exception:
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class TestFlowControl(TestCase):
|
| 217 |
+
|
| 218 |
+
def run_test(self, pyfunc, x_operands, y_operands,
|
| 219 |
+
flags=enable_pyobj_flags):
|
| 220 |
+
cfunc = jit((types.intp, types.intp), **flags)(pyfunc)
|
| 221 |
+
for x, y in itertools.product(x_operands, y_operands):
|
| 222 |
+
pyerr = None
|
| 223 |
+
cerr = None
|
| 224 |
+
try:
|
| 225 |
+
pyres = pyfunc(x, y)
|
| 226 |
+
except Exception as e:
|
| 227 |
+
pyerr = e
|
| 228 |
+
|
| 229 |
+
try:
|
| 230 |
+
cres = cfunc(x, y)
|
| 231 |
+
except Exception as e:
|
| 232 |
+
if pyerr is None:
|
| 233 |
+
raise
|
| 234 |
+
cerr = e
|
| 235 |
+
self.assertEqual(type(pyerr), type(cerr))
|
| 236 |
+
else:
|
| 237 |
+
if pyerr is not None:
|
| 238 |
+
self.fail("Invalid for pure-python but numba works\n" +
|
| 239 |
+
pyerr)
|
| 240 |
+
self.assertEqual(pyres, cres)
|
| 241 |
+
|
| 242 |
+
def test_for_loop1(self, flags=enable_pyobj_flags):
|
| 243 |
+
self.run_test(for_loop_usecase1, [-10, 0, 10], [0], flags=flags)
|
| 244 |
+
|
| 245 |
+
def test_for_loop1_npm(self):
|
| 246 |
+
self.test_for_loop1(flags=no_pyobj_flags)
|
| 247 |
+
|
| 248 |
+
def test_for_loop2(self, flags=enable_pyobj_flags):
|
| 249 |
+
self.run_test(for_loop_usecase2, [-10, 0, 10], [-10, 0, 10],
|
| 250 |
+
flags=flags)
|
| 251 |
+
|
| 252 |
+
def test_for_loop2_npm(self):
|
| 253 |
+
self.test_for_loop2(flags=no_pyobj_flags)
|
| 254 |
+
|
| 255 |
+
def test_for_loop3(self, flags=enable_pyobj_flags):
|
| 256 |
+
"""
|
| 257 |
+
List requires pyobject
|
| 258 |
+
"""
|
| 259 |
+
self.run_test(for_loop_usecase3, [1], [2],
|
| 260 |
+
flags=flags)
|
| 261 |
+
|
| 262 |
+
def test_for_loop3_npm(self):
|
| 263 |
+
self.test_for_loop3(flags=no_pyobj_flags)
|
| 264 |
+
|
| 265 |
+
def test_for_loop4(self, flags=enable_pyobj_flags):
|
| 266 |
+
self.run_test(for_loop_usecase4, [10], [10], flags=flags)
|
| 267 |
+
|
| 268 |
+
def test_for_loop4_npm(self):
|
| 269 |
+
self.test_for_loop4(flags=no_pyobj_flags)
|
| 270 |
+
|
| 271 |
+
def test_for_loop5(self, flags=enable_pyobj_flags):
|
| 272 |
+
self.run_test(for_loop_usecase5, [100], [50], flags=flags)
|
| 273 |
+
|
| 274 |
+
def test_for_loop5_npm(self):
|
| 275 |
+
self.test_for_loop5(flags=no_pyobj_flags)
|
| 276 |
+
|
| 277 |
+
def test_for_loop6(self, flags=enable_pyobj_flags):
|
| 278 |
+
self.run_test(for_loop_usecase6, [100], [50], flags=flags)
|
| 279 |
+
|
| 280 |
+
def test_for_loop6_npm(self):
|
| 281 |
+
self.test_for_loop6(flags=no_pyobj_flags)
|
| 282 |
+
|
| 283 |
+
def test_for_loop7(self, flags=enable_pyobj_flags):
|
| 284 |
+
self.run_test(for_loop_usecase7, [5], [0], flags=flags)
|
| 285 |
+
|
| 286 |
+
def test_for_loop7_npm(self):
|
| 287 |
+
self.test_for_loop7(flags=no_pyobj_flags)
|
| 288 |
+
|
| 289 |
+
def test_for_loop8(self, flags=enable_pyobj_flags):
|
| 290 |
+
self.run_test(for_loop_usecase8, [0, 1], [0, 2, 10], flags=flags)
|
| 291 |
+
|
| 292 |
+
def test_for_loop8_npm(self):
|
| 293 |
+
self.test_for_loop8(flags=no_pyobj_flags)
|
| 294 |
+
|
| 295 |
+
def test_for_loop9(self, flags=enable_pyobj_flags):
|
| 296 |
+
self.run_test(for_loop_usecase9, [0, 1], [0, 2, 10], flags=flags)
|
| 297 |
+
|
| 298 |
+
def test_for_loop9_npm(self):
|
| 299 |
+
self.test_for_loop9(flags=no_pyobj_flags)
|
| 300 |
+
|
| 301 |
+
def test_for_loop10(self, flags=enable_pyobj_flags):
|
| 302 |
+
self.run_test(for_loop_usecase10, [5], [2, 7], flags=flags)
|
| 303 |
+
|
| 304 |
+
def test_for_loop10_npm(self):
|
| 305 |
+
self.test_for_loop10(flags=no_pyobj_flags)
|
| 306 |
+
|
| 307 |
+
def test_while_loop1(self, flags=enable_pyobj_flags):
|
| 308 |
+
self.run_test(while_loop_usecase1, [10], [0], flags=flags)
|
| 309 |
+
|
| 310 |
+
def test_while_loop1_npm(self):
|
| 311 |
+
self.test_while_loop1(flags=no_pyobj_flags)
|
| 312 |
+
|
| 313 |
+
def test_while_loop2(self, flags=enable_pyobj_flags):
|
| 314 |
+
self.run_test(while_loop_usecase2, [10], [0], flags=flags)
|
| 315 |
+
|
| 316 |
+
def test_while_loop2_npm(self):
|
| 317 |
+
self.test_while_loop2(flags=no_pyobj_flags)
|
| 318 |
+
|
| 319 |
+
def test_while_loop3(self, flags=enable_pyobj_flags):
|
| 320 |
+
self.run_test(while_loop_usecase3, [10], [10], flags=flags)
|
| 321 |
+
|
| 322 |
+
def test_while_loop3_npm(self):
|
| 323 |
+
self.test_while_loop3(flags=no_pyobj_flags)
|
| 324 |
+
|
| 325 |
+
def test_while_loop4(self, flags=enable_pyobj_flags):
|
| 326 |
+
self.run_test(while_loop_usecase4, [10], [0], flags=flags)
|
| 327 |
+
|
| 328 |
+
def test_while_loop4_npm(self):
|
| 329 |
+
self.test_while_loop4(flags=no_pyobj_flags)
|
| 330 |
+
|
| 331 |
+
def test_while_loop5(self, flags=enable_pyobj_flags):
|
| 332 |
+
self.run_test(while_loop_usecase5, [0, 5, 10], [0, 5, 10], flags=flags)
|
| 333 |
+
|
| 334 |
+
def test_while_loop5_npm(self):
|
| 335 |
+
self.test_while_loop5(flags=no_pyobj_flags)
|
| 336 |
+
|
| 337 |
+
def test_ifelse1(self, flags=enable_pyobj_flags):
|
| 338 |
+
self.run_test(ifelse_usecase1, [-1, 0, 1], [-1, 0, 1], flags=flags)
|
| 339 |
+
|
| 340 |
+
def test_ifelse1_npm(self):
|
| 341 |
+
self.test_ifelse1(flags=no_pyobj_flags)
|
| 342 |
+
|
| 343 |
+
def test_ifelse2(self, flags=enable_pyobj_flags):
|
| 344 |
+
self.run_test(ifelse_usecase2, [-1, 0, 1], [-1, 0, 1], flags=flags)
|
| 345 |
+
|
| 346 |
+
def test_ifelse2_npm(self):
|
| 347 |
+
self.test_ifelse2(flags=no_pyobj_flags)
|
| 348 |
+
|
| 349 |
+
def test_ifelse3(self, flags=enable_pyobj_flags):
|
| 350 |
+
self.run_test(ifelse_usecase3, [-1, 0, 1], [-1, 0, 1], flags=flags)
|
| 351 |
+
|
| 352 |
+
def test_ifelse3_npm(self):
|
| 353 |
+
self.test_ifelse3(flags=no_pyobj_flags)
|
| 354 |
+
|
| 355 |
+
def test_ifelse4(self, flags=enable_pyobj_flags):
|
| 356 |
+
self.run_test(ifelse_usecase4, [-1, 0, 1], [-1, 0, 1], flags=flags)
|
| 357 |
+
|
| 358 |
+
def test_ifelse4_npm(self):
|
| 359 |
+
self.test_ifelse4(flags=no_pyobj_flags)
|
| 360 |
+
|
| 361 |
+
def test_ternary_ifelse1(self, flags=enable_pyobj_flags):
|
| 362 |
+
self.run_test(ternary_ifelse_usecase1, [-1, 0, 1], [-1, 0, 1],
|
| 363 |
+
flags=flags)
|
| 364 |
+
|
| 365 |
+
def test_ternary_ifelse1_npm(self):
|
| 366 |
+
self.test_ternary_ifelse1(flags=no_pyobj_flags)
|
| 367 |
+
|
| 368 |
+
def test_double_infinite_loop(self, flags=enable_pyobj_flags):
|
| 369 |
+
self.run_test(double_infinite_loop, [10], [0],
|
| 370 |
+
flags=flags)
|
| 371 |
+
|
| 372 |
+
def test_double_infinite_loop_npm(self):
|
| 373 |
+
self.test_double_infinite_loop(flags=no_pyobj_flags)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class TestCFGraph(TestCase):
|
| 377 |
+
"""
|
| 378 |
+
Test the numba.controlflow.CFGraph class.
|
| 379 |
+
"""
|
| 380 |
+
|
| 381 |
+
def from_adj_list(self, d, entry_point=0):
|
| 382 |
+
"""
|
| 383 |
+
Build a CFGraph class from a dict of adjacency lists.
|
| 384 |
+
"""
|
| 385 |
+
g = CFGraph()
|
| 386 |
+
# Need to add all nodes before adding edges
|
| 387 |
+
for node in d:
|
| 388 |
+
g.add_node(node)
|
| 389 |
+
for node, dests in d.items():
|
| 390 |
+
for dest in dests:
|
| 391 |
+
g.add_edge(node, dest)
|
| 392 |
+
return g
|
| 393 |
+
|
| 394 |
+
def loopless1(self):
|
| 395 |
+
"""
|
| 396 |
+
A simple CFG corresponding to the following code structure:
|
| 397 |
+
|
| 398 |
+
c = (... if ... else ...) + ...
|
| 399 |
+
return b + c
|
| 400 |
+
"""
|
| 401 |
+
g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []})
|
| 402 |
+
g.set_entry_point(0)
|
| 403 |
+
g.process()
|
| 404 |
+
return g
|
| 405 |
+
|
| 406 |
+
def loopless1_dead_nodes(self):
|
| 407 |
+
"""
|
| 408 |
+
Same as loopless1(), but with added dead blocks (some of them
|
| 409 |
+
in a loop).
|
| 410 |
+
"""
|
| 411 |
+
g = self.from_adj_list(
|
| 412 |
+
{0: [18, 12],
|
| 413 |
+
12: [21],
|
| 414 |
+
18: [21],
|
| 415 |
+
21: [],
|
| 416 |
+
91: [12, 0],
|
| 417 |
+
92: [91, 93],
|
| 418 |
+
93: [92],
|
| 419 |
+
94: [],
|
| 420 |
+
})
|
| 421 |
+
g.set_entry_point(0)
|
| 422 |
+
g.process()
|
| 423 |
+
return g
|
| 424 |
+
|
| 425 |
+
def loopless2(self):
|
| 426 |
+
"""
|
| 427 |
+
A loopless CFG corresponding to the following code structure:
|
| 428 |
+
|
| 429 |
+
c = (... if ... else ...) + ...
|
| 430 |
+
if c:
|
| 431 |
+
return ...
|
| 432 |
+
else:
|
| 433 |
+
return ...
|
| 434 |
+
|
| 435 |
+
Note there are two exit points, and the entry point has been
|
| 436 |
+
changed to a non-zero value.
|
| 437 |
+
"""
|
| 438 |
+
g = self.from_adj_list(
|
| 439 |
+
{99: [18, 12], 12: [21], 18: [21], 21: [42, 34], 34: [], 42: []})
|
| 440 |
+
g.set_entry_point(99)
|
| 441 |
+
g.process()
|
| 442 |
+
return g
|
| 443 |
+
|
| 444 |
+
def multiple_loops(self):
|
| 445 |
+
"""
|
| 446 |
+
A CFG with multiple nested loops:
|
| 447 |
+
|
| 448 |
+
for y in b:
|
| 449 |
+
for x in a:
|
| 450 |
+
# This loop has two back edges
|
| 451 |
+
if b:
|
| 452 |
+
continue
|
| 453 |
+
else:
|
| 454 |
+
continue
|
| 455 |
+
for z in c:
|
| 456 |
+
if z:
|
| 457 |
+
return ...
|
| 458 |
+
"""
|
| 459 |
+
g = self.from_adj_list({0: [7],
|
| 460 |
+
7: [10, 60],
|
| 461 |
+
10: [13],
|
| 462 |
+
13: [20],
|
| 463 |
+
20: [56, 23],
|
| 464 |
+
23: [32, 44],
|
| 465 |
+
32: [20],
|
| 466 |
+
44: [20],
|
| 467 |
+
56: [57],
|
| 468 |
+
57: [7],
|
| 469 |
+
60: [61],
|
| 470 |
+
61: [68],
|
| 471 |
+
68: [87, 71],
|
| 472 |
+
71: [80, 68],
|
| 473 |
+
80: [],
|
| 474 |
+
87: [88],
|
| 475 |
+
88: []}
|
| 476 |
+
)
|
| 477 |
+
g.set_entry_point(0)
|
| 478 |
+
g.process()
|
| 479 |
+
return g
|
| 480 |
+
|
| 481 |
+
def multiple_exits(self):
|
| 482 |
+
"""
|
| 483 |
+
A CFG with three loop exits, one of which is also a function
|
| 484 |
+
exit point, and another function exit point:
|
| 485 |
+
|
| 486 |
+
for x in a:
|
| 487 |
+
if a:
|
| 488 |
+
return b
|
| 489 |
+
elif b:
|
| 490 |
+
break
|
| 491 |
+
return c
|
| 492 |
+
"""
|
| 493 |
+
g = self.from_adj_list(
|
| 494 |
+
{0: [7],
|
| 495 |
+
7: [10, 36],
|
| 496 |
+
10: [19, 23],
|
| 497 |
+
19: [],
|
| 498 |
+
23: [29, 7],
|
| 499 |
+
29: [37],
|
| 500 |
+
36: [37],
|
| 501 |
+
37: []
|
| 502 |
+
})
|
| 503 |
+
g.set_entry_point(0)
|
| 504 |
+
g.process()
|
| 505 |
+
return g
|
| 506 |
+
|
| 507 |
+
def infinite_loop1(self):
|
| 508 |
+
"""
|
| 509 |
+
A CFG with a infinite loop and an alternate exit point:
|
| 510 |
+
|
| 511 |
+
if c:
|
| 512 |
+
return
|
| 513 |
+
while True:
|
| 514 |
+
if a:
|
| 515 |
+
...
|
| 516 |
+
else:
|
| 517 |
+
...
|
| 518 |
+
"""
|
| 519 |
+
g = self.from_adj_list(
|
| 520 |
+
{0: [10, 6], 6: [], 10: [13], 13: [26, 19], 19: [13], 26: [13]})
|
| 521 |
+
g.set_entry_point(0)
|
| 522 |
+
g.process()
|
| 523 |
+
return g
|
| 524 |
+
|
| 525 |
+
def infinite_loop2(self):
|
| 526 |
+
"""
|
| 527 |
+
A CFG with no exit point at all:
|
| 528 |
+
|
| 529 |
+
while True:
|
| 530 |
+
if a:
|
| 531 |
+
...
|
| 532 |
+
else:
|
| 533 |
+
...
|
| 534 |
+
"""
|
| 535 |
+
g = self.from_adj_list({0: [3], 3: [16, 9], 9: [3], 16: [3]})
|
| 536 |
+
g.set_entry_point(0)
|
| 537 |
+
g.process()
|
| 538 |
+
return g
|
| 539 |
+
|
| 540 |
+
def test_simple_properties(self):
|
| 541 |
+
g = self.loopless1()
|
| 542 |
+
self.assertEqual(sorted(g.successors(0)), [(12, None), (18, None)])
|
| 543 |
+
self.assertEqual(sorted(g.successors(21)), [])
|
| 544 |
+
self.assertEqual(sorted(g.predecessors(0)), [])
|
| 545 |
+
self.assertEqual(sorted(g.predecessors(21)), [(12, None), (18, None)])
|
| 546 |
+
|
| 547 |
+
def test_exit_points(self):
|
| 548 |
+
g = self.loopless1()
|
| 549 |
+
self.assertEqual(sorted(g.exit_points()), [21])
|
| 550 |
+
g = self.loopless1_dead_nodes()
|
| 551 |
+
self.assertEqual(sorted(g.exit_points()), [21])
|
| 552 |
+
g = self.loopless2()
|
| 553 |
+
self.assertEqual(sorted(g.exit_points()), [34, 42])
|
| 554 |
+
g = self.multiple_loops()
|
| 555 |
+
self.assertEqual(sorted(g.exit_points()), [80, 88])
|
| 556 |
+
g = self.infinite_loop1()
|
| 557 |
+
self.assertEqual(sorted(g.exit_points()), [6])
|
| 558 |
+
g = self.infinite_loop2()
|
| 559 |
+
self.assertEqual(sorted(g.exit_points()), [])
|
| 560 |
+
g = self.multiple_exits()
|
| 561 |
+
self.assertEqual(sorted(g.exit_points()), [19, 37])
|
| 562 |
+
|
| 563 |
+
def test_dead_nodes(self):
|
| 564 |
+
g = self.loopless1()
|
| 565 |
+
self.assertEqual(len(g.dead_nodes()), 0)
|
| 566 |
+
self.assertEqual(sorted(g.nodes()),
|
| 567 |
+
[0, 12, 18, 21])
|
| 568 |
+
g = self.loopless2()
|
| 569 |
+
self.assertEqual(len(g.dead_nodes()), 0)
|
| 570 |
+
self.assertEqual(sorted(g.nodes()),
|
| 571 |
+
[12, 18, 21, 34, 42, 99])
|
| 572 |
+
g = self.multiple_loops()
|
| 573 |
+
self.assertEqual(len(g.dead_nodes()), 0)
|
| 574 |
+
g = self.infinite_loop1()
|
| 575 |
+
self.assertEqual(len(g.dead_nodes()), 0)
|
| 576 |
+
g = self.multiple_exits()
|
| 577 |
+
self.assertEqual(len(g.dead_nodes()), 0)
|
| 578 |
+
# Only this example has dead nodes
|
| 579 |
+
g = self.loopless1_dead_nodes()
|
| 580 |
+
self.assertEqual(sorted(g.dead_nodes()),
|
| 581 |
+
[91, 92, 93, 94])
|
| 582 |
+
self.assertEqual(sorted(g.nodes()),
|
| 583 |
+
[0, 12, 18, 21])
|
| 584 |
+
|
| 585 |
+
def test_descendents(self):
|
| 586 |
+
g = self.loopless2()
|
| 587 |
+
d = g.descendents(34)
|
| 588 |
+
self.assertEqual(sorted(d), [])
|
| 589 |
+
d = g.descendents(42)
|
| 590 |
+
self.assertEqual(sorted(d), [])
|
| 591 |
+
d = g.descendents(21)
|
| 592 |
+
self.assertEqual(sorted(d), [34, 42])
|
| 593 |
+
d = g.descendents(99)
|
| 594 |
+
self.assertEqual(sorted(d), [12, 18, 21, 34, 42])
|
| 595 |
+
g = self.infinite_loop1()
|
| 596 |
+
d = g.descendents(26)
|
| 597 |
+
self.assertEqual(sorted(d), [])
|
| 598 |
+
d = g.descendents(19)
|
| 599 |
+
self.assertEqual(sorted(d), [])
|
| 600 |
+
d = g.descendents(13)
|
| 601 |
+
self.assertEqual(sorted(d), [19, 26])
|
| 602 |
+
d = g.descendents(10)
|
| 603 |
+
self.assertEqual(sorted(d), [13, 19, 26])
|
| 604 |
+
d = g.descendents(6)
|
| 605 |
+
self.assertEqual(sorted(d), [])
|
| 606 |
+
d = g.descendents(0)
|
| 607 |
+
self.assertEqual(sorted(d), [6, 10, 13, 19, 26])
|
| 608 |
+
|
| 609 |
+
def test_topo_order(self):
|
| 610 |
+
g = self.loopless1()
|
| 611 |
+
self.assertIn(g.topo_order(),
|
| 612 |
+
([0, 12, 18, 21], [0, 18, 12, 21]))
|
| 613 |
+
g = self.loopless2()
|
| 614 |
+
self.assertIn(g.topo_order(),
|
| 615 |
+
([99, 18, 12, 21, 34, 42], [99, 12, 18, 21, 34, 42]))
|
| 616 |
+
g = self.infinite_loop2()
|
| 617 |
+
self.assertIn(g.topo_order(),
|
| 618 |
+
([0, 3, 9, 16], [0, 3, 16, 9]))
|
| 619 |
+
g = self.infinite_loop1()
|
| 620 |
+
self.assertIn(g.topo_order(),
|
| 621 |
+
([0, 6, 10, 13, 19, 26], [0, 6, 10, 13, 26, 19],
|
| 622 |
+
[0, 10, 13, 19, 26, 6], [0, 10, 13, 26, 19, 6]))
|
| 623 |
+
|
| 624 |
+
def test_topo_sort(self):
|
| 625 |
+
def check_topo_sort(nodes, expected):
|
| 626 |
+
self.assertIn(list(g.topo_sort(nodes)), expected)
|
| 627 |
+
self.assertIn(list(g.topo_sort(nodes[::-1])), expected)
|
| 628 |
+
self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1],
|
| 629 |
+
expected)
|
| 630 |
+
self.assertIn(list(g.topo_sort(nodes[::-1], reverse=True))[::-1],
|
| 631 |
+
expected)
|
| 632 |
+
self.random.shuffle(nodes)
|
| 633 |
+
self.assertIn(list(g.topo_sort(nodes)), expected)
|
| 634 |
+
self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1],
|
| 635 |
+
expected)
|
| 636 |
+
|
| 637 |
+
g = self.loopless2()
|
| 638 |
+
check_topo_sort([21, 99, 12, 34], ([99, 12, 21, 34],))
|
| 639 |
+
# NOTE: topo_sort() is not stable
|
| 640 |
+
check_topo_sort([18, 12, 42, 99],
|
| 641 |
+
([99, 12, 18, 42], [99, 18, 12, 42]))
|
| 642 |
+
g = self.multiple_exits()
|
| 643 |
+
check_topo_sort([19, 10, 7, 36],
|
| 644 |
+
([7, 10, 19, 36], [7, 10, 36, 19], [7, 36, 10, 19]))
|
| 645 |
+
|
| 646 |
+
def check_dominators(self, got, expected):
|
| 647 |
+
self.assertEqual(sorted(got), sorted(expected))
|
| 648 |
+
for node in sorted(got):
|
| 649 |
+
self.assertEqual(sorted(got[node]), sorted(expected[node]),
|
| 650 |
+
"mismatch for %r" % (node,))
|
| 651 |
+
|
| 652 |
+
def test_dominators_loopless(self):
|
| 653 |
+
def eq_(d, l):
|
| 654 |
+
self.assertEqual(sorted(doms[d]), l)
|
| 655 |
+
for g in [self.loopless1(), self.loopless1_dead_nodes()]:
|
| 656 |
+
doms = g.dominators()
|
| 657 |
+
eq_(0, [0])
|
| 658 |
+
eq_(12, [0, 12])
|
| 659 |
+
eq_(18, [0, 18])
|
| 660 |
+
eq_(21, [0, 21])
|
| 661 |
+
g = self.loopless2()
|
| 662 |
+
doms = g.dominators()
|
| 663 |
+
eq_(99, [99])
|
| 664 |
+
eq_(12, [12, 99])
|
| 665 |
+
eq_(18, [18, 99])
|
| 666 |
+
eq_(21, [21, 99])
|
| 667 |
+
eq_(34, [21, 34, 99])
|
| 668 |
+
eq_(42, [21, 42, 99])
|
| 669 |
+
|
| 670 |
+
def test_dominators_loops(self):
|
| 671 |
+
g = self.multiple_exits()
|
| 672 |
+
doms = g.dominators()
|
| 673 |
+
self.check_dominators(doms,
|
| 674 |
+
{0: [0],
|
| 675 |
+
7: [0, 7],
|
| 676 |
+
10: [0, 7, 10],
|
| 677 |
+
19: [0, 7, 10, 19],
|
| 678 |
+
23: [0, 7, 10, 23],
|
| 679 |
+
29: [0, 7, 10, 23, 29],
|
| 680 |
+
36: [0, 7, 36],
|
| 681 |
+
37: [0, 7, 37],
|
| 682 |
+
})
|
| 683 |
+
g = self.multiple_loops()
|
| 684 |
+
doms = g.dominators()
|
| 685 |
+
self.check_dominators(doms,
|
| 686 |
+
{0: [0],
|
| 687 |
+
7: [0, 7],
|
| 688 |
+
10: [0, 10, 7],
|
| 689 |
+
13: [0, 10, 13, 7],
|
| 690 |
+
20: [0, 10, 20, 13, 7],
|
| 691 |
+
23: [0, 20, 23, 7, 10, 13],
|
| 692 |
+
32: [32, 0, 20, 23, 7, 10, 13],
|
| 693 |
+
44: [0, 20, 23, 7, 10, 44, 13],
|
| 694 |
+
56: [0, 20, 7, 56, 10, 13],
|
| 695 |
+
57: [0, 20, 7, 56, 57, 10, 13],
|
| 696 |
+
60: [0, 60, 7],
|
| 697 |
+
61: [0, 60, 61, 7],
|
| 698 |
+
68: [0, 68, 60, 61, 7],
|
| 699 |
+
71: [0, 68, 71, 7, 60, 61],
|
| 700 |
+
80: [80, 0, 68, 71, 7, 60, 61],
|
| 701 |
+
87: [0, 68, 87, 7, 60, 61],
|
| 702 |
+
88: [0, 68, 87, 88, 7, 60, 61]
|
| 703 |
+
})
|
| 704 |
+
g = self.infinite_loop1()
|
| 705 |
+
doms = g.dominators()
|
| 706 |
+
self.check_dominators(doms,
|
| 707 |
+
{0: [0],
|
| 708 |
+
6: [0, 6],
|
| 709 |
+
10: [0, 10],
|
| 710 |
+
13: [0, 10, 13],
|
| 711 |
+
19: [0, 10, 19, 13],
|
| 712 |
+
26: [0, 10, 13, 26],
|
| 713 |
+
})
|
| 714 |
+
|
| 715 |
+
def test_post_dominators_loopless(self):
|
| 716 |
+
def eq_(d, l):
|
| 717 |
+
self.assertEqual(sorted(doms[d]), l)
|
| 718 |
+
for g in [self.loopless1(), self.loopless1_dead_nodes()]:
|
| 719 |
+
doms = g.post_dominators()
|
| 720 |
+
eq_(0, [0, 21])
|
| 721 |
+
eq_(12, [12, 21])
|
| 722 |
+
eq_(18, [18, 21])
|
| 723 |
+
eq_(21, [21])
|
| 724 |
+
g = self.loopless2()
|
| 725 |
+
doms = g.post_dominators()
|
| 726 |
+
eq_(34, [34])
|
| 727 |
+
eq_(42, [42])
|
| 728 |
+
eq_(21, [21])
|
| 729 |
+
eq_(18, [18, 21])
|
| 730 |
+
eq_(12, [12, 21])
|
| 731 |
+
eq_(99, [21, 99])
|
| 732 |
+
|
| 733 |
+
def test_post_dominators_loops(self):
|
| 734 |
+
g = self.multiple_exits()
|
| 735 |
+
doms = g.post_dominators()
|
| 736 |
+
self.check_dominators(doms,
|
| 737 |
+
{0: [0, 7],
|
| 738 |
+
7: [7],
|
| 739 |
+
10: [10],
|
| 740 |
+
19: [19],
|
| 741 |
+
23: [23],
|
| 742 |
+
29: [29, 37],
|
| 743 |
+
36: [36, 37],
|
| 744 |
+
37: [37],
|
| 745 |
+
})
|
| 746 |
+
g = self.multiple_loops()
|
| 747 |
+
doms = g.post_dominators()
|
| 748 |
+
self.check_dominators(doms,
|
| 749 |
+
{0: [0, 60, 68, 61, 7],
|
| 750 |
+
7: [60, 68, 61, 7],
|
| 751 |
+
10: [68, 7, 10, 13, 20, 56, 57, 60, 61],
|
| 752 |
+
13: [68, 7, 13, 20, 56, 57, 60, 61],
|
| 753 |
+
20: [20, 68, 7, 56, 57, 60, 61],
|
| 754 |
+
23: [68, 7, 20, 23, 56, 57, 60, 61],
|
| 755 |
+
32: [32, 68, 7, 20, 56, 57, 60, 61],
|
| 756 |
+
44: [68, 7, 44, 20, 56, 57, 60, 61],
|
| 757 |
+
56: [68, 7, 56, 57, 60, 61],
|
| 758 |
+
57: [57, 60, 68, 61, 7],
|
| 759 |
+
60: [60, 68, 61],
|
| 760 |
+
61: [68, 61],
|
| 761 |
+
68: [68],
|
| 762 |
+
71: [71],
|
| 763 |
+
80: [80],
|
| 764 |
+
87: [88, 87],
|
| 765 |
+
88: [88]
|
| 766 |
+
})
|
| 767 |
+
|
| 768 |
+
def test_post_dominators_infinite_loops(self):
|
| 769 |
+
# Post-dominators with infinite loops need special care
|
| 770 |
+
# (the ordinary algorithm won't work).
|
| 771 |
+
g = self.infinite_loop1()
|
| 772 |
+
doms = g.post_dominators()
|
| 773 |
+
self.check_dominators(doms,
|
| 774 |
+
{0: [0],
|
| 775 |
+
6: [6],
|
| 776 |
+
10: [10, 13],
|
| 777 |
+
13: [13],
|
| 778 |
+
19: [19],
|
| 779 |
+
26: [26],
|
| 780 |
+
})
|
| 781 |
+
g = self.infinite_loop2()
|
| 782 |
+
doms = g.post_dominators()
|
| 783 |
+
self.check_dominators(doms,
|
| 784 |
+
{0: [0, 3],
|
| 785 |
+
3: [3],
|
| 786 |
+
9: [9],
|
| 787 |
+
16: [16],
|
| 788 |
+
})
|
| 789 |
+
|
| 790 |
+
def test_dominator_tree(self):
|
| 791 |
+
def check(graph, expected):
|
| 792 |
+
domtree = graph.dominator_tree()
|
| 793 |
+
self.assertEqual(domtree, expected)
|
| 794 |
+
|
| 795 |
+
check(self.loopless1(),
|
| 796 |
+
{0: {12, 18, 21}, 12: set(), 18: set(), 21: set()})
|
| 797 |
+
check(self.loopless2(),
|
| 798 |
+
{12: set(), 18: set(), 21: {34, 42}, 34: set(), 42: set(),
|
| 799 |
+
99: {18, 12, 21}})
|
| 800 |
+
check(self.loopless1_dead_nodes(),
|
| 801 |
+
{0: {12, 18, 21}, 12: set(), 18: set(), 21: set()})
|
| 802 |
+
check(self.multiple_loops(),
|
| 803 |
+
{0: {7}, 7: {10, 60}, 60: {61}, 61: {68}, 68: {71, 87},
|
| 804 |
+
87: {88}, 88: set(), 71: {80}, 80: set(), 10: {13},
|
| 805 |
+
13: {20}, 20: {56, 23}, 23: {32, 44}, 44: set(),
|
| 806 |
+
32: set(), 56: {57}, 57: set()})
|
| 807 |
+
check(self.multiple_exits(),
|
| 808 |
+
{0: {7}, 7: {10, 36, 37}, 36: set(), 10: {19, 23},
|
| 809 |
+
23: {29}, 29: set(), 37: set(), 19: set()})
|
| 810 |
+
check(self.infinite_loop1(),
|
| 811 |
+
{0: {10, 6}, 6: set(), 10: {13}, 13: {26, 19}, 19: set(),
|
| 812 |
+
26: set()})
|
| 813 |
+
check(self.infinite_loop2(),
|
| 814 |
+
{0: {3}, 3: {16, 9}, 9: set(), 16: set()})
|
| 815 |
+
|
| 816 |
+
def test_immediate_dominators(self):
|
| 817 |
+
def check(graph, expected):
|
| 818 |
+
idoms = graph.immediate_dominators()
|
| 819 |
+
self.assertEqual(idoms, expected)
|
| 820 |
+
|
| 821 |
+
check(self.loopless1(),
|
| 822 |
+
{0: 0, 12: 0, 18: 0, 21: 0})
|
| 823 |
+
check(self.loopless2(),
|
| 824 |
+
{18: 99, 12: 99, 21: 99, 42: 21, 34: 21, 99: 99})
|
| 825 |
+
check(self.loopless1_dead_nodes(),
|
| 826 |
+
{0: 0, 12: 0, 18: 0, 21: 0})
|
| 827 |
+
check(self.multiple_loops(),
|
| 828 |
+
{0: 0, 7: 0, 10: 7, 13: 10, 20: 13, 23: 20,
|
| 829 |
+
32: 23, 44: 23, 56: 20, 57: 56, 60: 7, 61: 60,
|
| 830 |
+
68: 61, 71: 68, 80: 71, 87: 68, 88: 87})
|
| 831 |
+
check(self.multiple_exits(),
|
| 832 |
+
{0:0, 7: 0, 10: 7, 19: 10, 23: 10, 29: 23, 36: 7, 37: 7})
|
| 833 |
+
check(self.infinite_loop1(),
|
| 834 |
+
{0: 0, 6: 0, 10: 0, 13: 10, 19: 13, 26: 13})
|
| 835 |
+
check(self.infinite_loop2(),
|
| 836 |
+
{0: 0, 3: 0, 9: 3, 16: 3})
|
| 837 |
+
|
| 838 |
+
def test_dominance_frontier(self):
|
| 839 |
+
def check(graph, expected):
|
| 840 |
+
df = graph.dominance_frontier()
|
| 841 |
+
self.assertEqual(df, expected)
|
| 842 |
+
|
| 843 |
+
check(self.loopless1(),
|
| 844 |
+
{0: set(), 12: {21}, 18: {21}, 21: set()})
|
| 845 |
+
check(self.loopless2(),
|
| 846 |
+
{18: {21}, 12: {21}, 21: set(), 42: set(), 34: set(), 99: set()})
|
| 847 |
+
check(self.loopless1_dead_nodes(),
|
| 848 |
+
{0: set(), 12: {21}, 18: {21}, 21: set()})
|
| 849 |
+
check(self.multiple_loops(),
|
| 850 |
+
{0: set(), 7: {7}, 10: {7}, 13: {7}, 20: {20, 7}, 23: {20},
|
| 851 |
+
32: {20}, 44: {20}, 56: {7}, 57: {7}, 60: set(), 61: set(),
|
| 852 |
+
68: {68}, 71: {68}, 80: set(), 87: set(), 88: set()})
|
| 853 |
+
check(self.multiple_exits(),
|
| 854 |
+
{0: set(), 7: {7}, 10: {37, 7}, 19: set(),
|
| 855 |
+
23: {37, 7}, 29: {37}, 36: {37}, 37: set()})
|
| 856 |
+
check(self.infinite_loop1(),
|
| 857 |
+
{0: set(), 6: set(), 10: set(), 13: {13}, 19: {13}, 26: {13}})
|
| 858 |
+
check(self.infinite_loop2(),
|
| 859 |
+
{0: set(), 3: {3}, 9: {3}, 16: {3}})
|
| 860 |
+
|
| 861 |
+
def test_backbone_loopless(self):
|
| 862 |
+
for g in [self.loopless1(), self.loopless1_dead_nodes()]:
|
| 863 |
+
self.assertEqual(sorted(g.backbone()), [0, 21])
|
| 864 |
+
g = self.loopless2()
|
| 865 |
+
self.assertEqual(sorted(g.backbone()), [21, 99])
|
| 866 |
+
|
| 867 |
+
def test_backbone_loops(self):
|
| 868 |
+
g = self.multiple_loops()
|
| 869 |
+
self.assertEqual(sorted(g.backbone()), [0, 7, 60, 61, 68])
|
| 870 |
+
g = self.infinite_loop1()
|
| 871 |
+
self.assertEqual(sorted(g.backbone()), [0])
|
| 872 |
+
g = self.infinite_loop2()
|
| 873 |
+
self.assertEqual(sorted(g.backbone()), [0, 3])
|
| 874 |
+
|
| 875 |
+
def test_loops(self):
|
| 876 |
+
for g in [self.loopless1(), self.loopless1_dead_nodes(),
|
| 877 |
+
self.loopless2()]:
|
| 878 |
+
self.assertEqual(len(g.loops()), 0)
|
| 879 |
+
|
| 880 |
+
g = self.multiple_loops()
|
| 881 |
+
# Loop headers
|
| 882 |
+
self.assertEqual(sorted(g.loops()), [7, 20, 68])
|
| 883 |
+
outer1 = g.loops()[7]
|
| 884 |
+
inner1 = g.loops()[20]
|
| 885 |
+
outer2 = g.loops()[68]
|
| 886 |
+
self.assertEqual(outer1.header, 7)
|
| 887 |
+
self.assertEqual(sorted(outer1.entries), [0])
|
| 888 |
+
self.assertEqual(sorted(outer1.exits), [60])
|
| 889 |
+
self.assertEqual(sorted(outer1.body),
|
| 890 |
+
[7, 10, 13, 20, 23, 32, 44, 56, 57])
|
| 891 |
+
self.assertEqual(inner1.header, 20)
|
| 892 |
+
self.assertEqual(sorted(inner1.entries), [13])
|
| 893 |
+
self.assertEqual(sorted(inner1.exits), [56])
|
| 894 |
+
self.assertEqual(sorted(inner1.body), [20, 23, 32, 44])
|
| 895 |
+
self.assertEqual(outer2.header, 68)
|
| 896 |
+
self.assertEqual(sorted(outer2.entries), [61])
|
| 897 |
+
self.assertEqual(sorted(outer2.exits), [80, 87])
|
| 898 |
+
self.assertEqual(sorted(outer2.body), [68, 71])
|
| 899 |
+
for node in [0, 60, 61, 80, 87, 88]:
|
| 900 |
+
self.assertEqual(g.in_loops(node), [])
|
| 901 |
+
for node in [7, 10, 13, 56, 57]:
|
| 902 |
+
self.assertEqual(g.in_loops(node), [outer1])
|
| 903 |
+
for node in [20, 23, 32, 44]:
|
| 904 |
+
self.assertEqual(g.in_loops(node), [inner1, outer1])
|
| 905 |
+
for node in [68, 71]:
|
| 906 |
+
self.assertEqual(g.in_loops(node), [outer2])
|
| 907 |
+
|
| 908 |
+
g = self.infinite_loop1()
|
| 909 |
+
# Loop headers
|
| 910 |
+
self.assertEqual(sorted(g.loops()), [13])
|
| 911 |
+
loop = g.loops()[13]
|
| 912 |
+
self.assertEqual(loop.header, 13)
|
| 913 |
+
self.assertEqual(sorted(loop.entries), [10])
|
| 914 |
+
self.assertEqual(sorted(loop.exits), [])
|
| 915 |
+
self.assertEqual(sorted(loop.body), [13, 19, 26])
|
| 916 |
+
for node in [0, 6, 10]:
|
| 917 |
+
self.assertEqual(g.in_loops(node), [])
|
| 918 |
+
for node in [13, 19, 26]:
|
| 919 |
+
self.assertEqual(g.in_loops(node), [loop])
|
| 920 |
+
|
| 921 |
+
g = self.infinite_loop2()
|
| 922 |
+
# Loop headers
|
| 923 |
+
self.assertEqual(sorted(g.loops()), [3])
|
| 924 |
+
loop = g.loops()[3]
|
| 925 |
+
self.assertEqual(loop.header, 3)
|
| 926 |
+
self.assertEqual(sorted(loop.entries), [0])
|
| 927 |
+
self.assertEqual(sorted(loop.exits), [])
|
| 928 |
+
self.assertEqual(sorted(loop.body), [3, 9, 16])
|
| 929 |
+
for node in [0]:
|
| 930 |
+
self.assertEqual(g.in_loops(node), [])
|
| 931 |
+
for node in [3, 9, 16]:
|
| 932 |
+
self.assertEqual(g.in_loops(node), [loop])
|
| 933 |
+
|
| 934 |
+
g = self.multiple_exits()
|
| 935 |
+
# Loop headers
|
| 936 |
+
self.assertEqual(sorted(g.loops()), [7])
|
| 937 |
+
loop = g.loops()[7]
|
| 938 |
+
self.assertEqual(loop.header, 7)
|
| 939 |
+
self.assertEqual(sorted(loop.entries), [0])
|
| 940 |
+
self.assertEqual(sorted(loop.exits), [19, 29, 36])
|
| 941 |
+
self.assertEqual(sorted(loop.body), [7, 10, 23])
|
| 942 |
+
for node in [0, 19, 29, 36]:
|
| 943 |
+
self.assertEqual(g.in_loops(node), [])
|
| 944 |
+
for node in [7, 10, 23]:
|
| 945 |
+
self.assertEqual(g.in_loops(node), [loop])
|
| 946 |
+
|
| 947 |
+
def test_loop_dfs_pathological(self):
|
| 948 |
+
# The follow adjlist is an export from the reproducer in #6186
|
| 949 |
+
g = self.from_adj_list({
|
| 950 |
+
0: {38, 14},
|
| 951 |
+
14: {38, 22},
|
| 952 |
+
22: {38, 30},
|
| 953 |
+
30: {42, 38},
|
| 954 |
+
38: {42},
|
| 955 |
+
42: {64, 50},
|
| 956 |
+
50: {64, 58},
|
| 957 |
+
58: {128},
|
| 958 |
+
64: {72, 86},
|
| 959 |
+
72: {80, 86},
|
| 960 |
+
80: {128},
|
| 961 |
+
86: {108, 94},
|
| 962 |
+
94: {108, 102},
|
| 963 |
+
102: {128},
|
| 964 |
+
108: {128, 116},
|
| 965 |
+
116: {128, 124},
|
| 966 |
+
124: {128},
|
| 967 |
+
128: {178, 174},
|
| 968 |
+
174: {178},
|
| 969 |
+
178: {210, 206},
|
| 970 |
+
206: {210},
|
| 971 |
+
210: {248, 252},
|
| 972 |
+
248: {252},
|
| 973 |
+
252: {282, 286},
|
| 974 |
+
282: {286},
|
| 975 |
+
286: {296, 326},
|
| 976 |
+
296: {330},
|
| 977 |
+
326: {330},
|
| 978 |
+
330: {370, 340},
|
| 979 |
+
340: {374},
|
| 980 |
+
370: {374},
|
| 981 |
+
374: {380, 382},
|
| 982 |
+
380: {382},
|
| 983 |
+
382: {818, 390},
|
| 984 |
+
390: {456, 458},
|
| 985 |
+
456: {458},
|
| 986 |
+
458: {538, 566},
|
| 987 |
+
538: {548, 566},
|
| 988 |
+
548: set(),
|
| 989 |
+
566: {586, 572},
|
| 990 |
+
572: {586},
|
| 991 |
+
586: {708, 596},
|
| 992 |
+
596: {608},
|
| 993 |
+
608: {610},
|
| 994 |
+
610: {704, 620},
|
| 995 |
+
620: {666, 630},
|
| 996 |
+
630: {636, 646},
|
| 997 |
+
636: {666, 646},
|
| 998 |
+
646: {666},
|
| 999 |
+
666: {610},
|
| 1000 |
+
704: {706},
|
| 1001 |
+
706: {818},
|
| 1002 |
+
708: {720},
|
| 1003 |
+
720: {722},
|
| 1004 |
+
722: {816, 732},
|
| 1005 |
+
732: {778, 742},
|
| 1006 |
+
742: {748, 758},
|
| 1007 |
+
748: {778, 758},
|
| 1008 |
+
758: {778},
|
| 1009 |
+
778: {722},
|
| 1010 |
+
816: {818},
|
| 1011 |
+
818: set(),
|
| 1012 |
+
})
|
| 1013 |
+
g.set_entry_point(0)
|
| 1014 |
+
g.process()
|
| 1015 |
+
stats = {}
|
| 1016 |
+
# Compute backedges and store the iteration count for testing
|
| 1017 |
+
back_edges = g._find_back_edges(stats=stats)
|
| 1018 |
+
self.assertEqual(back_edges, {(666, 610), (778, 722)})
|
| 1019 |
+
self.assertEqual(stats['iteration_count'], 155)
|
| 1020 |
+
|
| 1021 |
+
def test_equals(self):
|
| 1022 |
+
|
| 1023 |
+
def get_new():
|
| 1024 |
+
g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []})
|
| 1025 |
+
g.set_entry_point(0)
|
| 1026 |
+
g.process()
|
| 1027 |
+
return g
|
| 1028 |
+
|
| 1029 |
+
x = get_new()
|
| 1030 |
+
y = get_new()
|
| 1031 |
+
|
| 1032 |
+
# identical
|
| 1033 |
+
self.assertEqual(x, y)
|
| 1034 |
+
|
| 1035 |
+
# identical but defined in a different order
|
| 1036 |
+
g = self.from_adj_list({0: [12, 18], 18: [21], 21: [], 12: [21]})
|
| 1037 |
+
g.set_entry_point(0)
|
| 1038 |
+
g.process()
|
| 1039 |
+
self.assertEqual(x, g)
|
| 1040 |
+
|
| 1041 |
+
# different entry point
|
| 1042 |
+
z = get_new()
|
| 1043 |
+
z.set_entry_point(18)
|
| 1044 |
+
z.process()
|
| 1045 |
+
self.assertNotEqual(x, z)
|
| 1046 |
+
|
| 1047 |
+
# extra node/edge, same entry point
|
| 1048 |
+
z = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: [22],
|
| 1049 |
+
22: []})
|
| 1050 |
+
z.set_entry_point(0)
|
| 1051 |
+
z.process()
|
| 1052 |
+
self.assertNotEqual(x, z)
|
| 1053 |
+
|
| 1054 |
+
# same nodes, different edges
|
| 1055 |
+
a = self.from_adj_list({0: [18, 12], 12: [0], 18: []})
|
| 1056 |
+
a.set_entry_point(0)
|
| 1057 |
+
a.process()
|
| 1058 |
+
z = self.from_adj_list({0: [18, 12], 12: [18], 18: []})
|
| 1059 |
+
z.set_entry_point(0)
|
| 1060 |
+
z.process()
|
| 1061 |
+
self.assertNotEqual(a, z)
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
class TestRealCodeDomFront(TestCase):
|
| 1065 |
+
"""Test IDOM and DOMFRONT computation on real python bytecode.
|
| 1066 |
+
Note: there will be less testing on IDOM (esp in loop) because of
|
| 1067 |
+
the extra blocks inserted by the interpreter. But, testing on DOMFRONT
|
| 1068 |
+
(which depends on IDOM) is easier.
|
| 1069 |
+
|
| 1070 |
+
Testing is done by associating names to basicblock by using globals of
|
| 1071 |
+
the pattern "SET_BLOCK_<name>", which are scanned by
|
| 1072 |
+
`.get_cfa_and_namedblocks` into *namedblocks* dictionary. That way, we
|
| 1073 |
+
can check that a block of a certain name is a IDOM or DOMFRONT of another
|
| 1074 |
+
named block.
|
| 1075 |
+
"""
|
| 1076 |
+
def cfa(self, bc):
|
| 1077 |
+
cfa = ControlFlowAnalysis(bc)
|
| 1078 |
+
cfa.run()
|
| 1079 |
+
return cfa
|
| 1080 |
+
|
| 1081 |
+
def get_cfa_and_namedblocks(self, fn):
|
| 1082 |
+
fid = FunctionIdentity.from_function(fn)
|
| 1083 |
+
bc = ByteCode(func_id=fid)
|
| 1084 |
+
cfa = self.cfa(bc)
|
| 1085 |
+
namedblocks = self._scan_namedblocks(bc, cfa)
|
| 1086 |
+
|
| 1087 |
+
#### To debug, uncomment below
|
| 1088 |
+
# print(bc.dump())
|
| 1089 |
+
# print("IDOMS")
|
| 1090 |
+
# for k, v in sorted(cfa.graph.immediate_dominators().items()):
|
| 1091 |
+
# print('{} -> {}'.format(k, v))
|
| 1092 |
+
# print("DOMFRONT")
|
| 1093 |
+
# for k, vs in sorted(cfa.graph.dominance_frontier().items()):
|
| 1094 |
+
# print('{} -> {}'.format(k, vs))
|
| 1095 |
+
# print(namedblocks)
|
| 1096 |
+
# cfa.graph.render_dot().view()
|
| 1097 |
+
|
| 1098 |
+
return cfa, namedblocks
|
| 1099 |
+
|
| 1100 |
+
def _scan_namedblocks(self, bc, cfa):
|
| 1101 |
+
"""Scan namedblocks as denoted by a LOAD_GLOBAL bytecode referring
|
| 1102 |
+
to global variables with the pattern "SET_BLOCK_<name>", where "<name>"
|
| 1103 |
+
would be the name for the current block.
|
| 1104 |
+
"""
|
| 1105 |
+
namedblocks = {}
|
| 1106 |
+
blocks = sorted([x.offset for x in cfa.iterblocks()])
|
| 1107 |
+
prefix = 'SET_BLOCK_'
|
| 1108 |
+
|
| 1109 |
+
for inst in bc:
|
| 1110 |
+
# Find LOAD_GLOBAL that refers to "SET_BLOCK_<name>"
|
| 1111 |
+
if inst.opname == 'LOAD_GLOBAL':
|
| 1112 |
+
gv = bc.co_names[_fix_LOAD_GLOBAL_arg(inst.arg)]
|
| 1113 |
+
if gv.startswith(prefix):
|
| 1114 |
+
name = gv[len(prefix):]
|
| 1115 |
+
# Find the block where this instruction resides
|
| 1116 |
+
for s, e in zip(blocks, blocks[1:] + [blocks[-1] + 1]):
|
| 1117 |
+
if s <= inst.offset < e:
|
| 1118 |
+
break
|
| 1119 |
+
else:
|
| 1120 |
+
raise AssertionError('unreachable loop')
|
| 1121 |
+
blkno = s
|
| 1122 |
+
namedblocks[name] = blkno
|
| 1123 |
+
return namedblocks
|
| 1124 |
+
|
| 1125 |
+
def test_loop(self):
|
| 1126 |
+
def foo(n):
|
| 1127 |
+
c = 0
|
| 1128 |
+
SET_BLOCK_A # noqa: F821
|
| 1129 |
+
i = 0
|
| 1130 |
+
while SET_BLOCK_B0: # noqa: F821
|
| 1131 |
+
SET_BLOCK_B1 # noqa: F821
|
| 1132 |
+
c += 1
|
| 1133 |
+
i += 1
|
| 1134 |
+
SET_BLOCK_C # noqa: F821
|
| 1135 |
+
return c
|
| 1136 |
+
|
| 1137 |
+
cfa, blkpts = self.get_cfa_and_namedblocks(foo)
|
| 1138 |
+
|
| 1139 |
+
# Py3.10 turns while loop into if(...) { do {...} while(...) }.
|
| 1140 |
+
# Also, `SET_BLOCK_B0` is duplicated. As a result, the second B0
|
| 1141 |
+
# is picked up by `blkpts`.
|
| 1142 |
+
domfront = cfa.graph.dominance_frontier()
|
| 1143 |
+
self.assertFalse(domfront[blkpts['A']])
|
| 1144 |
+
self.assertFalse(domfront[blkpts['C']])
|
| 1145 |
+
|
| 1146 |
+
def test_loop_nested_and_break(self):
|
| 1147 |
+
def foo(n):
|
| 1148 |
+
SET_BLOCK_A # noqa: F821
|
| 1149 |
+
while SET_BLOCK_B0: # noqa: F821
|
| 1150 |
+
SET_BLOCK_B1 # noqa: F821
|
| 1151 |
+
while SET_BLOCK_C0: # noqa: F821
|
| 1152 |
+
SET_BLOCK_C1 # noqa: F821
|
| 1153 |
+
if SET_BLOCK_D0: # noqa: F821
|
| 1154 |
+
SET_BLOCK_D1 # noqa: F821
|
| 1155 |
+
break
|
| 1156 |
+
elif n:
|
| 1157 |
+
SET_BLOCK_D2 # noqa: F821
|
| 1158 |
+
SET_BLOCK_E # noqa: F821
|
| 1159 |
+
SET_BLOCK_F # noqa: F821
|
| 1160 |
+
SET_BLOCK_G # noqa: F821
|
| 1161 |
+
|
| 1162 |
+
cfa, blkpts = self.get_cfa_and_namedblocks(foo)
|
| 1163 |
+
self.assertEqual(blkpts['D0'], blkpts['C1'])
|
| 1164 |
+
|
| 1165 |
+
# Py3.10 changes while loop into if-do-while
|
| 1166 |
+
domfront = cfa.graph.dominance_frontier()
|
| 1167 |
+
self.assertFalse(domfront[blkpts['A']])
|
| 1168 |
+
self.assertFalse(domfront[blkpts['G']])
|
| 1169 |
+
# 2 domfront members for C1
|
| 1170 |
+
# C0 because of the loop; F because of the break.
|
| 1171 |
+
self.assertEqual({blkpts['F']}, domfront[blkpts['D1']])
|
| 1172 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['D2']])
|
| 1173 |
+
|
| 1174 |
+
def test_if_else(self):
|
| 1175 |
+
def foo(a, b):
|
| 1176 |
+
c = 0
|
| 1177 |
+
SET_BLOCK_A # noqa: F821
|
| 1178 |
+
if a < b:
|
| 1179 |
+
SET_BLOCK_B # noqa: F821
|
| 1180 |
+
c = 1
|
| 1181 |
+
elif SET_BLOCK_C0: # noqa: F821
|
| 1182 |
+
SET_BLOCK_C1 # noqa: F821
|
| 1183 |
+
c = 2
|
| 1184 |
+
else:
|
| 1185 |
+
SET_BLOCK_D # noqa: F821
|
| 1186 |
+
c = 3
|
| 1187 |
+
|
| 1188 |
+
SET_BLOCK_E # noqa: F821
|
| 1189 |
+
if a % b == 0:
|
| 1190 |
+
SET_BLOCK_F # noqa: F821
|
| 1191 |
+
c += 1
|
| 1192 |
+
SET_BLOCK_G # noqa: F821
|
| 1193 |
+
return c
|
| 1194 |
+
|
| 1195 |
+
cfa, blkpts = self.get_cfa_and_namedblocks(foo)
|
| 1196 |
+
|
| 1197 |
+
idoms = cfa.graph.immediate_dominators()
|
| 1198 |
+
self.assertEqual(blkpts['A'], idoms[blkpts['B']])
|
| 1199 |
+
self.assertEqual(blkpts['A'], idoms[blkpts['C0']])
|
| 1200 |
+
self.assertEqual(blkpts['C0'], idoms[blkpts['C1']])
|
| 1201 |
+
self.assertEqual(blkpts['C0'], idoms[blkpts['D']])
|
| 1202 |
+
self.assertEqual(blkpts['A'], idoms[blkpts['E']])
|
| 1203 |
+
self.assertEqual(blkpts['E'], idoms[blkpts['F']])
|
| 1204 |
+
self.assertEqual(blkpts['E'], idoms[blkpts['G']])
|
| 1205 |
+
|
| 1206 |
+
domfront = cfa.graph.dominance_frontier()
|
| 1207 |
+
self.assertFalse(domfront[blkpts['A']])
|
| 1208 |
+
self.assertFalse(domfront[blkpts['E']])
|
| 1209 |
+
self.assertFalse(domfront[blkpts['G']])
|
| 1210 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['B']])
|
| 1211 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['C0']])
|
| 1212 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['C1']])
|
| 1213 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['D']])
|
| 1214 |
+
self.assertEqual({blkpts['G']}, domfront[blkpts['F']])
|
| 1215 |
+
|
| 1216 |
+
def test_if_else_nested(self):
|
| 1217 |
+
def foo():
|
| 1218 |
+
if SET_BLOCK_A0: # noqa: F821
|
| 1219 |
+
SET_BLOCK_A1 # noqa: F821
|
| 1220 |
+
if SET_BLOCK_B0: # noqa: F821
|
| 1221 |
+
SET_BLOCK_B1 # noqa: F821
|
| 1222 |
+
a = 0
|
| 1223 |
+
else:
|
| 1224 |
+
if SET_BLOCK_C0: # noqa: F821
|
| 1225 |
+
SET_BLOCK_C1 # noqa: F821
|
| 1226 |
+
a = 1
|
| 1227 |
+
else:
|
| 1228 |
+
SET_BLOCK_C2 # noqa: F821
|
| 1229 |
+
a = 2
|
| 1230 |
+
SET_BLOCK_D # noqa: F821
|
| 1231 |
+
SET_BLOCK_E # noqa: F821
|
| 1232 |
+
SET_BLOCK_F # noqa: F821
|
| 1233 |
+
return a
|
| 1234 |
+
|
| 1235 |
+
cfa, blkpts = self.get_cfa_and_namedblocks(foo)
|
| 1236 |
+
|
| 1237 |
+
idoms = cfa.graph.immediate_dominators()
|
| 1238 |
+
self.assertEqual(blkpts['A0'], idoms[blkpts['A1']])
|
| 1239 |
+
self.assertEqual(blkpts['A1'], idoms[blkpts['B1']])
|
| 1240 |
+
self.assertEqual(blkpts['A1'], idoms[blkpts['C0']])
|
| 1241 |
+
self.assertEqual(blkpts['C0'], idoms[blkpts['D']])
|
| 1242 |
+
self.assertEqual(blkpts['A1'], idoms[blkpts['E']])
|
| 1243 |
+
self.assertEqual(blkpts['A0'], idoms[blkpts['F']])
|
| 1244 |
+
|
| 1245 |
+
domfront = cfa.graph.dominance_frontier()
|
| 1246 |
+
self.assertFalse(domfront[blkpts['A0']])
|
| 1247 |
+
self.assertFalse(domfront[blkpts['F']])
|
| 1248 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['B1']])
|
| 1249 |
+
self.assertEqual({blkpts['D']}, domfront[blkpts['C1']])
|
| 1250 |
+
self.assertEqual({blkpts['E']}, domfront[blkpts['D']])
|
| 1251 |
+
self.assertEqual({blkpts['F']}, domfront[blkpts['E']])
|
| 1252 |
+
|
| 1253 |
+
def test_infinite_loop(self):
|
| 1254 |
+
def foo():
|
| 1255 |
+
SET_BLOCK_A # noqa: F821
|
| 1256 |
+
while True: # infinite loop
|
| 1257 |
+
if SET_BLOCK_B: # noqa: F821
|
| 1258 |
+
SET_BLOCK_C # noqa: F821
|
| 1259 |
+
return
|
| 1260 |
+
SET_BLOCK_D # noqa: F821
|
| 1261 |
+
SET_BLOCK_E # noqa: F821
|
| 1262 |
+
|
| 1263 |
+
cfa, blkpts = self.get_cfa_and_namedblocks(foo)
|
| 1264 |
+
|
| 1265 |
+
idoms = cfa.graph.immediate_dominators()
|
| 1266 |
+
# Py3.10 optimizes away the infinite loop and removes SET_BLOCK_E from
|
| 1267 |
+
# the bytecode.
|
| 1268 |
+
self.assertNotIn('E', blkpts)
|
| 1269 |
+
self.assertEqual(blkpts['B'], idoms[blkpts['C']])
|
| 1270 |
+
self.assertEqual(blkpts['B'], idoms[blkpts['D']])
|
| 1271 |
+
|
| 1272 |
+
domfront = cfa.graph.dominance_frontier()
|
| 1273 |
+
self.assertFalse(domfront[blkpts['A']])
|
| 1274 |
+
self.assertFalse(domfront[blkpts['C']])
|
| 1275 |
+
self.assertEqual({blkpts['B']}, domfront[blkpts['B']])
|
| 1276 |
+
self.assertEqual({blkpts['B']}, domfront[blkpts['D']])
|
| 1277 |
+
|
| 1278 |
+
|
| 1279 |
+
if __name__ == '__main__':
|
| 1280 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_func_interface.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from numba import jit
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestFuncInterface(unittest.TestCase):
|
| 6 |
+
def test_jit_function_docstring(self):
|
| 7 |
+
|
| 8 |
+
def add(x, y):
|
| 9 |
+
'''Return sum of two numbers'''
|
| 10 |
+
return x + y
|
| 11 |
+
|
| 12 |
+
c_add = jit(add)
|
| 13 |
+
self.assertEqual(c_add.__doc__, 'Return sum of two numbers')
|
| 14 |
+
|
| 15 |
+
def test_jit_function_name(self):
|
| 16 |
+
|
| 17 |
+
def add(x, y):
|
| 18 |
+
return x + y
|
| 19 |
+
|
| 20 |
+
c_add = jit(add)
|
| 21 |
+
self.assertEqual(c_add.__name__, 'add')
|
| 22 |
+
|
| 23 |
+
def test_jit_function_module(self):
|
| 24 |
+
|
| 25 |
+
def add(x, y):
|
| 26 |
+
return x + y
|
| 27 |
+
|
| 28 |
+
c_add = jit(add)
|
| 29 |
+
# Expected answer depends on how you run this test.
|
| 30 |
+
# Compare to python function instead.
|
| 31 |
+
self.assertEqual(c_add.__module__, add.__module__)
|
| 32 |
+
|
| 33 |
+
def test_jit_function_code_object(self):
|
| 34 |
+
def add(x, y):
|
| 35 |
+
return x + y
|
| 36 |
+
|
| 37 |
+
c_add = jit(add)
|
| 38 |
+
self.assertEqual(c_add.__code__, add.__code__)
|
| 39 |
+
self.assertEqual(c_add.func_code, add.__code__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_func_lifetime.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
|
| 9 |
+
|
| 10 |
+
class Dummy(object):
|
| 11 |
+
|
| 12 |
+
def __add__(self, other):
|
| 13 |
+
return other + 5
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def global_usecase1(x):
|
| 17 |
+
return x + 1
|
| 18 |
+
|
| 19 |
+
def global_usecase2():
|
| 20 |
+
return global_obj + 1
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestFuncLifetime(TestCase):
|
| 24 |
+
"""
|
| 25 |
+
Test the lifetime of compiled function objects and their dependencies.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def get_impl(self, dispatcher):
|
| 29 |
+
"""
|
| 30 |
+
Get the single implementation (a C function object) of a dispatcher.
|
| 31 |
+
"""
|
| 32 |
+
self.assertEqual(len(dispatcher.overloads), 1)
|
| 33 |
+
cres = list(dispatcher.overloads.values())[0]
|
| 34 |
+
return cres.entry_point
|
| 35 |
+
|
| 36 |
+
def check_local_func_lifetime(self, **jitargs):
|
| 37 |
+
def f(x):
|
| 38 |
+
return x + 1
|
| 39 |
+
|
| 40 |
+
c_f = jit('int32(int32)', **jitargs)(f)
|
| 41 |
+
self.assertPreciseEqual(c_f(1), 2)
|
| 42 |
+
|
| 43 |
+
cfunc = self.get_impl(c_f)
|
| 44 |
+
|
| 45 |
+
# Since we can't take a weakref to a C function object
|
| 46 |
+
# (see http://bugs.python.org/issue22116), ensure it's
|
| 47 |
+
# collected by taking a weakref to its __self__ instead
|
| 48 |
+
# (a _dynfunc._Closure object).
|
| 49 |
+
refs = [weakref.ref(obj) for obj in (f, c_f, cfunc.__self__)]
|
| 50 |
+
obj = f = c_f = cfunc = None
|
| 51 |
+
gc.collect()
|
| 52 |
+
self.assertEqual([wr() for wr in refs], [None] * len(refs))
|
| 53 |
+
|
| 54 |
+
def test_local_func_lifetime(self):
|
| 55 |
+
self.check_local_func_lifetime(forceobj=True)
|
| 56 |
+
|
| 57 |
+
def test_local_func_lifetime_npm(self):
|
| 58 |
+
self.check_local_func_lifetime(nopython=True)
|
| 59 |
+
|
| 60 |
+
def check_global_func_lifetime(self, **jitargs):
|
| 61 |
+
c_f = jit(**jitargs)(global_usecase1)
|
| 62 |
+
self.assertPreciseEqual(c_f(1), 2)
|
| 63 |
+
|
| 64 |
+
cfunc = self.get_impl(c_f)
|
| 65 |
+
|
| 66 |
+
wr = weakref.ref(c_f)
|
| 67 |
+
refs = [weakref.ref(obj) for obj in (c_f, cfunc.__self__)]
|
| 68 |
+
obj = c_f = cfunc = None
|
| 69 |
+
gc.collect()
|
| 70 |
+
self.assertEqual([wr() for wr in refs], [None] * len(refs))
|
| 71 |
+
|
| 72 |
+
def test_global_func_lifetime(self):
|
| 73 |
+
self.check_global_func_lifetime(forceobj=True)
|
| 74 |
+
|
| 75 |
+
def test_global_func_lifetime_npm(self):
|
| 76 |
+
self.check_global_func_lifetime(nopython=True)
|
| 77 |
+
|
| 78 |
+
def check_global_obj_lifetime(self, **jitargs):
|
| 79 |
+
# Since global objects can be recorded for typing purposes,
|
| 80 |
+
# check that they are not kept around after they are removed
|
| 81 |
+
# from the globals.
|
| 82 |
+
global global_obj
|
| 83 |
+
global_obj = Dummy()
|
| 84 |
+
|
| 85 |
+
c_f = jit(**jitargs)(global_usecase2)
|
| 86 |
+
self.assertPreciseEqual(c_f(), 6)
|
| 87 |
+
|
| 88 |
+
refs = [weakref.ref(obj) for obj in (c_f, global_obj)]
|
| 89 |
+
obj = c_f = global_obj = None
|
| 90 |
+
gc.collect()
|
| 91 |
+
self.assertEqual([wr() for wr in refs], [None] * len(refs))
|
| 92 |
+
|
| 93 |
+
def test_global_obj_lifetime(self):
|
| 94 |
+
self.check_global_obj_lifetime(forceobj=True)
|
| 95 |
+
|
| 96 |
+
def check_inner_function_lifetime(self, **jitargs):
|
| 97 |
+
"""
|
| 98 |
+
When a jitted function calls into another jitted function, check
|
| 99 |
+
that everything is collected as desired.
|
| 100 |
+
"""
|
| 101 |
+
def mult_10(a):
|
| 102 |
+
return a * 10
|
| 103 |
+
|
| 104 |
+
c_mult_10 = jit('intp(intp)', **jitargs)(mult_10)
|
| 105 |
+
c_mult_10.disable_compile()
|
| 106 |
+
|
| 107 |
+
def do_math(x):
|
| 108 |
+
return c_mult_10(x + 4)
|
| 109 |
+
|
| 110 |
+
c_do_math = jit('intp(intp)', **jitargs)(do_math)
|
| 111 |
+
c_do_math.disable_compile()
|
| 112 |
+
|
| 113 |
+
self.assertEqual(c_do_math(1), 50)
|
| 114 |
+
|
| 115 |
+
wrs = [weakref.ref(obj) for obj in
|
| 116 |
+
(mult_10, c_mult_10, do_math, c_do_math,
|
| 117 |
+
self.get_impl(c_mult_10).__self__,
|
| 118 |
+
self.get_impl(c_do_math).__self__,
|
| 119 |
+
)]
|
| 120 |
+
obj = mult_10 = c_mult_10 = do_math = c_do_math = None
|
| 121 |
+
gc.collect()
|
| 122 |
+
self.assertEqual([w() for w in wrs], [None] * len(wrs))
|
| 123 |
+
|
| 124 |
+
def test_inner_function_lifetime(self):
|
| 125 |
+
self.check_inner_function_lifetime(forceobj=True)
|
| 126 |
+
|
| 127 |
+
def test_inner_function_lifetime_npm(self):
|
| 128 |
+
self.check_inner_function_lifetime(nopython=True)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class TestLifeTimeIssue(TestCase):
|
| 132 |
+
def test_double_free(self):
|
| 133 |
+
from numba import njit
|
| 134 |
+
import numpy as np
|
| 135 |
+
|
| 136 |
+
# This is the function that causes the crash
|
| 137 |
+
|
| 138 |
+
@njit
|
| 139 |
+
def is_point_in_polygons(point, polygons):
|
| 140 |
+
num_polygons = polygons.shape[0]
|
| 141 |
+
if num_polygons != 0:
|
| 142 |
+
# An extra decref is inserted in this block
|
| 143 |
+
intentionally_unused_variable = polygons[0]
|
| 144 |
+
return 0
|
| 145 |
+
|
| 146 |
+
# This function creates some NRT objects for the previous function
|
| 147 |
+
# to corrupt.
|
| 148 |
+
|
| 149 |
+
@njit
|
| 150 |
+
def dummy():
|
| 151 |
+
return np.empty(10, dtype=np.int64)
|
| 152 |
+
|
| 153 |
+
polygons = np.array([[[0, 1]]])
|
| 154 |
+
points = np.array([[-1.5, 0.5]])
|
| 155 |
+
a = dummy()
|
| 156 |
+
is_point_in_polygons(points[0], polygons)
|
| 157 |
+
b = dummy()
|
| 158 |
+
# Crash happens at second call
|
| 159 |
+
is_point_in_polygons(points[0], polygons)
|
| 160 |
+
c = dummy()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == '__main__':
|
| 164 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_generators.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from numba import jit, njit
|
| 5 |
+
from numba.core import types
|
| 6 |
+
from numba.tests.support import TestCase, MemoryLeakMixin
|
| 7 |
+
from numba.core.datamodel.testing import test_factory
|
| 8 |
+
|
| 9 |
+
forceobj_flags = {'nopython': False, 'forceobj': True}
|
| 10 |
+
nopython_flags = {'nopython': True}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def make_consumer(gen_func):
|
| 14 |
+
def consumer(x):
|
| 15 |
+
res = 0.0
|
| 16 |
+
for y in gen_func(x):
|
| 17 |
+
res += y
|
| 18 |
+
return res
|
| 19 |
+
|
| 20 |
+
return consumer
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def gen1(x):
|
| 24 |
+
for i in range(x):
|
| 25 |
+
yield i
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def gen2(x):
|
| 29 |
+
for i in range(x):
|
| 30 |
+
yield i
|
| 31 |
+
for j in range(1, 3):
|
| 32 |
+
yield i + j
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def gen3(x):
|
| 36 |
+
# Polymorphic yield types must be unified
|
| 37 |
+
yield x
|
| 38 |
+
yield x + 1.5
|
| 39 |
+
yield x + 1j
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def gen4(x, y, z):
|
| 43 |
+
for i in range(3):
|
| 44 |
+
yield z
|
| 45 |
+
yield y + z
|
| 46 |
+
return
|
| 47 |
+
yield x
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def gen5():
|
| 51 |
+
# The bytecode for this generator doesn't contain any YIELD_VALUE
|
| 52 |
+
# (it's optimized away). We fail typing it, since the yield type
|
| 53 |
+
# is entirely undefined.
|
| 54 |
+
if 0:
|
| 55 |
+
yield 1
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def gen6(a, b):
|
| 59 |
+
# Infinite loop: exercise computation of state variables
|
| 60 |
+
x = a + 1
|
| 61 |
+
while True:
|
| 62 |
+
y = b + 2
|
| 63 |
+
yield x + y
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def gen7(arr):
|
| 67 |
+
# Array variable in generator state
|
| 68 |
+
for i in range(arr.size):
|
| 69 |
+
yield arr[i]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Optional arguments and boolean state members
|
| 73 |
+
def gen8(x=1, y=2, b=False):
|
| 74 |
+
bb = not b
|
| 75 |
+
yield x
|
| 76 |
+
if bb:
|
| 77 |
+
yield y
|
| 78 |
+
if b:
|
| 79 |
+
yield x + y
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def genobj(x):
|
| 83 |
+
object()
|
| 84 |
+
yield x
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def return_generator_expr(x):
|
| 88 |
+
return (i * 2 for i in x)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def gen_ndindex(shape):
|
| 92 |
+
for ind in np.ndindex(shape):
|
| 93 |
+
yield ind
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def gen_flat(arr):
|
| 97 |
+
for val in arr.flat:
|
| 98 |
+
yield val
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def gen_ndenumerate(arr):
|
| 102 |
+
for tup in np.ndenumerate(arr):
|
| 103 |
+
yield tup
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def gen_bool():
|
| 107 |
+
yield True
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def gen_unification_error():
|
| 111 |
+
yield None
|
| 112 |
+
yield 1j
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def gen_optional_and_type_unification_error():
|
| 116 |
+
# yields complex and optional(literalint)
|
| 117 |
+
i = 0
|
| 118 |
+
yield 1j
|
| 119 |
+
while True:
|
| 120 |
+
i = yield i
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def gen_changing_tuple_type():
|
| 124 |
+
# https://github.com/numba/numba/issues/7295
|
| 125 |
+
yield 1, 2
|
| 126 |
+
yield 3, 4
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def gen_changing_number_type():
|
| 130 |
+
# additional test for https://github.com/numba/numba/issues/7295
|
| 131 |
+
yield 1
|
| 132 |
+
yield 3.5
|
| 133 |
+
yield 67.8j
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TestGenerators(MemoryLeakMixin, TestCase):
|
| 137 |
+
def check_generator(self, pygen, cgen):
|
| 138 |
+
self.assertEqual(next(cgen), next(pygen))
|
| 139 |
+
# Use list comprehensions to make sure we trash the generator's
|
| 140 |
+
# former C stack.
|
| 141 |
+
expected = [x for x in pygen]
|
| 142 |
+
got = [x for x in cgen]
|
| 143 |
+
self.assertEqual(expected, got)
|
| 144 |
+
with self.assertRaises(StopIteration):
|
| 145 |
+
next(cgen)
|
| 146 |
+
|
| 147 |
+
def check_gen1(self, **kwargs):
|
| 148 |
+
pyfunc = gen1
|
| 149 |
+
cr = jit((types.int32,), **kwargs)(pyfunc)
|
| 150 |
+
pygen = pyfunc(8)
|
| 151 |
+
cgen = cr(8)
|
| 152 |
+
self.check_generator(pygen, cgen)
|
| 153 |
+
|
| 154 |
+
def test_gen1(self):
|
| 155 |
+
self.check_gen1(**nopython_flags)
|
| 156 |
+
|
| 157 |
+
def test_gen1_objmode(self):
|
| 158 |
+
self.check_gen1(**forceobj_flags)
|
| 159 |
+
|
| 160 |
+
def check_gen2(self, **kwargs):
|
| 161 |
+
pyfunc = gen2
|
| 162 |
+
cr = jit((types.int32,), **kwargs)(pyfunc)
|
| 163 |
+
pygen = pyfunc(8)
|
| 164 |
+
cgen = cr(8)
|
| 165 |
+
self.check_generator(pygen, cgen)
|
| 166 |
+
|
| 167 |
+
def test_gen2(self):
|
| 168 |
+
self.check_gen2(**nopython_flags)
|
| 169 |
+
|
| 170 |
+
def test_gen2_objmode(self):
|
| 171 |
+
self.check_gen2(**forceobj_flags)
|
| 172 |
+
|
| 173 |
+
def check_gen3(self, **kwargs):
|
| 174 |
+
pyfunc = gen3
|
| 175 |
+
cr = jit((types.int32,), **kwargs)(pyfunc)
|
| 176 |
+
pygen = pyfunc(8)
|
| 177 |
+
cgen = cr(8)
|
| 178 |
+
self.check_generator(pygen, cgen)
|
| 179 |
+
|
| 180 |
+
def test_gen3(self):
|
| 181 |
+
self.check_gen3(**nopython_flags)
|
| 182 |
+
|
| 183 |
+
def test_gen3_objmode(self):
|
| 184 |
+
self.check_gen3(**forceobj_flags)
|
| 185 |
+
|
| 186 |
+
def check_gen4(self, **kwargs):
|
| 187 |
+
pyfunc = gen4
|
| 188 |
+
cr = jit((types.int32,) * 3, **kwargs)(pyfunc)
|
| 189 |
+
pygen = pyfunc(5, 6, 7)
|
| 190 |
+
cgen = cr(5, 6, 7)
|
| 191 |
+
self.check_generator(pygen, cgen)
|
| 192 |
+
|
| 193 |
+
def test_gen4(self):
|
| 194 |
+
self.check_gen4(**nopython_flags)
|
| 195 |
+
|
| 196 |
+
def test_gen4_objmode(self):
|
| 197 |
+
self.check_gen4(**forceobj_flags)
|
| 198 |
+
|
| 199 |
+
def test_gen5(self):
|
| 200 |
+
with self.assertTypingError() as raises:
|
| 201 |
+
jit((), **nopython_flags)(gen5)
|
| 202 |
+
self.assertIn("Cannot type generator: it does not yield any value",
|
| 203 |
+
str(raises.exception))
|
| 204 |
+
|
| 205 |
+
def test_gen5_objmode(self):
|
| 206 |
+
cgen = jit((), **forceobj_flags)(gen5)()
|
| 207 |
+
self.assertEqual(list(cgen), [])
|
| 208 |
+
with self.assertRaises(StopIteration):
|
| 209 |
+
next(cgen)
|
| 210 |
+
|
| 211 |
+
def check_gen6(self, **kwargs):
|
| 212 |
+
cr = jit((types.int32,) * 2, **kwargs)(gen6)
|
| 213 |
+
cgen = cr(5, 6)
|
| 214 |
+
l = []
|
| 215 |
+
for i in range(3):
|
| 216 |
+
l.append(next(cgen))
|
| 217 |
+
self.assertEqual(l, [14] * 3)
|
| 218 |
+
|
| 219 |
+
def test_gen6(self):
|
| 220 |
+
self.check_gen6(**nopython_flags)
|
| 221 |
+
|
| 222 |
+
def test_gen6_objmode(self):
|
| 223 |
+
self.check_gen6(**forceobj_flags)
|
| 224 |
+
|
| 225 |
+
def check_gen7(self, **kwargs):
|
| 226 |
+
pyfunc = gen7
|
| 227 |
+
cr = jit((types.Array(types.float64, 1, 'C'),), **kwargs)(pyfunc)
|
| 228 |
+
arr = np.linspace(1, 10, 7)
|
| 229 |
+
pygen = pyfunc(arr.copy())
|
| 230 |
+
cgen = cr(arr)
|
| 231 |
+
self.check_generator(pygen, cgen)
|
| 232 |
+
|
| 233 |
+
def test_gen7(self):
|
| 234 |
+
self.check_gen7(**nopython_flags)
|
| 235 |
+
|
| 236 |
+
def test_gen7_objmode(self):
|
| 237 |
+
self.check_gen7(**forceobj_flags)
|
| 238 |
+
|
| 239 |
+
def check_gen8(self, **jit_args):
|
| 240 |
+
pyfunc = gen8
|
| 241 |
+
cfunc = jit(**jit_args)(pyfunc)
|
| 242 |
+
|
| 243 |
+
def check(*args, **kwargs):
|
| 244 |
+
self.check_generator(pyfunc(*args, **kwargs),
|
| 245 |
+
cfunc(*args, **kwargs))
|
| 246 |
+
|
| 247 |
+
check(2, 3)
|
| 248 |
+
check(4)
|
| 249 |
+
check(y=5)
|
| 250 |
+
check(x=6, b=True)
|
| 251 |
+
|
| 252 |
+
def test_gen8(self):
|
| 253 |
+
self.check_gen8(nopython=True)
|
| 254 |
+
|
| 255 |
+
def test_gen8_objmode(self):
|
| 256 |
+
self.check_gen8(forceobj=True)
|
| 257 |
+
|
| 258 |
+
def check_gen9(self, **kwargs):
|
| 259 |
+
pyfunc = gen_bool
|
| 260 |
+
cr = jit((), **kwargs)(pyfunc)
|
| 261 |
+
pygen = pyfunc()
|
| 262 |
+
cgen = cr()
|
| 263 |
+
self.check_generator(pygen, cgen)
|
| 264 |
+
|
| 265 |
+
def test_gen9(self):
|
| 266 |
+
self.check_gen9(**nopython_flags)
|
| 267 |
+
|
| 268 |
+
def test_gen9_objmode(self):
|
| 269 |
+
self.check_gen9(**forceobj_flags)
|
| 270 |
+
|
| 271 |
+
def check_consume_generator(self, gen_func):
|
| 272 |
+
cgen = jit(nopython=True)(gen_func)
|
| 273 |
+
cfunc = jit(nopython=True)(make_consumer(cgen))
|
| 274 |
+
pyfunc = make_consumer(gen_func)
|
| 275 |
+
expected = pyfunc(5)
|
| 276 |
+
got = cfunc(5)
|
| 277 |
+
self.assertPreciseEqual(got, expected)
|
| 278 |
+
|
| 279 |
+
def test_consume_gen1(self):
|
| 280 |
+
self.check_consume_generator(gen1)
|
| 281 |
+
|
| 282 |
+
def test_consume_gen2(self):
|
| 283 |
+
self.check_consume_generator(gen2)
|
| 284 |
+
|
| 285 |
+
def test_consume_gen3(self):
|
| 286 |
+
self.check_consume_generator(gen3)
|
| 287 |
+
|
| 288 |
+
# Check generator storage of some types
|
| 289 |
+
|
| 290 |
+
def check_ndindex(self, **kwargs):
|
| 291 |
+
pyfunc = gen_ndindex
|
| 292 |
+
cr = jit((types.UniTuple(types.intp, 2),), **kwargs)(pyfunc)
|
| 293 |
+
shape = (2, 3)
|
| 294 |
+
pygen = pyfunc(shape)
|
| 295 |
+
cgen = cr(shape)
|
| 296 |
+
self.check_generator(pygen, cgen)
|
| 297 |
+
|
| 298 |
+
def test_ndindex(self):
|
| 299 |
+
self.check_ndindex(**nopython_flags)
|
| 300 |
+
|
| 301 |
+
def test_ndindex_objmode(self):
|
| 302 |
+
self.check_ndindex(**forceobj_flags)
|
| 303 |
+
|
| 304 |
+
def check_np_flat(self, pyfunc, **kwargs):
|
| 305 |
+
cr = jit((types.Array(types.int32, 2, "C"),), **kwargs)(pyfunc)
|
| 306 |
+
arr = np.arange(6, dtype=np.int32).reshape((2, 3))
|
| 307 |
+
self.check_generator(pyfunc(arr), cr(arr))
|
| 308 |
+
crA = jit((types.Array(types.int32, 2, "A"),), **kwargs)(pyfunc)
|
| 309 |
+
arr = arr.T
|
| 310 |
+
self.check_generator(pyfunc(arr), crA(arr))
|
| 311 |
+
|
| 312 |
+
def test_np_flat(self):
|
| 313 |
+
self.check_np_flat(gen_flat, **nopython_flags)
|
| 314 |
+
|
| 315 |
+
def test_np_flat_objmode(self):
|
| 316 |
+
self.check_np_flat(gen_flat, **forceobj_flags)
|
| 317 |
+
|
| 318 |
+
def test_ndenumerate(self):
|
| 319 |
+
self.check_np_flat(gen_ndenumerate, **nopython_flags)
|
| 320 |
+
|
| 321 |
+
def test_ndenumerate_objmode(self):
|
| 322 |
+
self.check_np_flat(gen_ndenumerate, **forceobj_flags)
|
| 323 |
+
|
| 324 |
+
def test_type_unification_error(self):
|
| 325 |
+
pyfunc = gen_unification_error
|
| 326 |
+
with self.assertTypingError() as raises:
|
| 327 |
+
jit((), **nopython_flags)(pyfunc)
|
| 328 |
+
|
| 329 |
+
msg = ("Can't unify yield type from the following types: complex128, "
|
| 330 |
+
"none")
|
| 331 |
+
self.assertIn(msg, str(raises.exception))
|
| 332 |
+
|
| 333 |
+
def test_optional_expansion_type_unification_error(self):
|
| 334 |
+
pyfunc = gen_optional_and_type_unification_error
|
| 335 |
+
with self.assertTypingError() as raises:
|
| 336 |
+
jit((), **nopython_flags)(pyfunc)
|
| 337 |
+
|
| 338 |
+
msg = ("Can't unify yield type from the following types: complex128, "
|
| 339 |
+
"int%s, none")
|
| 340 |
+
self.assertIn(msg % types.intp.bitwidth, str(raises.exception))
|
| 341 |
+
|
| 342 |
+
def test_changing_tuple_type(self):
|
| 343 |
+
# test https://github.com/numba/numba/issues/7295
|
| 344 |
+
pyfunc = gen_changing_tuple_type
|
| 345 |
+
expected = list(pyfunc())
|
| 346 |
+
got = list(njit(pyfunc)())
|
| 347 |
+
self.assertEqual(expected, got)
|
| 348 |
+
|
| 349 |
+
def test_changing_number_type(self):
|
| 350 |
+
# additional test for https://github.com/numba/numba/issues/7295
|
| 351 |
+
pyfunc = gen_changing_number_type
|
| 352 |
+
expected = list(pyfunc())
|
| 353 |
+
got = list(njit(pyfunc)())
|
| 354 |
+
self.assertEqual(expected, got)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def nrt_gen0(ary):
|
| 358 |
+
for elem in ary:
|
| 359 |
+
yield elem
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def nrt_gen1(ary1, ary2):
|
| 363 |
+
for e1, e2 in zip(ary1, ary2):
|
| 364 |
+
yield e1
|
| 365 |
+
yield e2
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
class TestNrtArrayGen(MemoryLeakMixin, TestCase):
|
| 369 |
+
def test_nrt_gen0(self):
|
| 370 |
+
pygen = nrt_gen0
|
| 371 |
+
cgen = jit(nopython=True)(pygen)
|
| 372 |
+
|
| 373 |
+
py_ary = np.arange(10)
|
| 374 |
+
c_ary = py_ary.copy()
|
| 375 |
+
|
| 376 |
+
py_res = list(pygen(py_ary))
|
| 377 |
+
c_res = list(cgen(c_ary))
|
| 378 |
+
|
| 379 |
+
np.testing.assert_equal(py_ary, c_ary)
|
| 380 |
+
self.assertEqual(py_res, c_res)
|
| 381 |
+
# Check reference count
|
| 382 |
+
self.assertRefCountEqual(py_ary, c_ary)
|
| 383 |
+
|
| 384 |
+
def test_nrt_gen1(self):
|
| 385 |
+
pygen = nrt_gen1
|
| 386 |
+
cgen = jit(nopython=True)(pygen)
|
| 387 |
+
|
| 388 |
+
py_ary1 = np.arange(10)
|
| 389 |
+
py_ary2 = py_ary1 + 100
|
| 390 |
+
|
| 391 |
+
c_ary1 = py_ary1.copy()
|
| 392 |
+
c_ary2 = py_ary2.copy()
|
| 393 |
+
|
| 394 |
+
py_res = list(pygen(py_ary1, py_ary2))
|
| 395 |
+
c_res = list(cgen(c_ary1, c_ary2))
|
| 396 |
+
|
| 397 |
+
np.testing.assert_equal(py_ary1, c_ary1)
|
| 398 |
+
np.testing.assert_equal(py_ary2, c_ary2)
|
| 399 |
+
self.assertEqual(py_res, c_res)
|
| 400 |
+
# Check reference count
|
| 401 |
+
self.assertRefCountEqual(py_ary1, c_ary1)
|
| 402 |
+
self.assertRefCountEqual(py_ary2, c_ary2)
|
| 403 |
+
|
| 404 |
+
def test_combine_gen0_gen1(self):
|
| 405 |
+
"""
|
| 406 |
+
Issue #1163 is observed when two generator with NRT object arguments
|
| 407 |
+
is ran in sequence. The first one does a invalid free and corrupts
|
| 408 |
+
the NRT memory subsystem. The second generator is likely to segfault
|
| 409 |
+
due to corrupted NRT data structure (an invalid MemInfo).
|
| 410 |
+
"""
|
| 411 |
+
self.test_nrt_gen0()
|
| 412 |
+
self.test_nrt_gen1()
|
| 413 |
+
|
| 414 |
+
def test_nrt_gen0_stop_iteration(self):
|
| 415 |
+
"""
|
| 416 |
+
Test cleanup on StopIteration
|
| 417 |
+
"""
|
| 418 |
+
pygen = nrt_gen0
|
| 419 |
+
cgen = jit(nopython=True)(pygen)
|
| 420 |
+
|
| 421 |
+
py_ary = np.arange(1)
|
| 422 |
+
c_ary = py_ary.copy()
|
| 423 |
+
|
| 424 |
+
py_iter = pygen(py_ary)
|
| 425 |
+
c_iter = cgen(c_ary)
|
| 426 |
+
|
| 427 |
+
py_res = next(py_iter)
|
| 428 |
+
c_res = next(c_iter)
|
| 429 |
+
|
| 430 |
+
with self.assertRaises(StopIteration):
|
| 431 |
+
py_res = next(py_iter)
|
| 432 |
+
|
| 433 |
+
with self.assertRaises(StopIteration):
|
| 434 |
+
c_res = next(c_iter)
|
| 435 |
+
|
| 436 |
+
del py_iter
|
| 437 |
+
del c_iter
|
| 438 |
+
|
| 439 |
+
np.testing.assert_equal(py_ary, c_ary)
|
| 440 |
+
self.assertEqual(py_res, c_res)
|
| 441 |
+
# Check reference count
|
| 442 |
+
self.assertRefCountEqual(py_ary, c_ary)
|
| 443 |
+
|
| 444 |
+
def test_nrt_gen0_no_iter(self):
|
| 445 |
+
"""
|
| 446 |
+
Test cleanup for a initialized but never iterated (never call next())
|
| 447 |
+
generator.
|
| 448 |
+
"""
|
| 449 |
+
pygen = nrt_gen0
|
| 450 |
+
cgen = jit(nopython=True)(pygen)
|
| 451 |
+
|
| 452 |
+
py_ary = np.arange(1)
|
| 453 |
+
c_ary = py_ary.copy()
|
| 454 |
+
|
| 455 |
+
py_iter = pygen(py_ary)
|
| 456 |
+
c_iter = cgen(c_ary)
|
| 457 |
+
|
| 458 |
+
del py_iter
|
| 459 |
+
del c_iter
|
| 460 |
+
|
| 461 |
+
np.testing.assert_equal(py_ary, c_ary)
|
| 462 |
+
|
| 463 |
+
# Check reference count
|
| 464 |
+
self.assertRefCountEqual(py_ary, c_ary)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
# TODO: fix nested generator and MemoryLeakMixin
|
| 468 |
+
class TestNrtNestedGen(TestCase):
|
| 469 |
+
def test_nrt_nested_gen(self):
|
| 470 |
+
|
| 471 |
+
def gen0(arr):
|
| 472 |
+
for i in range(arr.size):
|
| 473 |
+
yield arr
|
| 474 |
+
|
| 475 |
+
def factory(gen0):
|
| 476 |
+
def gen1(arr):
|
| 477 |
+
out = np.zeros_like(arr)
|
| 478 |
+
for x in gen0(arr):
|
| 479 |
+
out = out + x
|
| 480 |
+
return out, arr
|
| 481 |
+
|
| 482 |
+
return gen1
|
| 483 |
+
|
| 484 |
+
py_arr = np.arange(10)
|
| 485 |
+
c_arr = py_arr.copy()
|
| 486 |
+
py_res, py_old = factory(gen0)(py_arr)
|
| 487 |
+
c_gen = jit(nopython=True)(factory(jit(nopython=True)(gen0)))
|
| 488 |
+
c_res, c_old = c_gen(c_arr)
|
| 489 |
+
|
| 490 |
+
self.assertIsNot(py_arr, c_arr)
|
| 491 |
+
self.assertIs(py_old, py_arr)
|
| 492 |
+
self.assertIs(c_old, c_arr)
|
| 493 |
+
|
| 494 |
+
np.testing.assert_equal(py_res, c_res)
|
| 495 |
+
|
| 496 |
+
self.assertRefCountEqual(py_res, c_res)
|
| 497 |
+
|
| 498 |
+
# The below test will fail due to generator finalizer not invoked.
|
| 499 |
+
# This kept a reference of the c_old.
|
| 500 |
+
#
|
| 501 |
+
# self.assertEqual(sys.getrefcount(py_old),
|
| 502 |
+
# sys.getrefcount(c_old))
|
| 503 |
+
|
| 504 |
+
@unittest.expectedFailure
|
| 505 |
+
def test_nrt_nested_gen_refct(self):
|
| 506 |
+
def gen0(arr):
|
| 507 |
+
yield arr
|
| 508 |
+
|
| 509 |
+
def factory(gen0):
|
| 510 |
+
def gen1(arr):
|
| 511 |
+
for out in gen0(arr):
|
| 512 |
+
return out
|
| 513 |
+
|
| 514 |
+
return gen1
|
| 515 |
+
|
| 516 |
+
py_arr = np.arange(10)
|
| 517 |
+
c_arr = py_arr.copy()
|
| 518 |
+
py_old = factory(gen0)(py_arr)
|
| 519 |
+
c_gen = jit(nopython=True)(factory(jit(nopython=True)(gen0)))
|
| 520 |
+
c_old = c_gen(c_arr)
|
| 521 |
+
|
| 522 |
+
self.assertIsNot(py_arr, c_arr)
|
| 523 |
+
self.assertIs(py_old, py_arr)
|
| 524 |
+
self.assertIs(c_old, c_arr)
|
| 525 |
+
|
| 526 |
+
self.assertRefCountEqual(py_old, c_old)
|
| 527 |
+
|
| 528 |
+
def test_nrt_nested_nopython_gen(self):
|
| 529 |
+
"""
|
| 530 |
+
Test nesting three generators
|
| 531 |
+
"""
|
| 532 |
+
|
| 533 |
+
def factory(decor=lambda x: x):
|
| 534 |
+
@decor
|
| 535 |
+
def foo(a, n):
|
| 536 |
+
for i in range(n):
|
| 537 |
+
yield a[i]
|
| 538 |
+
a[i] += i
|
| 539 |
+
|
| 540 |
+
@decor
|
| 541 |
+
def bar(n):
|
| 542 |
+
a = np.arange(n)
|
| 543 |
+
for i in foo(a, n):
|
| 544 |
+
yield i * 2
|
| 545 |
+
for i in range(a.size):
|
| 546 |
+
yield a[i]
|
| 547 |
+
|
| 548 |
+
@decor
|
| 549 |
+
def cat(n):
|
| 550 |
+
for i in bar(n):
|
| 551 |
+
yield i + i
|
| 552 |
+
|
| 553 |
+
return cat
|
| 554 |
+
|
| 555 |
+
py_gen = factory()
|
| 556 |
+
c_gen = factory(jit(nopython=True))
|
| 557 |
+
|
| 558 |
+
py_res = list(py_gen(10))
|
| 559 |
+
c_res = list(c_gen(10))
|
| 560 |
+
|
| 561 |
+
self.assertEqual(py_res, c_res)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class TestGeneratorWithNRT(MemoryLeakMixin, TestCase):
|
| 565 |
+
def test_issue_1254(self):
|
| 566 |
+
"""
|
| 567 |
+
Missing environment for returning array
|
| 568 |
+
"""
|
| 569 |
+
|
| 570 |
+
@jit(nopython=True)
|
| 571 |
+
def random_directions(n):
|
| 572 |
+
for i in range(n):
|
| 573 |
+
vec = np.empty(3)
|
| 574 |
+
vec[:] = 12
|
| 575 |
+
yield vec
|
| 576 |
+
|
| 577 |
+
outputs = list(random_directions(5))
|
| 578 |
+
self.assertEqual(len(outputs), 5)
|
| 579 |
+
|
| 580 |
+
expect = np.empty(3)
|
| 581 |
+
expect[:] = 12
|
| 582 |
+
for got in outputs:
|
| 583 |
+
np.testing.assert_equal(expect, got)
|
| 584 |
+
|
| 585 |
+
def test_issue_1265(self):
|
| 586 |
+
"""
|
| 587 |
+
Double-free for locally allocated, non escaping NRT objects
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
def py_gen(rmin, rmax, nr):
|
| 591 |
+
a = np.linspace(rmin, rmax, nr)
|
| 592 |
+
yield a[0]
|
| 593 |
+
yield a[1]
|
| 594 |
+
|
| 595 |
+
c_gen = jit(nopython=True)(py_gen)
|
| 596 |
+
|
| 597 |
+
py_res = list(py_gen(-2, 2, 100))
|
| 598 |
+
c_res = list(c_gen(-2, 2, 100))
|
| 599 |
+
|
| 600 |
+
self.assertEqual(py_res, c_res)
|
| 601 |
+
|
| 602 |
+
def py_driver(args):
|
| 603 |
+
rmin, rmax, nr = args
|
| 604 |
+
points = np.empty(nr, dtype=np.complex128)
|
| 605 |
+
for i, c in enumerate(py_gen(rmin, rmax, nr)):
|
| 606 |
+
points[i] = c
|
| 607 |
+
|
| 608 |
+
return points
|
| 609 |
+
|
| 610 |
+
@jit(nopython=True)
|
| 611 |
+
def c_driver(args):
|
| 612 |
+
rmin, rmax, nr = args
|
| 613 |
+
points = np.empty(nr, dtype=np.complex128)
|
| 614 |
+
for i, c in enumerate(c_gen(rmin, rmax, nr)):
|
| 615 |
+
points[i] = c
|
| 616 |
+
|
| 617 |
+
return points
|
| 618 |
+
|
| 619 |
+
n = 2
|
| 620 |
+
patches = (-2, -1, n)
|
| 621 |
+
|
| 622 |
+
py_res = py_driver(patches)
|
| 623 |
+
# The error will cause a segfault here
|
| 624 |
+
c_res = c_driver(patches)
|
| 625 |
+
|
| 626 |
+
np.testing.assert_equal(py_res, c_res)
|
| 627 |
+
|
| 628 |
+
def test_issue_1808(self):
|
| 629 |
+
"""
|
| 630 |
+
Incorrect return data model
|
| 631 |
+
"""
|
| 632 |
+
magic = 0xdeadbeef
|
| 633 |
+
|
| 634 |
+
@njit
|
| 635 |
+
def generator():
|
| 636 |
+
yield magic
|
| 637 |
+
|
| 638 |
+
@njit
|
| 639 |
+
def get_generator():
|
| 640 |
+
return generator()
|
| 641 |
+
|
| 642 |
+
@njit
|
| 643 |
+
def main():
|
| 644 |
+
out = 0
|
| 645 |
+
for x in get_generator():
|
| 646 |
+
out += x
|
| 647 |
+
|
| 648 |
+
return out
|
| 649 |
+
|
| 650 |
+
self.assertEqual(main(), magic)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class TestGeneratorModel(test_factory()):
|
| 654 |
+
fe_type = types.Generator(gen_func=None, yield_type=types.int32,
|
| 655 |
+
arg_types=[types.int64, types.float32],
|
| 656 |
+
state_types=[types.intp, types.intp[::1]],
|
| 657 |
+
has_finalizer=False)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
if __name__ == '__main__':
|
| 661 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_help.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import subprocess
|
| 3 |
+
import types as pytypes
|
| 4 |
+
import os.path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
import builtins
|
| 9 |
+
from numba.core import types
|
| 10 |
+
from numba.tests.support import TestCase, temp_directory
|
| 11 |
+
from numba.misc.help.inspector import inspect_function, inspect_module
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestInspector(TestCase):
|
| 15 |
+
def check_function_descriptor(self, info, must_be_defined=False):
|
| 16 |
+
self.assertIsInstance(info, dict)
|
| 17 |
+
self.assertIn('numba_type', info)
|
| 18 |
+
numba_type = info['numba_type']
|
| 19 |
+
if numba_type is None:
|
| 20 |
+
self.assertFalse(must_be_defined)
|
| 21 |
+
else:
|
| 22 |
+
self.assertIsInstance(numba_type, types.Type)
|
| 23 |
+
self.assertIn('explained', info)
|
| 24 |
+
self.assertIsInstance(info['explained'], str)
|
| 25 |
+
self.assertIn('source_infos', info)
|
| 26 |
+
self.assertIsInstance(info['source_infos'], dict)
|
| 27 |
+
|
| 28 |
+
def test_inspect_function_on_range(self):
|
| 29 |
+
info = inspect_function(range)
|
| 30 |
+
self.check_function_descriptor(info, must_be_defined=True)
|
| 31 |
+
|
| 32 |
+
def test_inspect_function_on_np_all(self):
|
| 33 |
+
info = inspect_function(np.all)
|
| 34 |
+
self.check_function_descriptor(info, must_be_defined=True)
|
| 35 |
+
source_infos = info['source_infos']
|
| 36 |
+
self.assertGreater(len(source_infos), 0)
|
| 37 |
+
c = 0
|
| 38 |
+
for srcinfo in source_infos.values():
|
| 39 |
+
self.assertIsInstance(srcinfo['kind'], str)
|
| 40 |
+
self.assertIsInstance(srcinfo['name'], str)
|
| 41 |
+
self.assertIsInstance(srcinfo['sig'], str)
|
| 42 |
+
self.assertIsInstance(srcinfo['filename'], str)
|
| 43 |
+
self.assertIsInstance(srcinfo['lines'], tuple)
|
| 44 |
+
self.assertIn('docstring', srcinfo)
|
| 45 |
+
c += 1
|
| 46 |
+
self.assertEqual(c, len(source_infos))
|
| 47 |
+
|
| 48 |
+
def test_inspect_module(self):
|
| 49 |
+
c = 0
|
| 50 |
+
for it in inspect_module(builtins):
|
| 51 |
+
self.assertIsInstance(it['module'], pytypes.ModuleType)
|
| 52 |
+
self.assertIsInstance(it['name'], str)
|
| 53 |
+
self.assertTrue(callable(it['obj']))
|
| 54 |
+
self.check_function_descriptor(it)
|
| 55 |
+
c += 1
|
| 56 |
+
self.assertGreater(c, 0)
|
| 57 |
+
|
| 58 |
+
def test_inspect_cli(self):
|
| 59 |
+
# Try CLI on math module
|
| 60 |
+
cmdbase = [sys.executable, '-m', 'numba.misc.help.inspector']
|
| 61 |
+
|
| 62 |
+
dirpath = temp_directory('{}.{}'.format(__name__,
|
| 63 |
+
self.__class__.__name__))
|
| 64 |
+
filename = os.path.join(dirpath, 'out')
|
| 65 |
+
|
| 66 |
+
# Try default format "html"
|
| 67 |
+
expected_file = filename + '.html'
|
| 68 |
+
cmds = cmdbase + ['--file', filename, 'math']
|
| 69 |
+
# File shouldn't exist yet
|
| 70 |
+
self.assertFalse(os.path.isfile(expected_file))
|
| 71 |
+
# Run CLI
|
| 72 |
+
subprocess.check_output(cmds)
|
| 73 |
+
# File should exist now
|
| 74 |
+
self.assertTrue(os.path.isfile(expected_file))
|
| 75 |
+
|
| 76 |
+
# Try changing the format to "rst"
|
| 77 |
+
cmds = cmdbase + ['--file', filename, '--format', 'rst', 'math']
|
| 78 |
+
expected_file = filename + '.rst'
|
| 79 |
+
# File shouldn't exist yet
|
| 80 |
+
self.assertFalse(os.path.isfile(expected_file))
|
| 81 |
+
# Run CLI
|
| 82 |
+
subprocess.check_output(cmds)
|
| 83 |
+
# File should exist now
|
| 84 |
+
self.assertTrue(os.path.isfile(expected_file))
|
| 85 |
+
|
| 86 |
+
# Try unsupported format
|
| 87 |
+
cmds = cmdbase + ['--file', filename, '--format', 'foo', 'math']
|
| 88 |
+
# Run CLI
|
| 89 |
+
with self.assertRaises(subprocess.CalledProcessError) as raises:
|
| 90 |
+
subprocess.check_output(cmds, stderr=subprocess.STDOUT)
|
| 91 |
+
self.assertIn("\'foo\' is not supported",
|
| 92 |
+
raises.exception.stdout.decode())
|
lib/python3.10/site-packages/numba/tests/test_interpreter.py
ADDED
|
@@ -0,0 +1,1154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test bytecode fixes provided in interpreter.py
|
| 3 |
+
"""
|
| 4 |
+
import unittest
|
| 5 |
+
from numba import jit, njit, objmode, typeof, literally
|
| 6 |
+
from numba.extending import overload
|
| 7 |
+
from numba.core import types
|
| 8 |
+
from numba.core.errors import UnsupportedBytecodeError
|
| 9 |
+
from numba.tests.support import (
|
| 10 |
+
TestCase,
|
| 11 |
+
MemoryLeakMixin,
|
| 12 |
+
skip_unless_py10_or_later,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@njit
|
| 17 |
+
def sum_jit_func(
|
| 18 |
+
arg0=0,
|
| 19 |
+
arg1=0,
|
| 20 |
+
arg2=0,
|
| 21 |
+
arg3=0,
|
| 22 |
+
arg4=0,
|
| 23 |
+
arg5=0,
|
| 24 |
+
arg6=0,
|
| 25 |
+
arg7=0,
|
| 26 |
+
arg8=0,
|
| 27 |
+
arg9=0,
|
| 28 |
+
arg10=0,
|
| 29 |
+
arg11=0,
|
| 30 |
+
arg12=0,
|
| 31 |
+
arg13=0,
|
| 32 |
+
arg14=0,
|
| 33 |
+
arg15=0,
|
| 34 |
+
arg16=0,
|
| 35 |
+
arg17=0,
|
| 36 |
+
arg18=0,
|
| 37 |
+
arg19=0,
|
| 38 |
+
arg20=0,
|
| 39 |
+
arg21=0,
|
| 40 |
+
arg22=0,
|
| 41 |
+
arg23=0,
|
| 42 |
+
arg24=0,
|
| 43 |
+
arg25=0,
|
| 44 |
+
arg26=0,
|
| 45 |
+
arg27=0,
|
| 46 |
+
arg28=0,
|
| 47 |
+
arg29=0,
|
| 48 |
+
arg30=0,
|
| 49 |
+
arg31=0,
|
| 50 |
+
arg32=0,
|
| 51 |
+
arg33=0,
|
| 52 |
+
arg34=0,
|
| 53 |
+
arg35=0,
|
| 54 |
+
arg36=0,
|
| 55 |
+
arg37=0,
|
| 56 |
+
arg38=0,
|
| 57 |
+
arg39=0,
|
| 58 |
+
arg40=0,
|
| 59 |
+
arg41=0,
|
| 60 |
+
arg42=0,
|
| 61 |
+
arg43=0,
|
| 62 |
+
arg44=0,
|
| 63 |
+
arg45=0,
|
| 64 |
+
arg46=0,
|
| 65 |
+
):
|
| 66 |
+
return (
|
| 67 |
+
arg0
|
| 68 |
+
+ arg1
|
| 69 |
+
+ arg2
|
| 70 |
+
+ arg3
|
| 71 |
+
+ arg4
|
| 72 |
+
+ arg5
|
| 73 |
+
+ arg6
|
| 74 |
+
+ arg7
|
| 75 |
+
+ arg8
|
| 76 |
+
+ arg9
|
| 77 |
+
+ arg10
|
| 78 |
+
+ arg11
|
| 79 |
+
+ arg12
|
| 80 |
+
+ arg13
|
| 81 |
+
+ arg14
|
| 82 |
+
+ arg15
|
| 83 |
+
+ arg16
|
| 84 |
+
+ arg17
|
| 85 |
+
+ arg18
|
| 86 |
+
+ arg19
|
| 87 |
+
+ arg20
|
| 88 |
+
+ arg21
|
| 89 |
+
+ arg22
|
| 90 |
+
+ arg23
|
| 91 |
+
+ arg24
|
| 92 |
+
+ arg25
|
| 93 |
+
+ arg26
|
| 94 |
+
+ arg27
|
| 95 |
+
+ arg28
|
| 96 |
+
+ arg29
|
| 97 |
+
+ arg30
|
| 98 |
+
+ arg31
|
| 99 |
+
+ arg32
|
| 100 |
+
+ arg33
|
| 101 |
+
+ arg34
|
| 102 |
+
+ arg35
|
| 103 |
+
+ arg36
|
| 104 |
+
+ arg37
|
| 105 |
+
+ arg38
|
| 106 |
+
+ arg39
|
| 107 |
+
+ arg40
|
| 108 |
+
+ arg41
|
| 109 |
+
+ arg42
|
| 110 |
+
+ arg43
|
| 111 |
+
+ arg44
|
| 112 |
+
+ arg45
|
| 113 |
+
+ arg46
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TestCallFunctionExPeepHole(MemoryLeakMixin, TestCase):
|
| 118 |
+
"""
|
| 119 |
+
gh #7812
|
| 120 |
+
|
| 121 |
+
Tests that check a peephole optimization for Function calls
|
| 122 |
+
in Python 3.10. The bytecode changes when
|
| 123 |
+
(n_args / 2) + n_kws > 15, which moves the arguments from
|
| 124 |
+
the stack into a tuple and dictionary.
|
| 125 |
+
|
| 126 |
+
This peephole optimization updates the IR to use the original format.
|
| 127 |
+
There are different paths when n_args > 30 and n_args <= 30 and when
|
| 128 |
+
n_kws > 15 and n_kws <= 15.
|
| 129 |
+
"""
|
| 130 |
+
THRESHOLD_ARGS = 31
|
| 131 |
+
THRESHOLD_KWS = 16
|
| 132 |
+
|
| 133 |
+
def gen_func(self, n_args, n_kws):
|
| 134 |
+
"""
|
| 135 |
+
Generates a function that calls sum_jit_func
|
| 136 |
+
with the desired number of args and kws.
|
| 137 |
+
"""
|
| 138 |
+
param_list = [f"arg{i}" for i in range(n_args + n_kws)]
|
| 139 |
+
args_list = []
|
| 140 |
+
for i in range(n_args + n_kws):
|
| 141 |
+
# Call a function on every 5th argument to ensure
|
| 142 |
+
# we test function calls.
|
| 143 |
+
if i % 5 == 0:
|
| 144 |
+
arg_val = f"pow(arg{i}, 2)"
|
| 145 |
+
else:
|
| 146 |
+
arg_val = f"arg{i}"
|
| 147 |
+
args_list.append(arg_val)
|
| 148 |
+
total_params = ", ".join(param_list)
|
| 149 |
+
func_text = f"def impl({total_params}):\n"
|
| 150 |
+
func_text += " return sum_jit_func(\n"
|
| 151 |
+
for i in range(n_args):
|
| 152 |
+
func_text += f" {args_list[i]},\n"
|
| 153 |
+
for i in range(n_args, n_args + n_kws):
|
| 154 |
+
func_text += f" {param_list[i]}={args_list[i]},\n"
|
| 155 |
+
func_text += " )\n"
|
| 156 |
+
local_vars = {}
|
| 157 |
+
exec(func_text, {"sum_jit_func": sum_jit_func}, local_vars)
|
| 158 |
+
return local_vars["impl"]
|
| 159 |
+
|
| 160 |
+
@skip_unless_py10_or_later
|
| 161 |
+
def test_all_args(self):
|
| 162 |
+
"""
|
| 163 |
+
Tests calling a function when n_args > 30 and
|
| 164 |
+
n_kws = 0. This shouldn't use the peephole, but
|
| 165 |
+
it should still succeed.
|
| 166 |
+
"""
|
| 167 |
+
total_args = [i for i in range(self.THRESHOLD_ARGS)]
|
| 168 |
+
f = self.gen_func(self.THRESHOLD_ARGS, 0)
|
| 169 |
+
py_func = f
|
| 170 |
+
cfunc = njit()(f)
|
| 171 |
+
a = py_func(*total_args)
|
| 172 |
+
b = cfunc(*total_args)
|
| 173 |
+
self.assertEqual(a, b)
|
| 174 |
+
|
| 175 |
+
@skip_unless_py10_or_later
|
| 176 |
+
def test_all_kws(self):
|
| 177 |
+
"""
|
| 178 |
+
Tests calling a function when n_kws > 15 and
|
| 179 |
+
n_args = 0.
|
| 180 |
+
"""
|
| 181 |
+
total_args = [i for i in range(self.THRESHOLD_KWS)]
|
| 182 |
+
f = self.gen_func(0, self.THRESHOLD_KWS)
|
| 183 |
+
py_func = f
|
| 184 |
+
cfunc = njit()(f)
|
| 185 |
+
a = py_func(*total_args)
|
| 186 |
+
b = cfunc(*total_args)
|
| 187 |
+
self.assertEqual(a, b)
|
| 188 |
+
|
| 189 |
+
@skip_unless_py10_or_later
|
| 190 |
+
def test_small_args_small_kws(self):
|
| 191 |
+
"""
|
| 192 |
+
Tests calling a function when (n_args / 2) + n_kws > 15,
|
| 193 |
+
but n_args <= 30 and n_kws <= 15
|
| 194 |
+
"""
|
| 195 |
+
used_args = self.THRESHOLD_ARGS - 1
|
| 196 |
+
used_kws = self.THRESHOLD_KWS - 1
|
| 197 |
+
total_args = [i for i in range((used_args) + (used_kws))]
|
| 198 |
+
f = self.gen_func(used_args, used_kws)
|
| 199 |
+
py_func = f
|
| 200 |
+
cfunc = njit()(f)
|
| 201 |
+
a = py_func(*total_args)
|
| 202 |
+
b = cfunc(*total_args)
|
| 203 |
+
self.assertEqual(a, b)
|
| 204 |
+
|
| 205 |
+
@skip_unless_py10_or_later
|
| 206 |
+
def test_small_args_large_kws(self):
|
| 207 |
+
"""
|
| 208 |
+
Tests calling a function when (n_args / 2) + n_kws > 15,
|
| 209 |
+
but n_args <= 30 and n_kws > 15
|
| 210 |
+
"""
|
| 211 |
+
used_args = self.THRESHOLD_ARGS - 1
|
| 212 |
+
used_kws = self.THRESHOLD_KWS
|
| 213 |
+
total_args = [i for i in range((used_args) + (used_kws))]
|
| 214 |
+
f = self.gen_func(used_args, used_kws)
|
| 215 |
+
py_func = f
|
| 216 |
+
cfunc = njit()(f)
|
| 217 |
+
a = py_func(*total_args)
|
| 218 |
+
b = cfunc(*total_args)
|
| 219 |
+
self.assertEqual(a, b)
|
| 220 |
+
|
| 221 |
+
@skip_unless_py10_or_later
|
| 222 |
+
def test_large_args_small_kws(self):
|
| 223 |
+
"""
|
| 224 |
+
Tests calling a function when (n_args / 2) + n_kws > 15,
|
| 225 |
+
but n_args > 30 and n_kws <= 15
|
| 226 |
+
"""
|
| 227 |
+
used_args = self.THRESHOLD_ARGS
|
| 228 |
+
used_kws = self.THRESHOLD_KWS - 1
|
| 229 |
+
total_args = [i for i in range((used_args) + (used_kws))]
|
| 230 |
+
f = self.gen_func(used_args, used_kws)
|
| 231 |
+
py_func = f
|
| 232 |
+
cfunc = njit()(f)
|
| 233 |
+
a = py_func(*total_args)
|
| 234 |
+
b = cfunc(*total_args)
|
| 235 |
+
self.assertEqual(a, b)
|
| 236 |
+
|
| 237 |
+
@skip_unless_py10_or_later
|
| 238 |
+
def test_large_args_large_kws(self):
|
| 239 |
+
"""
|
| 240 |
+
Tests calling a function when (n_args / 2) + n_kws > 15,
|
| 241 |
+
but n_args > 30 and n_kws > 15
|
| 242 |
+
"""
|
| 243 |
+
used_args = self.THRESHOLD_ARGS
|
| 244 |
+
used_kws = self.THRESHOLD_KWS
|
| 245 |
+
total_args = [i for i in range((used_args) + (used_kws))]
|
| 246 |
+
f = self.gen_func(used_args, used_kws)
|
| 247 |
+
py_func = f
|
| 248 |
+
cfunc = njit()(f)
|
| 249 |
+
a = py_func(*total_args)
|
| 250 |
+
b = cfunc(*total_args)
|
| 251 |
+
self.assertEqual(a, b)
|
| 252 |
+
|
| 253 |
+
@skip_unless_py10_or_later
|
| 254 |
+
def test_large_kws_objmode(self):
|
| 255 |
+
"""
|
| 256 |
+
Tests calling an objectmode function with > 15 return values.
|
| 257 |
+
"""
|
| 258 |
+
def py_func():
|
| 259 |
+
return (
|
| 260 |
+
0,
|
| 261 |
+
1,
|
| 262 |
+
2,
|
| 263 |
+
3,
|
| 264 |
+
4,
|
| 265 |
+
5,
|
| 266 |
+
6,
|
| 267 |
+
7,
|
| 268 |
+
8,
|
| 269 |
+
9,
|
| 270 |
+
10,
|
| 271 |
+
11,
|
| 272 |
+
12,
|
| 273 |
+
13,
|
| 274 |
+
14,
|
| 275 |
+
15,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
@njit
|
| 279 |
+
def objmode_func():
|
| 280 |
+
"""
|
| 281 |
+
Wrapper to call py_func from objmode. This tests
|
| 282 |
+
large kws with objmode. If the definition for the
|
| 283 |
+
call is not properly updated this test will fail.
|
| 284 |
+
"""
|
| 285 |
+
with objmode(
|
| 286 |
+
a='int64',
|
| 287 |
+
b='int64',
|
| 288 |
+
c='int64',
|
| 289 |
+
d='int64',
|
| 290 |
+
e='int64',
|
| 291 |
+
f='int64',
|
| 292 |
+
g='int64',
|
| 293 |
+
h='int64',
|
| 294 |
+
i='int64',
|
| 295 |
+
j='int64',
|
| 296 |
+
k='int64',
|
| 297 |
+
l='int64',
|
| 298 |
+
m='int64',
|
| 299 |
+
n='int64',
|
| 300 |
+
o='int64',
|
| 301 |
+
p='int64',
|
| 302 |
+
):
|
| 303 |
+
(
|
| 304 |
+
a,
|
| 305 |
+
b,
|
| 306 |
+
c,
|
| 307 |
+
d,
|
| 308 |
+
e,
|
| 309 |
+
f,
|
| 310 |
+
g,
|
| 311 |
+
h,
|
| 312 |
+
i,
|
| 313 |
+
j,
|
| 314 |
+
k,
|
| 315 |
+
l,
|
| 316 |
+
m,
|
| 317 |
+
n,
|
| 318 |
+
o,
|
| 319 |
+
p
|
| 320 |
+
) = py_func()
|
| 321 |
+
return (
|
| 322 |
+
a
|
| 323 |
+
+ b
|
| 324 |
+
+ c
|
| 325 |
+
+ d
|
| 326 |
+
+ e
|
| 327 |
+
+ f
|
| 328 |
+
+ g
|
| 329 |
+
+ h
|
| 330 |
+
+ i
|
| 331 |
+
+ j
|
| 332 |
+
+ k
|
| 333 |
+
+ l
|
| 334 |
+
+ m
|
| 335 |
+
+ n
|
| 336 |
+
+ o
|
| 337 |
+
+ p
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
a = sum(list(py_func()))
|
| 341 |
+
b = objmode_func()
|
| 342 |
+
self.assertEqual(a, b)
|
| 343 |
+
|
| 344 |
+
@skip_unless_py10_or_later
|
| 345 |
+
def test_large_args_inline_controlflow(self):
|
| 346 |
+
"""
|
| 347 |
+
Tests generating large args when one of the inputs
|
| 348 |
+
has inlined controlflow.
|
| 349 |
+
"""
|
| 350 |
+
def inline_func(flag):
|
| 351 |
+
return sum_jit_func(
|
| 352 |
+
1,
|
| 353 |
+
1,
|
| 354 |
+
1,
|
| 355 |
+
1,
|
| 356 |
+
1,
|
| 357 |
+
1,
|
| 358 |
+
1,
|
| 359 |
+
1,
|
| 360 |
+
1,
|
| 361 |
+
1,
|
| 362 |
+
1,
|
| 363 |
+
1,
|
| 364 |
+
1,
|
| 365 |
+
1,
|
| 366 |
+
1,
|
| 367 |
+
1,
|
| 368 |
+
1,
|
| 369 |
+
1,
|
| 370 |
+
1,
|
| 371 |
+
1,
|
| 372 |
+
1,
|
| 373 |
+
1 if flag else 2,
|
| 374 |
+
1,
|
| 375 |
+
1,
|
| 376 |
+
1,
|
| 377 |
+
1,
|
| 378 |
+
1,
|
| 379 |
+
1,
|
| 380 |
+
1,
|
| 381 |
+
1,
|
| 382 |
+
1,
|
| 383 |
+
1,
|
| 384 |
+
1,
|
| 385 |
+
1,
|
| 386 |
+
1,
|
| 387 |
+
1,
|
| 388 |
+
arg41=1,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
with self.assertRaises(UnsupportedBytecodeError) as raises:
|
| 392 |
+
njit()(inline_func)(False)
|
| 393 |
+
self.assertIn(
|
| 394 |
+
'You can resolve this issue by moving the control flow out',
|
| 395 |
+
str(raises.exception)
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
@skip_unless_py10_or_later
|
| 399 |
+
def test_large_args_noninlined_controlflow(self):
|
| 400 |
+
"""
|
| 401 |
+
Tests generating large args when one of the inputs
|
| 402 |
+
has the change suggested in the error message
|
| 403 |
+
for inlined control flow.
|
| 404 |
+
"""
|
| 405 |
+
def inline_func(flag):
|
| 406 |
+
a_val = 1 if flag else 2
|
| 407 |
+
return sum_jit_func(
|
| 408 |
+
1,
|
| 409 |
+
1,
|
| 410 |
+
1,
|
| 411 |
+
1,
|
| 412 |
+
1,
|
| 413 |
+
1,
|
| 414 |
+
1,
|
| 415 |
+
1,
|
| 416 |
+
1,
|
| 417 |
+
1,
|
| 418 |
+
1,
|
| 419 |
+
1,
|
| 420 |
+
1,
|
| 421 |
+
1,
|
| 422 |
+
1,
|
| 423 |
+
1,
|
| 424 |
+
1,
|
| 425 |
+
1,
|
| 426 |
+
1,
|
| 427 |
+
1,
|
| 428 |
+
1,
|
| 429 |
+
a_val,
|
| 430 |
+
1,
|
| 431 |
+
1,
|
| 432 |
+
1,
|
| 433 |
+
1,
|
| 434 |
+
1,
|
| 435 |
+
1,
|
| 436 |
+
1,
|
| 437 |
+
1,
|
| 438 |
+
1,
|
| 439 |
+
1,
|
| 440 |
+
1,
|
| 441 |
+
1,
|
| 442 |
+
1,
|
| 443 |
+
1,
|
| 444 |
+
arg41=1,
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
py_func = inline_func
|
| 448 |
+
cfunc = njit()(inline_func)
|
| 449 |
+
a = py_func(False)
|
| 450 |
+
b = cfunc(False)
|
| 451 |
+
self.assertEqual(a, b)
|
| 452 |
+
|
| 453 |
+
@skip_unless_py10_or_later
|
| 454 |
+
def test_all_args_inline_controlflow(self):
|
| 455 |
+
"""
|
| 456 |
+
Tests generating only large args when one of the inputs
|
| 457 |
+
has inlined controlflow. This requires a special check
|
| 458 |
+
inside peep_hole_call_function_ex_to_call_function_kw
|
| 459 |
+
because it usually only handles varkwargs.
|
| 460 |
+
"""
|
| 461 |
+
def inline_func(flag):
|
| 462 |
+
return sum_jit_func(
|
| 463 |
+
1,
|
| 464 |
+
1,
|
| 465 |
+
1,
|
| 466 |
+
1,
|
| 467 |
+
1,
|
| 468 |
+
1,
|
| 469 |
+
1,
|
| 470 |
+
1,
|
| 471 |
+
1,
|
| 472 |
+
1,
|
| 473 |
+
1,
|
| 474 |
+
1,
|
| 475 |
+
1,
|
| 476 |
+
1,
|
| 477 |
+
1,
|
| 478 |
+
1,
|
| 479 |
+
1,
|
| 480 |
+
1,
|
| 481 |
+
1,
|
| 482 |
+
1,
|
| 483 |
+
1,
|
| 484 |
+
1 if flag else 2,
|
| 485 |
+
1,
|
| 486 |
+
1,
|
| 487 |
+
1,
|
| 488 |
+
1,
|
| 489 |
+
1,
|
| 490 |
+
1,
|
| 491 |
+
1,
|
| 492 |
+
1,
|
| 493 |
+
1,
|
| 494 |
+
1,
|
| 495 |
+
1,
|
| 496 |
+
1,
|
| 497 |
+
1,
|
| 498 |
+
1,
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
with self.assertRaises(UnsupportedBytecodeError) as raises:
|
| 502 |
+
njit()(inline_func)(False)
|
| 503 |
+
self.assertIn(
|
| 504 |
+
'You can resolve this issue by moving the control flow out',
|
| 505 |
+
str(raises.exception)
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
@skip_unless_py10_or_later
|
| 509 |
+
def test_all_args_noninlined_controlflow(self):
|
| 510 |
+
"""
|
| 511 |
+
Tests generating large args when one of the inputs
|
| 512 |
+
has the change suggested in the error message
|
| 513 |
+
for inlined control flow.
|
| 514 |
+
"""
|
| 515 |
+
def inline_func(flag):
|
| 516 |
+
a_val = 1 if flag else 2
|
| 517 |
+
return sum_jit_func(
|
| 518 |
+
1,
|
| 519 |
+
1,
|
| 520 |
+
1,
|
| 521 |
+
1,
|
| 522 |
+
1,
|
| 523 |
+
1,
|
| 524 |
+
1,
|
| 525 |
+
1,
|
| 526 |
+
1,
|
| 527 |
+
1,
|
| 528 |
+
1,
|
| 529 |
+
1,
|
| 530 |
+
1,
|
| 531 |
+
1,
|
| 532 |
+
1,
|
| 533 |
+
1,
|
| 534 |
+
1,
|
| 535 |
+
1,
|
| 536 |
+
1,
|
| 537 |
+
1,
|
| 538 |
+
1,
|
| 539 |
+
a_val,
|
| 540 |
+
1,
|
| 541 |
+
1,
|
| 542 |
+
1,
|
| 543 |
+
1,
|
| 544 |
+
1,
|
| 545 |
+
1,
|
| 546 |
+
1,
|
| 547 |
+
1,
|
| 548 |
+
1,
|
| 549 |
+
1,
|
| 550 |
+
1,
|
| 551 |
+
1,
|
| 552 |
+
1,
|
| 553 |
+
1,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
py_func = inline_func
|
| 557 |
+
cfunc = njit()(inline_func)
|
| 558 |
+
a = py_func(False)
|
| 559 |
+
b = cfunc(False)
|
| 560 |
+
self.assertEqual(a, b)
|
| 561 |
+
|
| 562 |
+
@skip_unless_py10_or_later
|
| 563 |
+
def test_large_kws_inline_controlflow(self):
|
| 564 |
+
"""
|
| 565 |
+
Tests generating large kws when one of the inputs
|
| 566 |
+
has inlined controlflow.
|
| 567 |
+
"""
|
| 568 |
+
def inline_func(flag):
|
| 569 |
+
return sum_jit_func(
|
| 570 |
+
arg0=1,
|
| 571 |
+
arg1=1,
|
| 572 |
+
arg2=1,
|
| 573 |
+
arg3=1,
|
| 574 |
+
arg4=1,
|
| 575 |
+
arg5=1,
|
| 576 |
+
arg6=1,
|
| 577 |
+
arg7=1,
|
| 578 |
+
arg8=1,
|
| 579 |
+
arg9=1,
|
| 580 |
+
arg10=1,
|
| 581 |
+
arg11=1,
|
| 582 |
+
arg12=1,
|
| 583 |
+
arg13=1,
|
| 584 |
+
arg14=1,
|
| 585 |
+
arg15=1 if flag else 2,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
with self.assertRaises(UnsupportedBytecodeError) as raises:
|
| 589 |
+
njit()(inline_func)(False)
|
| 590 |
+
self.assertIn(
|
| 591 |
+
'You can resolve this issue by moving the control flow out',
|
| 592 |
+
str(raises.exception)
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
@skip_unless_py10_or_later
|
| 596 |
+
def test_large_kws_noninlined_controlflow(self):
|
| 597 |
+
"""
|
| 598 |
+
Tests generating large kws when one of the inputs
|
| 599 |
+
has the change suggested in the error message
|
| 600 |
+
for inlined control flow.
|
| 601 |
+
"""
|
| 602 |
+
def inline_func(flag):
|
| 603 |
+
a_val = 1 if flag else 2
|
| 604 |
+
return sum_jit_func(
|
| 605 |
+
arg0=1,
|
| 606 |
+
arg1=1,
|
| 607 |
+
arg2=1,
|
| 608 |
+
arg3=1,
|
| 609 |
+
arg4=1,
|
| 610 |
+
arg5=1,
|
| 611 |
+
arg6=1,
|
| 612 |
+
arg7=1,
|
| 613 |
+
arg8=1,
|
| 614 |
+
arg9=1,
|
| 615 |
+
arg10=1,
|
| 616 |
+
arg11=1,
|
| 617 |
+
arg12=1,
|
| 618 |
+
arg13=1,
|
| 619 |
+
arg14=1,
|
| 620 |
+
arg15=a_val,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
py_func = inline_func
|
| 624 |
+
cfunc = njit()(inline_func)
|
| 625 |
+
a = py_func(False)
|
| 626 |
+
b = cfunc(False)
|
| 627 |
+
self.assertEqual(a, b)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class TestLargeConstDict(TestCase, MemoryLeakMixin):
|
| 631 |
+
"""
|
| 632 |
+
gh #7894
|
| 633 |
+
|
| 634 |
+
Tests that check a peephole optimization for constant
|
| 635 |
+
dictionaries in Python 3.10. The bytecode changes when
|
| 636 |
+
number of elements > 15, which splits the constant dictionary
|
| 637 |
+
into multiple dictionaries that are joined by a DICT_UPDATE
|
| 638 |
+
bytecode instruction.
|
| 639 |
+
|
| 640 |
+
This optimization modifies the IR to rejoin dictionaries
|
| 641 |
+
and remove the DICT_UPDATE generated code. This then allows
|
| 642 |
+
code that depends on literal dictionaries or literal keys
|
| 643 |
+
to succeed.
|
| 644 |
+
"""
|
| 645 |
+
|
| 646 |
+
@skip_unless_py10_or_later
|
| 647 |
+
def test_large_heterogeneous_const_dict(self):
|
| 648 |
+
"""
|
| 649 |
+
Tests that a function with a large heterogeneous constant
|
| 650 |
+
dictionary remains a constant.
|
| 651 |
+
"""
|
| 652 |
+
def const_func():
|
| 653 |
+
# D is a heterogeneous dictionary
|
| 654 |
+
# so this code can only compile if
|
| 655 |
+
# d is constant.
|
| 656 |
+
d = {
|
| 657 |
+
"A": 1,
|
| 658 |
+
"B": 1,
|
| 659 |
+
"C": 1,
|
| 660 |
+
"D": 1,
|
| 661 |
+
"E": 1,
|
| 662 |
+
"F": 1,
|
| 663 |
+
"G": 1,
|
| 664 |
+
"H": 1,
|
| 665 |
+
"I": 1,
|
| 666 |
+
"J": 1,
|
| 667 |
+
"K": 1,
|
| 668 |
+
"L": 1,
|
| 669 |
+
"M": 1,
|
| 670 |
+
"N": 1,
|
| 671 |
+
"O": 1,
|
| 672 |
+
"P": 1,
|
| 673 |
+
"Q": 1,
|
| 674 |
+
"R": 1,
|
| 675 |
+
"S": 'a',
|
| 676 |
+
}
|
| 677 |
+
return d["S"]
|
| 678 |
+
|
| 679 |
+
py_func = const_func
|
| 680 |
+
cfunc = njit()(const_func)
|
| 681 |
+
a = py_func()
|
| 682 |
+
b = cfunc()
|
| 683 |
+
self.assertEqual(a, b)
|
| 684 |
+
|
| 685 |
+
@skip_unless_py10_or_later
|
| 686 |
+
def test_large_heterogeneous_LiteralStrKeyDict_literal_values(self):
|
| 687 |
+
"""Check the literal values for a LiteralStrKeyDict requiring
|
| 688 |
+
optimizations because it is heterogeneous.
|
| 689 |
+
"""
|
| 690 |
+
|
| 691 |
+
def bar(d):
|
| 692 |
+
...
|
| 693 |
+
|
| 694 |
+
@overload(bar)
|
| 695 |
+
def ol_bar(d):
|
| 696 |
+
a = {
|
| 697 |
+
"A": 1,
|
| 698 |
+
"B": 1,
|
| 699 |
+
"C": 1,
|
| 700 |
+
"D": 1,
|
| 701 |
+
"E": 1,
|
| 702 |
+
"F": 1,
|
| 703 |
+
"G": 1,
|
| 704 |
+
"H": 1,
|
| 705 |
+
"I": 1,
|
| 706 |
+
"J": 1,
|
| 707 |
+
"K": 1,
|
| 708 |
+
"L": 1,
|
| 709 |
+
"M": 1,
|
| 710 |
+
"N": 1,
|
| 711 |
+
"O": 1,
|
| 712 |
+
"P": 1,
|
| 713 |
+
"Q": 1,
|
| 714 |
+
"R": 1,
|
| 715 |
+
"S": 'a',
|
| 716 |
+
}
|
| 717 |
+
|
| 718 |
+
def specific_ty(z):
|
| 719 |
+
return types.literal(z) if types.maybe_literal(z) else typeof(z)
|
| 720 |
+
expected = {types.literal(x): specific_ty(y) for x, y in a.items()}
|
| 721 |
+
self.assertTrue(isinstance(d, types.LiteralStrKeyDict))
|
| 722 |
+
self.assertEqual(d.literal_value, expected)
|
| 723 |
+
self.assertEqual(hasattr(d, 'initial_value'), False)
|
| 724 |
+
return lambda d: d
|
| 725 |
+
|
| 726 |
+
@njit
|
| 727 |
+
def foo():
|
| 728 |
+
# D is a heterogeneous dictionary
|
| 729 |
+
# so this code can only compile if
|
| 730 |
+
# d has the correct literal values.
|
| 731 |
+
d = {
|
| 732 |
+
"A": 1,
|
| 733 |
+
"B": 1,
|
| 734 |
+
"C": 1,
|
| 735 |
+
"D": 1,
|
| 736 |
+
"E": 1,
|
| 737 |
+
"F": 1,
|
| 738 |
+
"G": 1,
|
| 739 |
+
"H": 1,
|
| 740 |
+
"I": 1,
|
| 741 |
+
"J": 1,
|
| 742 |
+
"K": 1,
|
| 743 |
+
"L": 1,
|
| 744 |
+
"M": 1,
|
| 745 |
+
"N": 1,
|
| 746 |
+
"O": 1,
|
| 747 |
+
"P": 1,
|
| 748 |
+
"Q": 1,
|
| 749 |
+
"R": 1,
|
| 750 |
+
"S": 'a',
|
| 751 |
+
}
|
| 752 |
+
bar(d)
|
| 753 |
+
|
| 754 |
+
foo()
|
| 755 |
+
|
| 756 |
+
@skip_unless_py10_or_later
|
| 757 |
+
def test_large_heterogeneous_const_keys_dict(self):
|
| 758 |
+
"""
|
| 759 |
+
Tests that a function with a large heterogeneous constant
|
| 760 |
+
dictionary remains a constant.
|
| 761 |
+
"""
|
| 762 |
+
def const_keys_func(a):
|
| 763 |
+
# D is a heterogeneous dictionary
|
| 764 |
+
# so this code can only compile if
|
| 765 |
+
# d has constant keys.
|
| 766 |
+
d = {
|
| 767 |
+
"A": 1,
|
| 768 |
+
"B": 1,
|
| 769 |
+
"C": 1,
|
| 770 |
+
"D": 1,
|
| 771 |
+
"E": 1,
|
| 772 |
+
"F": 1,
|
| 773 |
+
"G": 1,
|
| 774 |
+
"H": 1,
|
| 775 |
+
"I": 1,
|
| 776 |
+
"J": 1,
|
| 777 |
+
"K": 1,
|
| 778 |
+
"L": 1,
|
| 779 |
+
"M": 1,
|
| 780 |
+
"N": 1,
|
| 781 |
+
"O": 1,
|
| 782 |
+
"P": 1,
|
| 783 |
+
"Q": 1,
|
| 784 |
+
"R": 1,
|
| 785 |
+
"S": a,
|
| 786 |
+
}
|
| 787 |
+
return d["S"]
|
| 788 |
+
|
| 789 |
+
py_func = const_keys_func
|
| 790 |
+
cfunc = njit()(const_keys_func)
|
| 791 |
+
# str to make the dictionary heterogeneous.
|
| 792 |
+
value = "a_string"
|
| 793 |
+
a = py_func(value)
|
| 794 |
+
b = cfunc(value)
|
| 795 |
+
self.assertEqual(a, b)
|
| 796 |
+
|
| 797 |
+
@skip_unless_py10_or_later
|
| 798 |
+
def test_large_dict_mutation_not_carried(self):
|
| 799 |
+
"""Checks that the optimization for large dictionaries
|
| 800 |
+
do not incorrectly update initial values due to other
|
| 801 |
+
mutations.
|
| 802 |
+
"""
|
| 803 |
+
def bar(d):
|
| 804 |
+
...
|
| 805 |
+
|
| 806 |
+
@overload(bar)
|
| 807 |
+
def ol_bar(d):
|
| 808 |
+
a = {
|
| 809 |
+
"A": 1,
|
| 810 |
+
"B": 1,
|
| 811 |
+
"C": 1,
|
| 812 |
+
"D": 1,
|
| 813 |
+
"E": 1,
|
| 814 |
+
"F": 1,
|
| 815 |
+
"G": 1,
|
| 816 |
+
"H": 1,
|
| 817 |
+
"I": 1,
|
| 818 |
+
"J": 1,
|
| 819 |
+
"K": 1,
|
| 820 |
+
"L": 1,
|
| 821 |
+
"M": 1,
|
| 822 |
+
"N": 1,
|
| 823 |
+
"O": 1,
|
| 824 |
+
"P": 1,
|
| 825 |
+
"Q": 1,
|
| 826 |
+
"R": 1,
|
| 827 |
+
"S": 7,
|
| 828 |
+
}
|
| 829 |
+
if d.initial_value is None:
|
| 830 |
+
return lambda d: literally(d)
|
| 831 |
+
self.assertTrue(isinstance(d, types.DictType))
|
| 832 |
+
self.assertEqual(d.initial_value, a)
|
| 833 |
+
return lambda d: d
|
| 834 |
+
|
| 835 |
+
@njit
|
| 836 |
+
def foo():
|
| 837 |
+
# This dictionary is mutated, check the initial_value carries
|
| 838 |
+
# correctly and is not mutated
|
| 839 |
+
d = {
|
| 840 |
+
"A": 1,
|
| 841 |
+
"B": 1,
|
| 842 |
+
"C": 1,
|
| 843 |
+
"D": 1,
|
| 844 |
+
"E": 1,
|
| 845 |
+
"F": 1,
|
| 846 |
+
"G": 1,
|
| 847 |
+
"H": 1,
|
| 848 |
+
"I": 1,
|
| 849 |
+
"J": 1,
|
| 850 |
+
"K": 1,
|
| 851 |
+
"L": 1,
|
| 852 |
+
"M": 1,
|
| 853 |
+
"N": 1,
|
| 854 |
+
"O": 1,
|
| 855 |
+
"P": 1,
|
| 856 |
+
"Q": 1,
|
| 857 |
+
"R": 1,
|
| 858 |
+
"S": 7,
|
| 859 |
+
}
|
| 860 |
+
d['X'] = 4
|
| 861 |
+
bar(d)
|
| 862 |
+
|
| 863 |
+
foo()
|
| 864 |
+
|
| 865 |
+
@skip_unless_py10_or_later
|
| 866 |
+
def test_usercode_update_use_d2(self):
|
| 867 |
+
"""
|
| 868 |
+
Tests an example using a regular update is
|
| 869 |
+
not modified by the optimization.
|
| 870 |
+
"""
|
| 871 |
+
|
| 872 |
+
def check_before(x):
|
| 873 |
+
pass
|
| 874 |
+
|
| 875 |
+
def check_after(x):
|
| 876 |
+
pass
|
| 877 |
+
|
| 878 |
+
checked_before = False
|
| 879 |
+
checked_after = False
|
| 880 |
+
|
| 881 |
+
@overload(check_before, prefer_literal=True)
|
| 882 |
+
def ol_check_before(d):
|
| 883 |
+
nonlocal checked_before
|
| 884 |
+
# Typing iteration from d1.update(d2)
|
| 885 |
+
# may reset the initial values to None,
|
| 886 |
+
# so we only check on the first iteration.
|
| 887 |
+
if not checked_before:
|
| 888 |
+
checked_before = True
|
| 889 |
+
a = {
|
| 890 |
+
"a": 1,
|
| 891 |
+
"b": 2,
|
| 892 |
+
"c": 3,
|
| 893 |
+
}
|
| 894 |
+
self.assertTrue(isinstance(d, types.DictType))
|
| 895 |
+
self.assertEqual(d.initial_value, a)
|
| 896 |
+
|
| 897 |
+
return lambda d: None
|
| 898 |
+
|
| 899 |
+
@overload(check_after, prefer_literal=True)
|
| 900 |
+
def ol_check_after(d):
|
| 901 |
+
nonlocal checked_after
|
| 902 |
+
# Typing iteration from d1.update(d2)
|
| 903 |
+
# may reset the initial values to None,
|
| 904 |
+
# so we only check on the first iteration.
|
| 905 |
+
if not checked_after:
|
| 906 |
+
checked_after = True
|
| 907 |
+
self.assertTrue(isinstance(d, types.DictType))
|
| 908 |
+
self.assertTrue(d.initial_value is None)
|
| 909 |
+
|
| 910 |
+
return lambda d: None
|
| 911 |
+
|
| 912 |
+
def const_dict_func():
|
| 913 |
+
"""
|
| 914 |
+
Dictionary update between two constant
|
| 915 |
+
dictionaries. This verifies d2 doesn't
|
| 916 |
+
get incorrectly removed.
|
| 917 |
+
"""
|
| 918 |
+
d1 = {
|
| 919 |
+
"a": 1,
|
| 920 |
+
"b": 2,
|
| 921 |
+
"c": 3,
|
| 922 |
+
}
|
| 923 |
+
d2 = {
|
| 924 |
+
"d": 4,
|
| 925 |
+
"e": 4
|
| 926 |
+
}
|
| 927 |
+
check_before(d1)
|
| 928 |
+
d1.update(d2)
|
| 929 |
+
check_after(d1)
|
| 930 |
+
# Create a use of d2 in a new block.
|
| 931 |
+
if len(d1) > 4:
|
| 932 |
+
return d2
|
| 933 |
+
return d1
|
| 934 |
+
|
| 935 |
+
py_func = const_dict_func
|
| 936 |
+
cfunc = njit()(const_dict_func)
|
| 937 |
+
a = py_func()
|
| 938 |
+
b = cfunc()
|
| 939 |
+
self.assertEqual(a, b)
|
| 940 |
+
|
| 941 |
+
@skip_unless_py10_or_later
|
| 942 |
+
def test_large_const_dict_inline_controlflow(self):
|
| 943 |
+
"""
|
| 944 |
+
Tests generating a large dictionary when one of
|
| 945 |
+
the inputs requires inline control flow
|
| 946 |
+
has the change suggested in the error message
|
| 947 |
+
for inlined control flow.
|
| 948 |
+
"""
|
| 949 |
+
def inline_func(a, flag):
|
| 950 |
+
# D is a heterogeneous dictionary
|
| 951 |
+
# so this code can only compile if
|
| 952 |
+
# d has constant keys.
|
| 953 |
+
d = {
|
| 954 |
+
"A": 1,
|
| 955 |
+
"B": 1,
|
| 956 |
+
"C": 1,
|
| 957 |
+
"D": 1,
|
| 958 |
+
"E": 1,
|
| 959 |
+
"F": 1,
|
| 960 |
+
"G": 1,
|
| 961 |
+
"H": 1 if flag else 2,
|
| 962 |
+
"I": 1,
|
| 963 |
+
"J": 1,
|
| 964 |
+
"K": 1,
|
| 965 |
+
"L": 1,
|
| 966 |
+
"M": 1,
|
| 967 |
+
"N": 1,
|
| 968 |
+
"O": 1,
|
| 969 |
+
"P": 1,
|
| 970 |
+
"Q": 1,
|
| 971 |
+
"R": 1,
|
| 972 |
+
"S": a,
|
| 973 |
+
}
|
| 974 |
+
return d["S"]
|
| 975 |
+
|
| 976 |
+
with self.assertRaises(UnsupportedBytecodeError) as raises:
|
| 977 |
+
njit()(inline_func)("a_string", False)
|
| 978 |
+
self.assertIn(
|
| 979 |
+
'You can resolve this issue by moving the control flow out',
|
| 980 |
+
str(raises.exception)
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
@skip_unless_py10_or_later
|
| 984 |
+
def test_large_const_dict_noninline_controlflow(self):
|
| 985 |
+
"""
|
| 986 |
+
Tests generating large constant dict when one of the
|
| 987 |
+
inputs has the change suggested in the error message
|
| 988 |
+
for inlined control flow.
|
| 989 |
+
"""
|
| 990 |
+
def non_inline_func(a, flag):
|
| 991 |
+
# D is a heterogeneous dictionary
|
| 992 |
+
# so this code can only compile if
|
| 993 |
+
# d has constant keys.
|
| 994 |
+
val = 1 if flag else 2
|
| 995 |
+
d = {
|
| 996 |
+
"A": 1,
|
| 997 |
+
"B": 1,
|
| 998 |
+
"C": 1,
|
| 999 |
+
"D": 1,
|
| 1000 |
+
"E": 1,
|
| 1001 |
+
"F": 1,
|
| 1002 |
+
"G": 1,
|
| 1003 |
+
"H": val,
|
| 1004 |
+
"I": 1,
|
| 1005 |
+
"J": 1,
|
| 1006 |
+
"K": 1,
|
| 1007 |
+
"L": 1,
|
| 1008 |
+
"M": 1,
|
| 1009 |
+
"N": 1,
|
| 1010 |
+
"O": 1,
|
| 1011 |
+
"P": 1,
|
| 1012 |
+
"Q": 1,
|
| 1013 |
+
"R": 1,
|
| 1014 |
+
"S": a,
|
| 1015 |
+
}
|
| 1016 |
+
return d["S"]
|
| 1017 |
+
|
| 1018 |
+
py_func = non_inline_func
|
| 1019 |
+
cfunc = njit()(non_inline_func)
|
| 1020 |
+
value = "a_string"
|
| 1021 |
+
a = py_func(value, False)
|
| 1022 |
+
b = cfunc(value, False)
|
| 1023 |
+
self.assertEqual(a, b)
|
| 1024 |
+
|
| 1025 |
+
@skip_unless_py10_or_later
|
| 1026 |
+
def test_fuse_twice_literal_values(self):
|
| 1027 |
+
"""
|
| 1028 |
+
Tests that the correct literal values are generated
|
| 1029 |
+
for a dictionary that produces two DICT_UPDATE
|
| 1030 |
+
bytecode entries for the same dictionary.
|
| 1031 |
+
"""
|
| 1032 |
+
def bar(d):
|
| 1033 |
+
...
|
| 1034 |
+
|
| 1035 |
+
@overload(bar)
|
| 1036 |
+
def ol_bar(d):
|
| 1037 |
+
a = {
|
| 1038 |
+
"a1" : 1,
|
| 1039 |
+
"a2" : 2,
|
| 1040 |
+
"a3" : 3,
|
| 1041 |
+
"a4" : 4,
|
| 1042 |
+
"a5" : 5,
|
| 1043 |
+
"a6" : 6,
|
| 1044 |
+
"a7" : 7,
|
| 1045 |
+
"a8" : 8,
|
| 1046 |
+
"a9" : 9,
|
| 1047 |
+
"a10" : 10,
|
| 1048 |
+
"a11" : 11,
|
| 1049 |
+
"a12" : 12,
|
| 1050 |
+
"a13" : 13,
|
| 1051 |
+
"a14" : 14,
|
| 1052 |
+
"a15" : 15,
|
| 1053 |
+
"a16" : 16,
|
| 1054 |
+
"a17" : 17,
|
| 1055 |
+
"a18" : 18,
|
| 1056 |
+
"a19" : 19,
|
| 1057 |
+
"a20" : 20,
|
| 1058 |
+
"a21" : 21,
|
| 1059 |
+
"a22" : 22,
|
| 1060 |
+
"a23" : 23,
|
| 1061 |
+
"a24" : 24,
|
| 1062 |
+
"a25" : 25,
|
| 1063 |
+
"a26" : 26,
|
| 1064 |
+
"a27" : 27,
|
| 1065 |
+
"a28" : 28,
|
| 1066 |
+
"a29" : 29,
|
| 1067 |
+
"a30" : 30,
|
| 1068 |
+
"a31" : 31,
|
| 1069 |
+
"a32" : 32,
|
| 1070 |
+
"a33" : 33,
|
| 1071 |
+
"a34" : 34, # 34 items is the limit of
|
| 1072 |
+
# (LOAD_CONST + MAP_ADD)^n + DICT_UPDATE
|
| 1073 |
+
"a35" : 35, # 35 Generates an additional BUILD_MAP + DICT_UPDATE
|
| 1074 |
+
}
|
| 1075 |
+
if d.initial_value is None:
|
| 1076 |
+
return lambda d: literally(d)
|
| 1077 |
+
self.assertTrue(isinstance(d, types.DictType))
|
| 1078 |
+
self.assertEqual(d.initial_value, a)
|
| 1079 |
+
return lambda d: d
|
| 1080 |
+
|
| 1081 |
+
@njit
|
| 1082 |
+
def foo():
|
| 1083 |
+
# This dictionary is mutated, check the initial_value carries
|
| 1084 |
+
# correctly and is not mutated
|
| 1085 |
+
d = {
|
| 1086 |
+
"a1" : 1,
|
| 1087 |
+
"a2" : 2,
|
| 1088 |
+
"a3" : 3,
|
| 1089 |
+
"a4" : 4,
|
| 1090 |
+
"a5" : 5,
|
| 1091 |
+
"a6" : 6,
|
| 1092 |
+
"a7" : 7,
|
| 1093 |
+
"a8" : 8,
|
| 1094 |
+
"a9" : 9,
|
| 1095 |
+
"a10" : 10,
|
| 1096 |
+
"a11" : 11,
|
| 1097 |
+
"a12" : 12,
|
| 1098 |
+
"a13" : 13,
|
| 1099 |
+
"a14" : 14,
|
| 1100 |
+
"a15" : 15,
|
| 1101 |
+
"a16" : 16,
|
| 1102 |
+
"a17" : 17,
|
| 1103 |
+
"a18" : 18,
|
| 1104 |
+
"a19" : 19,
|
| 1105 |
+
"a20" : 20,
|
| 1106 |
+
"a21" : 21,
|
| 1107 |
+
"a22" : 22,
|
| 1108 |
+
"a23" : 23,
|
| 1109 |
+
"a24" : 24,
|
| 1110 |
+
"a25" : 25,
|
| 1111 |
+
"a26" : 26,
|
| 1112 |
+
"a27" : 27,
|
| 1113 |
+
"a28" : 28,
|
| 1114 |
+
"a29" : 29,
|
| 1115 |
+
"a30" : 30,
|
| 1116 |
+
"a31" : 31,
|
| 1117 |
+
"a32" : 32,
|
| 1118 |
+
"a33" : 33,
|
| 1119 |
+
"a34" : 34, # 34 items is the limit of
|
| 1120 |
+
# (LOAD_CONST + MAP_ADD)^n + DICT_UPDATE
|
| 1121 |
+
"a35" : 35, # 35 Generates an additional BUILD_MAP + DICT_UPDATE
|
| 1122 |
+
}
|
| 1123 |
+
bar(d)
|
| 1124 |
+
|
| 1125 |
+
foo()
|
| 1126 |
+
|
| 1127 |
+
|
| 1128 |
+
class TestListExtendInStarArgNonTupleIterable(MemoryLeakMixin, TestCase):
|
| 1129 |
+
"""Test `fn(pos_arg0, pos_arg1, *args)` where args is a non-tuple iterable.
|
| 1130 |
+
|
| 1131 |
+
Python 3.9+ will generate LIST_EXTEND bytecode to combine the positional
|
| 1132 |
+
arguments with the `*args`.
|
| 1133 |
+
|
| 1134 |
+
See #8059
|
| 1135 |
+
|
| 1136 |
+
NOTE: At the moment, there are no meaningful tests for NoPython because the
|
| 1137 |
+
lack of support for `tuple(iterable)` for most iterable types.
|
| 1138 |
+
"""
|
| 1139 |
+
def test_list_extend_forceobj(self):
|
| 1140 |
+
def consumer(*x):
|
| 1141 |
+
return x
|
| 1142 |
+
|
| 1143 |
+
@jit(forceobj=True)
|
| 1144 |
+
def foo(x):
|
| 1145 |
+
return consumer(1, 2, *x)
|
| 1146 |
+
|
| 1147 |
+
got = foo("ijo")
|
| 1148 |
+
expect = foo.py_func("ijo")
|
| 1149 |
+
self.assertEqual(got, (1, 2, "i", "j", "o"))
|
| 1150 |
+
self.assertEqual(got, expect)
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
if __name__ == "__main__":
|
| 1154 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_ir.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from unittest.case import TestCase
|
| 3 |
+
import warnings
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from numba import objmode
|
| 7 |
+
from numba.core import ir, compiler
|
| 8 |
+
from numba.core import errors
|
| 9 |
+
from numba.core.compiler import (
|
| 10 |
+
CompilerBase,
|
| 11 |
+
ReconstructSSA,
|
| 12 |
+
)
|
| 13 |
+
from numba.core.compiler_machinery import (
|
| 14 |
+
FunctionPass,
|
| 15 |
+
PassManager,
|
| 16 |
+
register_pass,
|
| 17 |
+
)
|
| 18 |
+
from numba.core.untyped_passes import (
|
| 19 |
+
TranslateByteCode,
|
| 20 |
+
IRProcessing,
|
| 21 |
+
)
|
| 22 |
+
from numba import njit
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TestIR(unittest.TestCase):
|
| 26 |
+
|
| 27 |
+
def test_IRScope(self):
|
| 28 |
+
filename = "<?>"
|
| 29 |
+
top = ir.Scope(parent=None, loc=ir.Loc(filename=filename, line=1))
|
| 30 |
+
local = ir.Scope(parent=top, loc=ir.Loc(filename=filename, line=2))
|
| 31 |
+
|
| 32 |
+
apple = local.define('apple', loc=ir.Loc(filename=filename, line=3))
|
| 33 |
+
self.assertIs(local.get('apple'), apple)
|
| 34 |
+
self.assertEqual(len(local.localvars), 1)
|
| 35 |
+
|
| 36 |
+
orange = top.define('orange', loc=ir.Loc(filename=filename, line=4))
|
| 37 |
+
self.assertEqual(len(local.localvars), 1)
|
| 38 |
+
self.assertEqual(len(top.localvars), 1)
|
| 39 |
+
self.assertIs(top.get('orange'), orange)
|
| 40 |
+
self.assertIs(local.get('orange'), orange)
|
| 41 |
+
|
| 42 |
+
more_orange = local.define('orange', loc=ir.Loc(filename=filename,
|
| 43 |
+
line=5))
|
| 44 |
+
self.assertIs(top.get('orange'), orange)
|
| 45 |
+
self.assertIsNot(local.get('orange'), not orange)
|
| 46 |
+
self.assertIs(local.get('orange'), more_orange)
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
local.define('orange', loc=ir.Loc(filename=filename, line=5))
|
| 50 |
+
except ir.RedefinedError:
|
| 51 |
+
pass
|
| 52 |
+
else:
|
| 53 |
+
self.fail("Expecting an %s" % ir.RedefinedError)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class CheckEquality(unittest.TestCase):
|
| 57 |
+
|
| 58 |
+
var_a = ir.Var(None, 'a', ir.unknown_loc)
|
| 59 |
+
var_b = ir.Var(None, 'b', ir.unknown_loc)
|
| 60 |
+
var_c = ir.Var(None, 'c', ir.unknown_loc)
|
| 61 |
+
var_d = ir.Var(None, 'd', ir.unknown_loc)
|
| 62 |
+
var_e = ir.Var(None, 'e', ir.unknown_loc)
|
| 63 |
+
loc1 = ir.Loc('mock', 1, 0)
|
| 64 |
+
loc2 = ir.Loc('mock', 2, 0)
|
| 65 |
+
loc3 = ir.Loc('mock', 3, 0)
|
| 66 |
+
|
| 67 |
+
def check(self, base, same=[], different=[]):
|
| 68 |
+
for s in same:
|
| 69 |
+
self.assertTrue(base == s)
|
| 70 |
+
for d in different:
|
| 71 |
+
self.assertTrue(base != d)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TestIRMeta(CheckEquality):
|
| 75 |
+
"""
|
| 76 |
+
Tests IR node meta, like Loc and Scope
|
| 77 |
+
"""
|
| 78 |
+
def test_loc(self):
|
| 79 |
+
a = ir.Loc('file', 1, 0)
|
| 80 |
+
b = ir.Loc('file', 1, 0)
|
| 81 |
+
c = ir.Loc('pile', 1, 0)
|
| 82 |
+
d = ir.Loc('file', 2, 0)
|
| 83 |
+
e = ir.Loc('file', 1, 1)
|
| 84 |
+
self.check(a, same=[b,], different=[c, d, e])
|
| 85 |
+
|
| 86 |
+
f = ir.Loc('file', 1, 0, maybe_decorator=False)
|
| 87 |
+
g = ir.Loc('file', 1, 0, maybe_decorator=True)
|
| 88 |
+
self.check(a, same=[f, g])
|
| 89 |
+
|
| 90 |
+
def test_scope(self):
|
| 91 |
+
parent1 = ir.Scope(None, self.loc1)
|
| 92 |
+
parent2 = ir.Scope(None, self.loc1)
|
| 93 |
+
parent3 = ir.Scope(None, self.loc2)
|
| 94 |
+
self.check(parent1, same=[parent2, parent3,])
|
| 95 |
+
|
| 96 |
+
a = ir.Scope(parent1, self.loc1)
|
| 97 |
+
b = ir.Scope(parent1, self.loc1)
|
| 98 |
+
c = ir.Scope(parent1, self.loc2)
|
| 99 |
+
d = ir.Scope(parent3, self.loc1)
|
| 100 |
+
self.check(a, same=[b, c, d])
|
| 101 |
+
|
| 102 |
+
# parent1 and parent2 are equal, so children referring to either parent
|
| 103 |
+
# should be equal
|
| 104 |
+
e = ir.Scope(parent2, self.loc1)
|
| 105 |
+
self.check(a, same=[e,])
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class TestIRNodes(CheckEquality):
|
| 109 |
+
"""
|
| 110 |
+
Tests IR nodes
|
| 111 |
+
"""
|
| 112 |
+
def test_terminator(self):
|
| 113 |
+
# terminator base class inst should always be equal
|
| 114 |
+
t1 = ir.Terminator()
|
| 115 |
+
t2 = ir.Terminator()
|
| 116 |
+
self.check(t1, same=[t2])
|
| 117 |
+
|
| 118 |
+
def test_jump(self):
|
| 119 |
+
a = ir.Jump(1, self.loc1)
|
| 120 |
+
b = ir.Jump(1, self.loc1)
|
| 121 |
+
c = ir.Jump(1, self.loc2)
|
| 122 |
+
d = ir.Jump(2, self.loc1)
|
| 123 |
+
self.check(a, same=[b, c], different=[d])
|
| 124 |
+
|
| 125 |
+
def test_return(self):
|
| 126 |
+
a = ir.Return(self.var_a, self.loc1)
|
| 127 |
+
b = ir.Return(self.var_a, self.loc1)
|
| 128 |
+
c = ir.Return(self.var_a, self.loc2)
|
| 129 |
+
d = ir.Return(self.var_b, self.loc1)
|
| 130 |
+
self.check(a, same=[b, c], different=[d])
|
| 131 |
+
|
| 132 |
+
def test_raise(self):
|
| 133 |
+
a = ir.Raise(self.var_a, self.loc1)
|
| 134 |
+
b = ir.Raise(self.var_a, self.loc1)
|
| 135 |
+
c = ir.Raise(self.var_a, self.loc2)
|
| 136 |
+
d = ir.Raise(self.var_b, self.loc1)
|
| 137 |
+
self.check(a, same=[b, c], different=[d])
|
| 138 |
+
|
| 139 |
+
def test_staticraise(self):
|
| 140 |
+
a = ir.StaticRaise(AssertionError, None, self.loc1)
|
| 141 |
+
b = ir.StaticRaise(AssertionError, None, self.loc1)
|
| 142 |
+
c = ir.StaticRaise(AssertionError, None, self.loc2)
|
| 143 |
+
e = ir.StaticRaise(AssertionError, ("str",), self.loc1)
|
| 144 |
+
d = ir.StaticRaise(RuntimeError, None, self.loc1)
|
| 145 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 146 |
+
|
| 147 |
+
def test_branch(self):
|
| 148 |
+
a = ir.Branch(self.var_a, 1, 2, self.loc1)
|
| 149 |
+
b = ir.Branch(self.var_a, 1, 2, self.loc1)
|
| 150 |
+
c = ir.Branch(self.var_a, 1, 2, self.loc2)
|
| 151 |
+
d = ir.Branch(self.var_b, 1, 2, self.loc1)
|
| 152 |
+
e = ir.Branch(self.var_a, 2, 2, self.loc1)
|
| 153 |
+
f = ir.Branch(self.var_a, 1, 3, self.loc1)
|
| 154 |
+
self.check(a, same=[b, c], different=[d, e, f])
|
| 155 |
+
|
| 156 |
+
def test_expr(self):
|
| 157 |
+
a = ir.Expr('some_op', self.loc1)
|
| 158 |
+
b = ir.Expr('some_op', self.loc1)
|
| 159 |
+
c = ir.Expr('some_op', self.loc2)
|
| 160 |
+
d = ir.Expr('some_other_op', self.loc1)
|
| 161 |
+
self.check(a, same=[b, c], different=[d])
|
| 162 |
+
|
| 163 |
+
def test_setitem(self):
|
| 164 |
+
a = ir.SetItem(self.var_a, self.var_b, self.var_c, self.loc1)
|
| 165 |
+
b = ir.SetItem(self.var_a, self.var_b, self.var_c, self.loc1)
|
| 166 |
+
c = ir.SetItem(self.var_a, self.var_b, self.var_c, self.loc2)
|
| 167 |
+
d = ir.SetItem(self.var_d, self.var_b, self.var_c, self.loc1)
|
| 168 |
+
e = ir.SetItem(self.var_a, self.var_d, self.var_c, self.loc1)
|
| 169 |
+
f = ir.SetItem(self.var_a, self.var_b, self.var_d, self.loc1)
|
| 170 |
+
self.check(a, same=[b, c], different=[d, e, f])
|
| 171 |
+
|
| 172 |
+
def test_staticsetitem(self):
|
| 173 |
+
a = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_c, self.loc1)
|
| 174 |
+
b = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_c, self.loc1)
|
| 175 |
+
c = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_c, self.loc2)
|
| 176 |
+
d = ir.StaticSetItem(self.var_d, 1, self.var_b, self.var_c, self.loc1)
|
| 177 |
+
e = ir.StaticSetItem(self.var_a, 2, self.var_b, self.var_c, self.loc1)
|
| 178 |
+
f = ir.StaticSetItem(self.var_a, 1, self.var_d, self.var_c, self.loc1)
|
| 179 |
+
g = ir.StaticSetItem(self.var_a, 1, self.var_b, self.var_d, self.loc1)
|
| 180 |
+
self.check(a, same=[b, c], different=[d, e, f, g])
|
| 181 |
+
|
| 182 |
+
def test_delitem(self):
|
| 183 |
+
a = ir.DelItem(self.var_a, self.var_b, self.loc1)
|
| 184 |
+
b = ir.DelItem(self.var_a, self.var_b, self.loc1)
|
| 185 |
+
c = ir.DelItem(self.var_a, self.var_b, self.loc2)
|
| 186 |
+
d = ir.DelItem(self.var_c, self.var_b, self.loc1)
|
| 187 |
+
e = ir.DelItem(self.var_a, self.var_c, self.loc1)
|
| 188 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 189 |
+
|
| 190 |
+
def test_del(self):
|
| 191 |
+
a = ir.Del(self.var_a.name, self.loc1)
|
| 192 |
+
b = ir.Del(self.var_a.name, self.loc1)
|
| 193 |
+
c = ir.Del(self.var_a.name, self.loc2)
|
| 194 |
+
d = ir.Del(self.var_b.name, self.loc1)
|
| 195 |
+
self.check(a, same=[b, c], different=[d])
|
| 196 |
+
|
| 197 |
+
def test_setattr(self):
|
| 198 |
+
a = ir.SetAttr(self.var_a, 'foo', self.var_b, self.loc1)
|
| 199 |
+
b = ir.SetAttr(self.var_a, 'foo', self.var_b, self.loc1)
|
| 200 |
+
c = ir.SetAttr(self.var_a, 'foo', self.var_b, self.loc2)
|
| 201 |
+
d = ir.SetAttr(self.var_c, 'foo', self.var_b, self.loc1)
|
| 202 |
+
e = ir.SetAttr(self.var_a, 'bar', self.var_b, self.loc1)
|
| 203 |
+
f = ir.SetAttr(self.var_a, 'foo', self.var_c, self.loc1)
|
| 204 |
+
self.check(a, same=[b, c], different=[d, e, f])
|
| 205 |
+
|
| 206 |
+
def test_delattr(self):
|
| 207 |
+
a = ir.DelAttr(self.var_a, 'foo', self.loc1)
|
| 208 |
+
b = ir.DelAttr(self.var_a, 'foo', self.loc1)
|
| 209 |
+
c = ir.DelAttr(self.var_a, 'foo', self.loc2)
|
| 210 |
+
d = ir.DelAttr(self.var_c, 'foo', self.loc1)
|
| 211 |
+
e = ir.DelAttr(self.var_a, 'bar', self.loc1)
|
| 212 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 213 |
+
|
| 214 |
+
def test_assign(self):
|
| 215 |
+
a = ir.Assign(self.var_a, self.var_b, self.loc1)
|
| 216 |
+
b = ir.Assign(self.var_a, self.var_b, self.loc1)
|
| 217 |
+
c = ir.Assign(self.var_a, self.var_b, self.loc2)
|
| 218 |
+
d = ir.Assign(self.var_c, self.var_b, self.loc1)
|
| 219 |
+
e = ir.Assign(self.var_a, self.var_c, self.loc1)
|
| 220 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 221 |
+
|
| 222 |
+
def test_print(self):
|
| 223 |
+
a = ir.Print((self.var_a,), self.var_b, self.loc1)
|
| 224 |
+
b = ir.Print((self.var_a,), self.var_b, self.loc1)
|
| 225 |
+
c = ir.Print((self.var_a,), self.var_b, self.loc2)
|
| 226 |
+
d = ir.Print((self.var_c,), self.var_b, self.loc1)
|
| 227 |
+
e = ir.Print((self.var_a,), self.var_c, self.loc1)
|
| 228 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 229 |
+
|
| 230 |
+
def test_storemap(self):
|
| 231 |
+
a = ir.StoreMap(self.var_a, self.var_b, self.var_c, self.loc1)
|
| 232 |
+
b = ir.StoreMap(self.var_a, self.var_b, self.var_c, self.loc1)
|
| 233 |
+
c = ir.StoreMap(self.var_a, self.var_b, self.var_c, self.loc2)
|
| 234 |
+
d = ir.StoreMap(self.var_d, self.var_b, self.var_c, self.loc1)
|
| 235 |
+
e = ir.StoreMap(self.var_a, self.var_d, self.var_c, self.loc1)
|
| 236 |
+
f = ir.StoreMap(self.var_a, self.var_b, self.var_d, self.loc1)
|
| 237 |
+
self.check(a, same=[b, c], different=[d, e, f])
|
| 238 |
+
|
| 239 |
+
def test_yield(self):
|
| 240 |
+
a = ir.Yield(self.var_a, self.loc1, 0)
|
| 241 |
+
b = ir.Yield(self.var_a, self.loc1, 0)
|
| 242 |
+
c = ir.Yield(self.var_a, self.loc2, 0)
|
| 243 |
+
d = ir.Yield(self.var_b, self.loc1, 0)
|
| 244 |
+
e = ir.Yield(self.var_a, self.loc1, 1)
|
| 245 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 246 |
+
|
| 247 |
+
def test_enterwith(self):
|
| 248 |
+
a = ir.EnterWith(self.var_a, 0, 1, self.loc1)
|
| 249 |
+
b = ir.EnterWith(self.var_a, 0, 1, self.loc1)
|
| 250 |
+
c = ir.EnterWith(self.var_a, 0, 1, self.loc2)
|
| 251 |
+
d = ir.EnterWith(self.var_b, 0, 1, self.loc1)
|
| 252 |
+
e = ir.EnterWith(self.var_a, 1, 1, self.loc1)
|
| 253 |
+
f = ir.EnterWith(self.var_a, 0, 2, self.loc1)
|
| 254 |
+
self.check(a, same=[b, c], different=[d, e, f])
|
| 255 |
+
|
| 256 |
+
def test_arg(self):
|
| 257 |
+
a = ir.Arg('foo', 0, self.loc1)
|
| 258 |
+
b = ir.Arg('foo', 0, self.loc1)
|
| 259 |
+
c = ir.Arg('foo', 0, self.loc2)
|
| 260 |
+
d = ir.Arg('bar', 0, self.loc1)
|
| 261 |
+
e = ir.Arg('foo', 1, self.loc1)
|
| 262 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 263 |
+
|
| 264 |
+
def test_const(self):
|
| 265 |
+
a = ir.Const(1, self.loc1)
|
| 266 |
+
b = ir.Const(1, self.loc1)
|
| 267 |
+
c = ir.Const(1, self.loc2)
|
| 268 |
+
d = ir.Const(2, self.loc1)
|
| 269 |
+
self.check(a, same=[b, c], different=[d])
|
| 270 |
+
|
| 271 |
+
def test_global(self):
|
| 272 |
+
a = ir.Global('foo', 0, self.loc1)
|
| 273 |
+
b = ir.Global('foo', 0, self.loc1)
|
| 274 |
+
c = ir.Global('foo', 0, self.loc2)
|
| 275 |
+
d = ir.Global('bar', 0, self.loc1)
|
| 276 |
+
e = ir.Global('foo', 1, self.loc1)
|
| 277 |
+
self.check(a, same=[b, c], different=[d, e])
|
| 278 |
+
|
| 279 |
+
def test_var(self):
|
| 280 |
+
a = ir.Var(None, 'foo', self.loc1)
|
| 281 |
+
b = ir.Var(None, 'foo', self.loc1)
|
| 282 |
+
c = ir.Var(None, 'foo', self.loc2)
|
| 283 |
+
d = ir.Var(ir.Scope(None, ir.unknown_loc), 'foo', self.loc1)
|
| 284 |
+
e = ir.Var(None, 'bar', self.loc1)
|
| 285 |
+
self.check(a, same=[b, c, d], different=[e])
|
| 286 |
+
|
| 287 |
+
def test_undefinedtype(self):
|
| 288 |
+
a = ir.UndefinedType()
|
| 289 |
+
b = ir.UndefinedType()
|
| 290 |
+
self.check(a, same=[b])
|
| 291 |
+
|
| 292 |
+
def test_loop(self):
|
| 293 |
+
a = ir.Loop(1, 3)
|
| 294 |
+
b = ir.Loop(1, 3)
|
| 295 |
+
c = ir.Loop(2, 3)
|
| 296 |
+
d = ir.Loop(1, 4)
|
| 297 |
+
self.check(a, same=[b], different=[c, d])
|
| 298 |
+
|
| 299 |
+
def test_with(self):
|
| 300 |
+
a = ir.With(1, 3)
|
| 301 |
+
b = ir.With(1, 3)
|
| 302 |
+
c = ir.With(2, 3)
|
| 303 |
+
d = ir.With(1, 4)
|
| 304 |
+
self.check(a, same=[b], different=[c, d])
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# used later
|
| 308 |
+
_GLOBAL = 1234
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class TestIRCompounds(CheckEquality):
|
| 312 |
+
"""
|
| 313 |
+
Tests IR concepts that have state
|
| 314 |
+
"""
|
| 315 |
+
def test_varmap(self):
|
| 316 |
+
a = ir.VarMap()
|
| 317 |
+
a.define(self.var_a, 'foo')
|
| 318 |
+
a.define(self.var_b, 'bar')
|
| 319 |
+
|
| 320 |
+
b = ir.VarMap()
|
| 321 |
+
b.define(self.var_a, 'foo')
|
| 322 |
+
b.define(self.var_b, 'bar')
|
| 323 |
+
|
| 324 |
+
c = ir.VarMap()
|
| 325 |
+
c.define(self.var_a, 'foo')
|
| 326 |
+
c.define(self.var_c, 'bar')
|
| 327 |
+
|
| 328 |
+
self.check(a, same=[b], different=[c])
|
| 329 |
+
|
| 330 |
+
def test_block(self):
|
| 331 |
+
def gen_block():
|
| 332 |
+
parent = ir.Scope(None, self.loc1)
|
| 333 |
+
tmp = ir.Block(parent, self.loc2)
|
| 334 |
+
assign1 = ir.Assign(self.var_a, self.var_b, self.loc3)
|
| 335 |
+
assign2 = ir.Assign(self.var_a, self.var_c, self.loc3)
|
| 336 |
+
assign3 = ir.Assign(self.var_c, self.var_b, self.loc3)
|
| 337 |
+
tmp.append(assign1)
|
| 338 |
+
tmp.append(assign2)
|
| 339 |
+
tmp.append(assign3)
|
| 340 |
+
return tmp
|
| 341 |
+
|
| 342 |
+
a = gen_block()
|
| 343 |
+
b = gen_block()
|
| 344 |
+
c = gen_block().append(ir.Assign(self.var_a, self.var_b, self.loc3))
|
| 345 |
+
|
| 346 |
+
self.check(a, same=[b], different=[c])
|
| 347 |
+
|
| 348 |
+
def test_functionir(self):
|
| 349 |
+
|
| 350 |
+
def run_frontend(x):
|
| 351 |
+
return compiler.run_frontend(x, emit_dels=True)
|
| 352 |
+
|
| 353 |
+
# this creates a function full of all sorts of things to ensure the IR
|
| 354 |
+
# is pretty involved, it then compares two instances of the compiled
|
| 355 |
+
# function IR to check the IR is the same invariant of objects, and then
|
| 356 |
+
# a tiny mutation is made to the IR in the second function and detection
|
| 357 |
+
# of this change is checked.
|
| 358 |
+
def gen():
|
| 359 |
+
_FREEVAR = 0xCAFE
|
| 360 |
+
|
| 361 |
+
def foo(a, b, c=12, d=1j, e=None):
|
| 362 |
+
f = a + b
|
| 363 |
+
a += _FREEVAR
|
| 364 |
+
g = np.zeros(c, dtype=np.complex64)
|
| 365 |
+
h = f + g
|
| 366 |
+
i = 1j / d
|
| 367 |
+
if np.abs(i) > 0:
|
| 368 |
+
k = h / i
|
| 369 |
+
l = np.arange(1, c + 1)
|
| 370 |
+
with objmode():
|
| 371 |
+
print(e, k)
|
| 372 |
+
m = np.sqrt(l - g)
|
| 373 |
+
if np.abs(m[0]) < 1:
|
| 374 |
+
n = 0
|
| 375 |
+
for o in range(a):
|
| 376 |
+
n += 0
|
| 377 |
+
if np.abs(n) < 3:
|
| 378 |
+
break
|
| 379 |
+
n += m[2]
|
| 380 |
+
p = g / l
|
| 381 |
+
q = []
|
| 382 |
+
for r in range(len(p)):
|
| 383 |
+
q.append(p[r])
|
| 384 |
+
if r > 4 + 1:
|
| 385 |
+
with objmode(s='intp', t='complex128'):
|
| 386 |
+
s = 123
|
| 387 |
+
t = 5
|
| 388 |
+
if s > 122:
|
| 389 |
+
t += s
|
| 390 |
+
t += q[0] + _GLOBAL
|
| 391 |
+
|
| 392 |
+
return f + o + r + t + r + a + n
|
| 393 |
+
|
| 394 |
+
return foo
|
| 395 |
+
|
| 396 |
+
x = gen()
|
| 397 |
+
y = gen()
|
| 398 |
+
x_ir = run_frontend(x)
|
| 399 |
+
y_ir = run_frontend(y)
|
| 400 |
+
|
| 401 |
+
self.assertTrue(x_ir.equal_ir(y_ir))
|
| 402 |
+
|
| 403 |
+
def check_diffstr(string, pointing_at=[]):
|
| 404 |
+
lines = string.splitlines()
|
| 405 |
+
for item in pointing_at:
|
| 406 |
+
for l in lines:
|
| 407 |
+
if l.startswith('->'):
|
| 408 |
+
if item in l:
|
| 409 |
+
break
|
| 410 |
+
else:
|
| 411 |
+
raise AssertionError("Could not find %s " % item)
|
| 412 |
+
|
| 413 |
+
self.assertIn("IR is considered equivalent", x_ir.diff_str(y_ir))
|
| 414 |
+
|
| 415 |
+
# minor mutation, simply switch branch targets on last branch
|
| 416 |
+
for label in reversed(list(y_ir.blocks.keys())):
|
| 417 |
+
blk = y_ir.blocks[label]
|
| 418 |
+
if isinstance(blk.body[-1], ir.Branch):
|
| 419 |
+
ref = blk.body[-1]
|
| 420 |
+
ref.truebr, ref.falsebr = ref.falsebr, ref.truebr
|
| 421 |
+
break
|
| 422 |
+
|
| 423 |
+
check_diffstr(x_ir.diff_str(y_ir), ['branch'])
|
| 424 |
+
|
| 425 |
+
z = gen()
|
| 426 |
+
self.assertFalse(x_ir.equal_ir(y_ir))
|
| 427 |
+
|
| 428 |
+
z_ir = run_frontend(z)
|
| 429 |
+
|
| 430 |
+
change_set = set()
|
| 431 |
+
for label in reversed(list(z_ir.blocks.keys())):
|
| 432 |
+
blk = z_ir.blocks[label]
|
| 433 |
+
ref = blk.body[:-1]
|
| 434 |
+
idx = None
|
| 435 |
+
for i in range(len(ref) - 1):
|
| 436 |
+
# look for two adjacent Del
|
| 437 |
+
if (isinstance(ref[i], ir.Del) and
|
| 438 |
+
isinstance(ref[i + 1], ir.Del)):
|
| 439 |
+
idx = i
|
| 440 |
+
break
|
| 441 |
+
if idx is not None:
|
| 442 |
+
b = blk.body
|
| 443 |
+
change_set.add(str(b[idx + 1]))
|
| 444 |
+
change_set.add(str(b[idx]))
|
| 445 |
+
b[idx], b[idx + 1] = b[idx + 1], b[idx]
|
| 446 |
+
break
|
| 447 |
+
|
| 448 |
+
# ensure that a mutation occurred.
|
| 449 |
+
self.assertTrue(change_set)
|
| 450 |
+
|
| 451 |
+
self.assertFalse(x_ir.equal_ir(z_ir))
|
| 452 |
+
self.assertEqual(len(change_set), 2)
|
| 453 |
+
for item in change_set:
|
| 454 |
+
self.assertTrue(item.startswith('del '))
|
| 455 |
+
check_diffstr(x_ir.diff_str(z_ir), change_set)
|
| 456 |
+
|
| 457 |
+
def foo(a, b):
|
| 458 |
+
c = a * 2
|
| 459 |
+
d = c + b
|
| 460 |
+
e = np.sqrt(d)
|
| 461 |
+
return e
|
| 462 |
+
|
| 463 |
+
def bar(a, b): # same as foo
|
| 464 |
+
c = a * 2
|
| 465 |
+
d = c + b
|
| 466 |
+
e = np.sqrt(d)
|
| 467 |
+
return e
|
| 468 |
+
|
| 469 |
+
def baz(a, b):
|
| 470 |
+
c = a * 2
|
| 471 |
+
d = b + c
|
| 472 |
+
e = np.sqrt(d + 1)
|
| 473 |
+
return e
|
| 474 |
+
|
| 475 |
+
foo_ir = run_frontend(foo)
|
| 476 |
+
bar_ir = run_frontend(bar)
|
| 477 |
+
self.assertTrue(foo_ir.equal_ir(bar_ir))
|
| 478 |
+
self.assertIn("IR is considered equivalent", foo_ir.diff_str(bar_ir))
|
| 479 |
+
|
| 480 |
+
baz_ir = run_frontend(baz)
|
| 481 |
+
self.assertFalse(foo_ir.equal_ir(baz_ir))
|
| 482 |
+
tmp = foo_ir.diff_str(baz_ir)
|
| 483 |
+
self.assertIn("Other block contains more statements", tmp)
|
| 484 |
+
check_diffstr(tmp, ["c + b", "b + c"])
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class TestIRPedanticChecks(TestCase):
|
| 488 |
+
def test_var_in_scope_assumption(self):
|
| 489 |
+
# Create a pass that clears ir.Scope in ir.Block
|
| 490 |
+
@register_pass(mutates_CFG=False, analysis_only=False)
|
| 491 |
+
class RemoveVarInScope(FunctionPass):
|
| 492 |
+
_name = "_remove_var_in_scope"
|
| 493 |
+
|
| 494 |
+
def __init__(self):
|
| 495 |
+
FunctionPass.__init__(self)
|
| 496 |
+
|
| 497 |
+
# implement method to do the work, "state" is the internal compiler
|
| 498 |
+
# state from the CompilerBase instance.
|
| 499 |
+
def run_pass(self, state):
|
| 500 |
+
func_ir = state.func_ir
|
| 501 |
+
# walk the blocks
|
| 502 |
+
for blk in func_ir.blocks.values():
|
| 503 |
+
oldscope = blk.scope
|
| 504 |
+
# put in an empty Scope
|
| 505 |
+
blk.scope = ir.Scope(parent=oldscope.parent,
|
| 506 |
+
loc=oldscope.loc)
|
| 507 |
+
return True
|
| 508 |
+
|
| 509 |
+
# Create a pass that always fails, to stop the compiler
|
| 510 |
+
@register_pass(mutates_CFG=False, analysis_only=False)
|
| 511 |
+
class FailPass(FunctionPass):
|
| 512 |
+
_name = "_fail"
|
| 513 |
+
|
| 514 |
+
def __init__(self, *args, **kwargs):
|
| 515 |
+
FunctionPass.__init__(self)
|
| 516 |
+
|
| 517 |
+
def run_pass(self, state):
|
| 518 |
+
# This is unreachable. SSA pass should have raised before this
|
| 519 |
+
# pass when run with `error.NumbaPedanticWarning`s raised as
|
| 520 |
+
# errors.
|
| 521 |
+
raise AssertionError("unreachable")
|
| 522 |
+
|
| 523 |
+
class MyCompiler(CompilerBase):
|
| 524 |
+
def define_pipelines(self):
|
| 525 |
+
pm = PassManager("testing pm")
|
| 526 |
+
pm.add_pass(TranslateByteCode, "analyzing bytecode")
|
| 527 |
+
pm.add_pass(IRProcessing, "processing IR")
|
| 528 |
+
pm.add_pass(RemoveVarInScope, "_remove_var_in_scope")
|
| 529 |
+
pm.add_pass(ReconstructSSA, "ssa")
|
| 530 |
+
pm.add_pass(FailPass, "_fail")
|
| 531 |
+
pm.finalize()
|
| 532 |
+
return [pm]
|
| 533 |
+
|
| 534 |
+
@njit(pipeline_class=MyCompiler)
|
| 535 |
+
def dummy(x):
|
| 536 |
+
# To trigger SSA and the pedantic check, this function must have
|
| 537 |
+
# multiple assignments to the same variable in different blocks.
|
| 538 |
+
a = 1
|
| 539 |
+
b = 2
|
| 540 |
+
if a < b:
|
| 541 |
+
a = 2
|
| 542 |
+
else:
|
| 543 |
+
b = 3
|
| 544 |
+
return a, b
|
| 545 |
+
|
| 546 |
+
with warnings.catch_warnings():
|
| 547 |
+
# Make NumbaPedanticWarning an error
|
| 548 |
+
warnings.simplefilter("error", errors.NumbaPedanticWarning)
|
| 549 |
+
# Catch NumbaIRAssumptionWarning
|
| 550 |
+
with self.assertRaises(errors.NumbaIRAssumptionWarning) as raises:
|
| 551 |
+
dummy(1)
|
| 552 |
+
# Verify the error message
|
| 553 |
+
self.assertRegex(
|
| 554 |
+
str(raises.exception),
|
| 555 |
+
r"variable '[a-z]' is not in scope",
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
if __name__ == '__main__':
|
| 560 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_jit_module.py
AD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9 |
+
import unittest
|
| 10 |
+
from numba.tests.support import SerialMixin, create_temp_module
|
| 11 |
+
from numba.core import dispatcher
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@contextlib.contextmanager
|
| 15 |
+
def captured_logs(l):
|
| 16 |
+
try:
|
| 17 |
+
buffer = StringIO()
|
| 18 |
+
handler = logging.StreamHandler(buffer)
|
| 19 |
+
l.addHandler(handler)
|
| 20 |
+
yield buffer
|
| 21 |
+
finally:
|
| 22 |
+
l.removeHandler(handler)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TestJitModule(SerialMixin, unittest.TestCase):
|
| 26 |
+
|
| 27 |
+
source_lines = """
|
| 28 |
+
from numba import jit_module
|
| 29 |
+
|
| 30 |
+
def inc(x):
|
| 31 |
+
return x + 1
|
| 32 |
+
|
| 33 |
+
def add(x, y):
|
| 34 |
+
return x + y
|
| 35 |
+
|
| 36 |
+
def inc_add(x):
|
| 37 |
+
y = inc(x)
|
| 38 |
+
return add(x, y)
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
mean = np.mean
|
| 42 |
+
|
| 43 |
+
class Foo(object):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
jit_module({jit_options})
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def test_create_temp_jitted_module(self):
|
| 50 |
+
sys_path_original = list(sys.path)
|
| 51 |
+
sys_modules_original = dict(sys.modules)
|
| 52 |
+
with create_temp_module(self.source_lines) as test_module:
|
| 53 |
+
temp_module_dir = os.path.dirname(test_module.__file__)
|
| 54 |
+
self.assertEqual(temp_module_dir, sys.path[0])
|
| 55 |
+
self.assertEqual(sys.path[1:], sys_path_original)
|
| 56 |
+
self.assertTrue(test_module.__name__ in sys.modules)
|
| 57 |
+
# Test that modifications to sys.path / sys.modules are reverted
|
| 58 |
+
self.assertEqual(sys.path, sys_path_original)
|
| 59 |
+
self.assertEqual(sys.modules, sys_modules_original)
|
| 60 |
+
|
| 61 |
+
def test_create_temp_jitted_module_with_exception(self):
|
| 62 |
+
try:
|
| 63 |
+
sys_path_original = list(sys.path)
|
| 64 |
+
sys_modules_original = dict(sys.modules)
|
| 65 |
+
with create_temp_module(self.source_lines):
|
| 66 |
+
raise ValueError("Something went wrong!")
|
| 67 |
+
except ValueError:
|
| 68 |
+
# Test that modifications to sys.path / sys.modules are reverted
|
| 69 |
+
self.assertEqual(sys.path, sys_path_original)
|
| 70 |
+
self.assertEqual(sys.modules, sys_modules_original)
|
| 71 |
+
|
| 72 |
+
def test_jit_module(self):
|
| 73 |
+
with create_temp_module(self.source_lines) as test_module:
|
| 74 |
+
self.assertIsInstance(test_module.inc, dispatcher.Dispatcher)
|
| 75 |
+
self.assertIsInstance(test_module.add, dispatcher.Dispatcher)
|
| 76 |
+
self.assertIsInstance(test_module.inc_add, dispatcher.Dispatcher)
|
| 77 |
+
self.assertTrue(test_module.mean is np.mean)
|
| 78 |
+
self.assertTrue(inspect.isclass(test_module.Foo))
|
| 79 |
+
|
| 80 |
+
# Test output of jitted functions is as expected
|
| 81 |
+
x, y = 1.7, 2.3
|
| 82 |
+
self.assertEqual(test_module.inc(x),
|
| 83 |
+
test_module.inc.py_func(x))
|
| 84 |
+
self.assertEqual(test_module.add(x, y),
|
| 85 |
+
test_module.add.py_func(x, y))
|
| 86 |
+
self.assertEqual(test_module.inc_add(x),
|
| 87 |
+
test_module.inc_add.py_func(x))
|
| 88 |
+
|
| 89 |
+
def test_jit_module_jit_options(self):
|
| 90 |
+
jit_options = {"nopython": True,
|
| 91 |
+
"nogil": False,
|
| 92 |
+
"error_model": "numpy",
|
| 93 |
+
"boundscheck": False,
|
| 94 |
+
}
|
| 95 |
+
with create_temp_module(self.source_lines,
|
| 96 |
+
**jit_options) as test_module:
|
| 97 |
+
self.assertEqual(test_module.inc.targetoptions, jit_options)
|
| 98 |
+
|
| 99 |
+
def test_jit_module_jit_options_override(self):
|
| 100 |
+
source_lines = """
|
| 101 |
+
from numba import jit, jit_module
|
| 102 |
+
|
| 103 |
+
@jit(nogil=True, forceobj=True)
|
| 104 |
+
def inc(x):
|
| 105 |
+
return x + 1
|
| 106 |
+
|
| 107 |
+
def add(x, y):
|
| 108 |
+
return x + y
|
| 109 |
+
|
| 110 |
+
jit_module({jit_options})
|
| 111 |
+
"""
|
| 112 |
+
jit_options = {"nopython": True,
|
| 113 |
+
"error_model": "numpy",
|
| 114 |
+
"boundscheck": False,
|
| 115 |
+
}
|
| 116 |
+
with create_temp_module(source_lines=source_lines,
|
| 117 |
+
**jit_options) as test_module:
|
| 118 |
+
self.assertEqual(test_module.add.targetoptions, jit_options)
|
| 119 |
+
# Test that manual jit-wrapping overrides jit_module options,
|
| 120 |
+
# `forceobj` will automatically apply `nopython=False`.
|
| 121 |
+
self.assertEqual(test_module.inc.targetoptions,
|
| 122 |
+
{'nogil': True, 'forceobj': True,
|
| 123 |
+
'boundscheck': None, 'nopython': False})
|
| 124 |
+
|
| 125 |
+
def test_jit_module_logging_output(self):
|
| 126 |
+
logger = logging.getLogger('numba.core.decorators')
|
| 127 |
+
logger.setLevel(logging.DEBUG)
|
| 128 |
+
jit_options = {"nopython": True,
|
| 129 |
+
"error_model": "numpy",
|
| 130 |
+
}
|
| 131 |
+
with captured_logs(logger) as logs:
|
| 132 |
+
with create_temp_module(self.source_lines,
|
| 133 |
+
**jit_options) as test_module:
|
| 134 |
+
logs = logs.getvalue()
|
| 135 |
+
expected = ["Auto decorating function",
|
| 136 |
+
"from module {}".format(test_module.__name__),
|
| 137 |
+
"with jit and options: {}".format(jit_options)]
|
| 138 |
+
self.assertTrue(all(i in logs for i in expected))
|
| 139 |
+
|
| 140 |
+
def test_jit_module_logging_level(self):
|
| 141 |
+
logger = logging.getLogger('numba.core.decorators')
|
| 142 |
+
# Test there's no logging for INFO level
|
| 143 |
+
logger.setLevel(logging.INFO)
|
| 144 |
+
with captured_logs(logger) as logs:
|
| 145 |
+
with create_temp_module(self.source_lines):
|
| 146 |
+
self.assertEqual(logs.getvalue(), '')
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Tests for the compiler components of the Numba typed-list.
|
| 2 |
+
|
| 3 |
+
The tests here should exercise everything within an `@njit` context.
|
| 4 |
+
Importantly, the tests should not return a typed list from within such a
|
| 5 |
+
context as this would require code from numba/typed/typedlist.py (this is
|
| 6 |
+
tested separately). Tests in this file build on each other in the order of
|
| 7 |
+
writing. For example, the first test, tests the creation, append and len of the
|
| 8 |
+
list. These are the barebones to do anything useful with a list. The subsequent
|
| 9 |
+
test for getitem assumes makes use of these three operations and therefore
|
| 10 |
+
assumes that they work.
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from textwrap import dedent
|
| 15 |
+
|
| 16 |
+
from numba import njit
|
| 17 |
+
from numba import int32
|
| 18 |
+
from numba.extending import register_jitable
|
| 19 |
+
from numba.core import types
|
| 20 |
+
from numba.core.errors import TypingError
|
| 21 |
+
from numba.tests.support import (TestCase, MemoryLeakMixin, override_config,
|
| 22 |
+
forbid_codegen)
|
| 23 |
+
from numba.typed import listobject, List
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TestCreateAppendLength(MemoryLeakMixin, TestCase):
|
| 27 |
+
"""Test list creation, append and len. """
|
| 28 |
+
|
| 29 |
+
def test_list_create(self):
|
| 30 |
+
@njit
|
| 31 |
+
def foo(n):
|
| 32 |
+
l = listobject.new_list(int32)
|
| 33 |
+
for i in range(n):
|
| 34 |
+
l.append(i)
|
| 35 |
+
return len(l)
|
| 36 |
+
|
| 37 |
+
for i in (0, 1, 2, 100):
|
| 38 |
+
self.assertEqual(foo(i), i)
|
| 39 |
+
|
| 40 |
+
def test_list_create_no_jit(self):
|
| 41 |
+
with override_config('DISABLE_JIT', True):
|
| 42 |
+
with forbid_codegen():
|
| 43 |
+
l = listobject.new_list(int32)
|
| 44 |
+
self.assertEqual(type(l), list)
|
| 45 |
+
|
| 46 |
+
def test_nonempty_list_create_no_jit(self):
|
| 47 |
+
# See Issue #6001: https://github.com/numba/numba/issues/6001
|
| 48 |
+
with override_config('DISABLE_JIT', True):
|
| 49 |
+
with forbid_codegen():
|
| 50 |
+
l = List([1, 2, 3])
|
| 51 |
+
self.assertEqual(type(l), list)
|
| 52 |
+
self.assertEqual(l, [1, 2, 3])
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class TestBool(MemoryLeakMixin, TestCase):
|
| 56 |
+
"""Test list bool."""
|
| 57 |
+
|
| 58 |
+
def test_list_bool(self):
|
| 59 |
+
@njit
|
| 60 |
+
def foo(n):
|
| 61 |
+
l = listobject.new_list(int32)
|
| 62 |
+
for i in range(n):
|
| 63 |
+
l.append(i)
|
| 64 |
+
return bool(l)
|
| 65 |
+
|
| 66 |
+
for i in (0, 1, 2, 100):
|
| 67 |
+
self.assertEqual(foo(i), i > 0)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class TestAllocation(MemoryLeakMixin, TestCase):
|
| 71 |
+
|
| 72 |
+
def test_list_allocation(self):
|
| 73 |
+
@njit
|
| 74 |
+
def foo_kwarg(n):
|
| 75 |
+
l = listobject.new_list(int32, allocated=n)
|
| 76 |
+
return l._allocated()
|
| 77 |
+
|
| 78 |
+
for i in range(16):
|
| 79 |
+
self.assertEqual(foo_kwarg(i), i)
|
| 80 |
+
|
| 81 |
+
@njit
|
| 82 |
+
def foo_posarg(n):
|
| 83 |
+
l = listobject.new_list(int32, n)
|
| 84 |
+
return l._allocated()
|
| 85 |
+
for i in range(16):
|
| 86 |
+
self.assertEqual(foo_posarg(i), i)
|
| 87 |
+
|
| 88 |
+
def test_list_allocation_negative(self):
|
| 89 |
+
@njit
|
| 90 |
+
def foo():
|
| 91 |
+
l = listobject.new_list(int32, -1)
|
| 92 |
+
return l._allocated()
|
| 93 |
+
|
| 94 |
+
with self.assertRaises(RuntimeError) as raises:
|
| 95 |
+
self.assertEqual(foo(), -1)
|
| 96 |
+
self.assertIn(
|
| 97 |
+
"expecting *allocated* to be >= 0",
|
| 98 |
+
str(raises.exception),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TestToFromMeminfo(MemoryLeakMixin, TestCase):
|
| 103 |
+
|
| 104 |
+
def test_list_to_from_meminfo(self):
|
| 105 |
+
"""
|
| 106 |
+
Exercise listobject.{_as_meminfo, _from_meminfo}
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
@njit
|
| 110 |
+
def boxer():
|
| 111 |
+
l = listobject.new_list(int32)
|
| 112 |
+
for i in range(10, 20):
|
| 113 |
+
l.append(i)
|
| 114 |
+
return listobject._as_meminfo(l)
|
| 115 |
+
|
| 116 |
+
lsttype = types.ListType(int32)
|
| 117 |
+
|
| 118 |
+
@njit
|
| 119 |
+
def unboxer(mi):
|
| 120 |
+
l = listobject._from_meminfo(mi, lsttype)
|
| 121 |
+
return l[0], l[1], l[2], l[3], l[4], l[5], l[6], l[7], l[8], l[9]
|
| 122 |
+
|
| 123 |
+
mi = boxer()
|
| 124 |
+
self.assertEqual(mi.refcount, 1)
|
| 125 |
+
|
| 126 |
+
received = list(unboxer(mi))
|
| 127 |
+
expected = list(range(10, 20))
|
| 128 |
+
self.assertEqual(received, expected)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class TestGetitem(MemoryLeakMixin, TestCase):
|
| 132 |
+
"""Test list getitem. """
|
| 133 |
+
|
| 134 |
+
def test_list_getitem_singleton(self):
|
| 135 |
+
@njit
|
| 136 |
+
def foo(n):
|
| 137 |
+
l = listobject.new_list(int32)
|
| 138 |
+
l.append(n)
|
| 139 |
+
return l[0]
|
| 140 |
+
|
| 141 |
+
self.assertEqual(foo(0), 0)
|
| 142 |
+
|
| 143 |
+
def test_list_getitem_singleton_negtive_index(self):
|
| 144 |
+
@njit
|
| 145 |
+
def foo(n):
|
| 146 |
+
l = listobject.new_list(int32)
|
| 147 |
+
l.append(n)
|
| 148 |
+
return l[-1]
|
| 149 |
+
|
| 150 |
+
self.assertEqual(foo(0), 0)
|
| 151 |
+
|
| 152 |
+
def test_list_getitem_multiple(self):
|
| 153 |
+
@njit
|
| 154 |
+
def foo(i):
|
| 155 |
+
l = listobject.new_list(int32)
|
| 156 |
+
for j in range(10, 20):
|
| 157 |
+
l.append(j)
|
| 158 |
+
return l[i]
|
| 159 |
+
|
| 160 |
+
for i,j in ((0, 10), (9, 19), (4, 14), (-5, 15), (-1, 19), (-10, 10)):
|
| 161 |
+
self.assertEqual(foo(i), j)
|
| 162 |
+
|
| 163 |
+
def test_list_getitem_empty_index_error(self):
|
| 164 |
+
self.disable_leak_check()
|
| 165 |
+
|
| 166 |
+
@njit
|
| 167 |
+
def foo(i):
|
| 168 |
+
l = listobject.new_list(int32)
|
| 169 |
+
return l[i]
|
| 170 |
+
|
| 171 |
+
for i in (1, 0, -1):
|
| 172 |
+
with self.assertRaises(IndexError) as raises:
|
| 173 |
+
foo(i)
|
| 174 |
+
self.assertIn(
|
| 175 |
+
"list index out of range",
|
| 176 |
+
str(raises.exception),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def test_list_getitem_multiple_index_error(self):
|
| 180 |
+
self.disable_leak_check()
|
| 181 |
+
|
| 182 |
+
@njit
|
| 183 |
+
def foo(i):
|
| 184 |
+
l = listobject.new_list(int32)
|
| 185 |
+
for j in range(10, 20):
|
| 186 |
+
l.append(j)
|
| 187 |
+
return l[i]
|
| 188 |
+
|
| 189 |
+
for i in (10, -11):
|
| 190 |
+
with self.assertRaises(IndexError) as raises:
|
| 191 |
+
foo(i)
|
| 192 |
+
self.assertIn(
|
| 193 |
+
"list index out of range",
|
| 194 |
+
str(raises.exception),
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def test_list_getitem_empty_typing_error(self):
|
| 198 |
+
self.disable_leak_check()
|
| 199 |
+
|
| 200 |
+
@njit
|
| 201 |
+
def foo(i):
|
| 202 |
+
l = listobject.new_list(int32)
|
| 203 |
+
return l[i]
|
| 204 |
+
|
| 205 |
+
for i in "xyz", 1.0, 1j:
|
| 206 |
+
with self.assertRaises(TypingError) as raises:
|
| 207 |
+
foo(i)
|
| 208 |
+
self.assertIn(
|
| 209 |
+
"list indices must be integers or slices",
|
| 210 |
+
str(raises.exception),
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
def test_list_getitem_integer_types_as_index(self):
|
| 214 |
+
|
| 215 |
+
@njit
|
| 216 |
+
def foo(i):
|
| 217 |
+
l = listobject.new_list(int32)
|
| 218 |
+
l.append(0)
|
| 219 |
+
return l[i]
|
| 220 |
+
|
| 221 |
+
# try all signed integers and make sure they are cast
|
| 222 |
+
for t in (types.signed_domain
|
| 223 |
+
):
|
| 224 |
+
self.assertEqual(foo((t(0))), 0)
|
| 225 |
+
|
| 226 |
+
def test_list_getitem_different_sized_uint_index(self):
|
| 227 |
+
# Checks that the index type cast and ext/trunc to the
|
| 228 |
+
# type of the length is correct, both wraparound and
|
| 229 |
+
# direct index is tested via -1/0.
|
| 230 |
+
|
| 231 |
+
for ty in types.unsigned_domain:
|
| 232 |
+
@njit
|
| 233 |
+
def foo():
|
| 234 |
+
l = listobject.new_list(int32)
|
| 235 |
+
l.append(7)
|
| 236 |
+
return l[ty(0)]
|
| 237 |
+
|
| 238 |
+
self.assertEqual(foo(), 7)
|
| 239 |
+
|
| 240 |
+
def test_list_getitem_different_sized_int_index(self):
|
| 241 |
+
# Checks that the index type cast and ext/trunc to the
|
| 242 |
+
# type of the length is correct, both wraparound and
|
| 243 |
+
# direct index is tested via -1/0.
|
| 244 |
+
|
| 245 |
+
for ty in types.signed_domain:
|
| 246 |
+
@njit
|
| 247 |
+
def foo():
|
| 248 |
+
l = listobject.new_list(int32)
|
| 249 |
+
l.append(7)
|
| 250 |
+
return l[ty(0)], l[ty(-1)]
|
| 251 |
+
|
| 252 |
+
self.assertEqual(foo(), (7, 7))
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class TestGetitemSlice(MemoryLeakMixin, TestCase):
|
| 256 |
+
"""Test list getitem when indexing with slices. """
|
| 257 |
+
|
| 258 |
+
def test_list_getitem_empty_slice_defaults(self):
|
| 259 |
+
@njit
|
| 260 |
+
def foo():
|
| 261 |
+
l = listobject.new_list(int32)
|
| 262 |
+
n = l[:]
|
| 263 |
+
return len(n)
|
| 264 |
+
|
| 265 |
+
self.assertEqual(foo(), 0)
|
| 266 |
+
|
| 267 |
+
def test_list_getitem_singleton_slice_defaults(self):
|
| 268 |
+
@njit
|
| 269 |
+
def foo():
|
| 270 |
+
l = listobject.new_list(int32)
|
| 271 |
+
l.append(0)
|
| 272 |
+
n = l[:]
|
| 273 |
+
return len(n)
|
| 274 |
+
|
| 275 |
+
self.assertEqual(foo(), 1)
|
| 276 |
+
|
| 277 |
+
def test_list_getitem_multiple_slice_defaults(self):
|
| 278 |
+
@njit
|
| 279 |
+
def foo(i):
|
| 280 |
+
l = listobject.new_list(int32)
|
| 281 |
+
for j in range(10, 20):
|
| 282 |
+
l.append(j)
|
| 283 |
+
n = l[:]
|
| 284 |
+
return n[i]
|
| 285 |
+
|
| 286 |
+
for i,j in ((0, 10), (9, 19), (4, 14), (-5, 15), (-1, 19), (-10, 10)):
|
| 287 |
+
self.assertEqual(foo(i), j)
|
| 288 |
+
|
| 289 |
+
def test_list_getitem_multiple_slice_pos_start(self):
|
| 290 |
+
@njit
|
| 291 |
+
def foo():
|
| 292 |
+
l = listobject.new_list(int32)
|
| 293 |
+
for j in range(10, 20):
|
| 294 |
+
l.append(j)
|
| 295 |
+
n = l[5:]
|
| 296 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 297 |
+
|
| 298 |
+
length, items = foo()
|
| 299 |
+
self.assertEqual(length, 5)
|
| 300 |
+
self.assertEqual(items, (15, 16, 17, 18, 19))
|
| 301 |
+
|
| 302 |
+
def test_list_getitem_multiple_slice_pos_stop(self):
|
| 303 |
+
@njit
|
| 304 |
+
def foo():
|
| 305 |
+
l = listobject.new_list(int32)
|
| 306 |
+
for j in range(10, 20):
|
| 307 |
+
l.append(j)
|
| 308 |
+
n = l[:5]
|
| 309 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 310 |
+
|
| 311 |
+
length, items = foo()
|
| 312 |
+
self.assertEqual(length, 5)
|
| 313 |
+
self.assertEqual(items, (10, 11, 12, 13, 14))
|
| 314 |
+
|
| 315 |
+
def test_list_getitem_multiple_slice_pos_start_pos_stop(self):
|
| 316 |
+
@njit
|
| 317 |
+
def foo():
|
| 318 |
+
l = listobject.new_list(int32)
|
| 319 |
+
for j in range(10, 20):
|
| 320 |
+
l.append(j)
|
| 321 |
+
n = l[2:7]
|
| 322 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 323 |
+
|
| 324 |
+
length, items = foo()
|
| 325 |
+
self.assertEqual(length, 5)
|
| 326 |
+
self.assertEqual(items, (12, 13, 14, 15, 16))
|
| 327 |
+
|
| 328 |
+
def test_list_getitem_multiple_slice_pos_start_pos_stop_pos_step(self):
|
| 329 |
+
@njit
|
| 330 |
+
def foo():
|
| 331 |
+
l = listobject.new_list(int32)
|
| 332 |
+
for j in range(10, 20):
|
| 333 |
+
l.append(j)
|
| 334 |
+
n = l[1:9:2]
|
| 335 |
+
return len(n), (n[0], n[1], n[2], n[3])
|
| 336 |
+
|
| 337 |
+
length, items = foo()
|
| 338 |
+
self.assertEqual(length, 4)
|
| 339 |
+
self.assertEqual(items, (11, 13, 15, 17))
|
| 340 |
+
|
| 341 |
+
def test_list_getitem_multiple_slice_neg_start(self):
|
| 342 |
+
@njit
|
| 343 |
+
def foo():
|
| 344 |
+
l = listobject.new_list(int32)
|
| 345 |
+
for j in range(10, 20):
|
| 346 |
+
l.append(j)
|
| 347 |
+
n = l[-5:]
|
| 348 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 349 |
+
|
| 350 |
+
length, items = foo()
|
| 351 |
+
self.assertEqual(length, 5)
|
| 352 |
+
self.assertEqual(items, (15, 16, 17, 18, 19))
|
| 353 |
+
|
| 354 |
+
def test_list_getitem_multiple_slice_neg_stop(self):
|
| 355 |
+
@njit
|
| 356 |
+
def foo():
|
| 357 |
+
l = listobject.new_list(int32)
|
| 358 |
+
for j in range(10, 20):
|
| 359 |
+
l.append(j)
|
| 360 |
+
n = l[:-5]
|
| 361 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 362 |
+
|
| 363 |
+
length, items = foo()
|
| 364 |
+
self.assertEqual(length, 5)
|
| 365 |
+
self.assertEqual(items, (10, 11, 12, 13, 14))
|
| 366 |
+
|
| 367 |
+
def test_list_getitem_multiple_slice_neg_step(self):
|
| 368 |
+
@njit
|
| 369 |
+
def foo():
|
| 370 |
+
l = listobject.new_list(int32)
|
| 371 |
+
for j in range(10, 20):
|
| 372 |
+
l.append(j)
|
| 373 |
+
n = l[::-2]
|
| 374 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 375 |
+
|
| 376 |
+
length, items = foo()
|
| 377 |
+
self.assertEqual(length, 5)
|
| 378 |
+
self.assertEqual(items, (19, 17, 15, 13, 11))
|
| 379 |
+
|
| 380 |
+
def test_list_getitem_multiple_slice_pos_start_neg_step(self):
|
| 381 |
+
@njit
|
| 382 |
+
def foo():
|
| 383 |
+
l = listobject.new_list(int32)
|
| 384 |
+
for j in range(10, 20):
|
| 385 |
+
l.append(j)
|
| 386 |
+
n = l[4::-1]
|
| 387 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 388 |
+
|
| 389 |
+
length, items = foo()
|
| 390 |
+
self.assertEqual(length, 5)
|
| 391 |
+
self.assertEqual(items, (14, 13, 12, 11, 10))
|
| 392 |
+
|
| 393 |
+
def test_list_getitem_multiple_slice_neg_start_neg_step(self):
|
| 394 |
+
@njit
|
| 395 |
+
def foo():
|
| 396 |
+
l = listobject.new_list(int32)
|
| 397 |
+
for j in range(10, 20):
|
| 398 |
+
l.append(j)
|
| 399 |
+
n = l[-6::-1]
|
| 400 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 401 |
+
|
| 402 |
+
length, items = foo()
|
| 403 |
+
self.assertEqual(length, 5)
|
| 404 |
+
self.assertEqual(items, (14, 13, 12, 11, 10))
|
| 405 |
+
|
| 406 |
+
def test_list_getitem_multiple_slice_pos_stop_neg_step(self):
|
| 407 |
+
@njit
|
| 408 |
+
def foo():
|
| 409 |
+
l = listobject.new_list(int32)
|
| 410 |
+
for j in range(10, 20):
|
| 411 |
+
l.append(j)
|
| 412 |
+
n = l[:4:-1]
|
| 413 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 414 |
+
|
| 415 |
+
length, items = foo()
|
| 416 |
+
self.assertEqual(length, 5)
|
| 417 |
+
self.assertEqual(items, (19, 18, 17, 16, 15))
|
| 418 |
+
|
| 419 |
+
def test_list_getitem_multiple_slice_neg_stop_neg_step(self):
|
| 420 |
+
@njit
|
| 421 |
+
def foo():
|
| 422 |
+
l = listobject.new_list(int32)
|
| 423 |
+
for j in range(10, 20):
|
| 424 |
+
l.append(j)
|
| 425 |
+
n = l[:-6:-1]
|
| 426 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 427 |
+
|
| 428 |
+
length, items = foo()
|
| 429 |
+
self.assertEqual(length, 5)
|
| 430 |
+
self.assertEqual(items, (19, 18, 17, 16, 15))
|
| 431 |
+
|
| 432 |
+
def test_list_getitem_multiple_slice_pos_start_pos_stop_neg_step(self):
|
| 433 |
+
@njit
|
| 434 |
+
def foo():
|
| 435 |
+
l = listobject.new_list(int32)
|
| 436 |
+
for j in range(10, 20):
|
| 437 |
+
l.append(j)
|
| 438 |
+
n = l[8:3:-1]
|
| 439 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 440 |
+
|
| 441 |
+
length, items = foo()
|
| 442 |
+
self.assertEqual(length, 5)
|
| 443 |
+
self.assertEqual(items, (18, 17, 16, 15, 14))
|
| 444 |
+
|
| 445 |
+
def test_list_getitem_multiple_slice_neg_start_neg_stop_neg_step(self):
|
| 446 |
+
@njit
|
| 447 |
+
def foo():
|
| 448 |
+
l = listobject.new_list(int32)
|
| 449 |
+
for j in range(10, 20):
|
| 450 |
+
l.append(j)
|
| 451 |
+
n = l[-2:-7:-1]
|
| 452 |
+
return len(n), (n[0], n[1], n[2], n[3], n[4])
|
| 453 |
+
|
| 454 |
+
length, items = foo()
|
| 455 |
+
self.assertEqual(length, 5)
|
| 456 |
+
self.assertEqual(items, (18, 17, 16, 15, 14))
|
| 457 |
+
|
| 458 |
+
def test_list_getitem_multiple_slice_start_out_of_range(self):
|
| 459 |
+
@njit
|
| 460 |
+
def foo():
|
| 461 |
+
l = listobject.new_list(int32)
|
| 462 |
+
for j in range(10, 20):
|
| 463 |
+
l.append(j)
|
| 464 |
+
n = l[10:]
|
| 465 |
+
return len(n)
|
| 466 |
+
|
| 467 |
+
self.assertEqual(foo(), 0)
|
| 468 |
+
|
| 469 |
+
def test_list_getitem_multiple_slice_stop_zero(self):
|
| 470 |
+
@njit
|
| 471 |
+
def foo():
|
| 472 |
+
l = listobject.new_list(int32)
|
| 473 |
+
for j in range(10, 20):
|
| 474 |
+
l.append(j)
|
| 475 |
+
n = l[:0]
|
| 476 |
+
return len(n)
|
| 477 |
+
|
| 478 |
+
self.assertEqual(foo(), 0)
|
| 479 |
+
|
| 480 |
+
def test_list_getitem_multiple_slice_zero_step_index_error(self):
|
| 481 |
+
self.disable_leak_check()
|
| 482 |
+
|
| 483 |
+
@njit
|
| 484 |
+
def foo():
|
| 485 |
+
l = listobject.new_list(int32)
|
| 486 |
+
for j in range(10, 20):
|
| 487 |
+
l.append(j)
|
| 488 |
+
l[::0]
|
| 489 |
+
|
| 490 |
+
with self.assertRaises(ValueError) as raises:
|
| 491 |
+
foo()
|
| 492 |
+
self.assertIn(
|
| 493 |
+
"slice step cannot be zero",
|
| 494 |
+
str(raises.exception),
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
class TestSetitem(MemoryLeakMixin, TestCase):
|
| 499 |
+
"""Test list setitem. """
|
| 500 |
+
|
| 501 |
+
def test_list_setitem_singleton(self):
|
| 502 |
+
@njit
|
| 503 |
+
def foo(n):
|
| 504 |
+
l = listobject.new_list(int32)
|
| 505 |
+
l.append(0)
|
| 506 |
+
l[0] = n
|
| 507 |
+
return l[0]
|
| 508 |
+
|
| 509 |
+
for i in (0, 1, 2, 100):
|
| 510 |
+
self.assertEqual(foo(i), i)
|
| 511 |
+
|
| 512 |
+
def test_list_setitem_singleton_negative_index(self):
|
| 513 |
+
@njit
|
| 514 |
+
def foo(n):
|
| 515 |
+
l = listobject.new_list(int32)
|
| 516 |
+
l.append(0)
|
| 517 |
+
l[0] = n
|
| 518 |
+
return l[-1]
|
| 519 |
+
|
| 520 |
+
for i in (0, 1, 2, 100):
|
| 521 |
+
self.assertEqual(foo(i), i)
|
| 522 |
+
|
| 523 |
+
def test_list_setitem_singleton_index_error(self):
|
| 524 |
+
self.disable_leak_check()
|
| 525 |
+
|
| 526 |
+
@njit
|
| 527 |
+
def foo(i):
|
| 528 |
+
l = listobject.new_list(int32)
|
| 529 |
+
l.append(0)
|
| 530 |
+
l[i] = 1
|
| 531 |
+
|
| 532 |
+
with self.assertRaises(IndexError):
|
| 533 |
+
foo(1)
|
| 534 |
+
|
| 535 |
+
with self.assertRaises(IndexError):
|
| 536 |
+
foo(-2)
|
| 537 |
+
|
| 538 |
+
def test_list_setitem_multiple(self):
|
| 539 |
+
|
| 540 |
+
@njit
|
| 541 |
+
def foo(i, n):
|
| 542 |
+
l = listobject.new_list(int32)
|
| 543 |
+
for j in range(10, 20):
|
| 544 |
+
l.append(j)
|
| 545 |
+
l[i] = n
|
| 546 |
+
return l[i]
|
| 547 |
+
|
| 548 |
+
for i,n in zip(range(0,10), range(20,30)):
|
| 549 |
+
self.assertEqual(foo(i, n), n)
|
| 550 |
+
|
| 551 |
+
def test_list_setitem_multiple_index_error(self):
|
| 552 |
+
self.disable_leak_check()
|
| 553 |
+
|
| 554 |
+
@njit
|
| 555 |
+
def foo(i):
|
| 556 |
+
l = listobject.new_list(int32)
|
| 557 |
+
for j in range(10, 20):
|
| 558 |
+
l.append(j)
|
| 559 |
+
l[i] = 0
|
| 560 |
+
|
| 561 |
+
with self.assertRaises(IndexError):
|
| 562 |
+
foo(10)
|
| 563 |
+
|
| 564 |
+
with self.assertRaises(IndexError):
|
| 565 |
+
foo(-11)
|
| 566 |
+
|
| 567 |
+
def test_list_setitem_singleton_typing_error_on_index(self):
|
| 568 |
+
self.disable_leak_check()
|
| 569 |
+
|
| 570 |
+
@njit
|
| 571 |
+
def foo(i):
|
| 572 |
+
l = listobject.new_list(int32)
|
| 573 |
+
l.append(0)
|
| 574 |
+
# slice with a non-{integer,slice}
|
| 575 |
+
l[i] = 1
|
| 576 |
+
|
| 577 |
+
for i in "xyz", 1.0, 1j:
|
| 578 |
+
with self.assertRaises(TypingError) as raises:
|
| 579 |
+
foo(i)
|
| 580 |
+
self.assertIn(
|
| 581 |
+
"list indices must be integers or slices",
|
| 582 |
+
str(raises.exception),
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
def test_list_setitem_singleton_typing_error_on_item(self):
|
| 586 |
+
self.disable_leak_check()
|
| 587 |
+
|
| 588 |
+
@njit
|
| 589 |
+
def foo():
|
| 590 |
+
l = listobject.new_list(int32)
|
| 591 |
+
l.append(0)
|
| 592 |
+
# assign a non-iterable to a slice
|
| 593 |
+
l[:] = 1
|
| 594 |
+
|
| 595 |
+
with self.assertRaises(TypingError) as raises:
|
| 596 |
+
foo()
|
| 597 |
+
self.assertIn(
|
| 598 |
+
"can only assign an iterable when using a slice "
|
| 599 |
+
"with assignment/setitem",
|
| 600 |
+
str(raises.exception),
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
def test_list_setitem_integer_types_as_index(self):
|
| 604 |
+
|
| 605 |
+
@njit
|
| 606 |
+
def foo(i):
|
| 607 |
+
l = listobject.new_list(int32)
|
| 608 |
+
l.append(0)
|
| 609 |
+
l[i] = 1
|
| 610 |
+
return l[i]
|
| 611 |
+
|
| 612 |
+
# try all signed integers and make sure they are cast
|
| 613 |
+
for t in (types.signed_domain
|
| 614 |
+
):
|
| 615 |
+
self.assertEqual(foo((t(0))), 1)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class TestPop(MemoryLeakMixin, TestCase):
|
| 619 |
+
"""Test list pop. """
|
| 620 |
+
|
| 621 |
+
def test_list_pop_singleton(self):
|
| 622 |
+
@njit
|
| 623 |
+
def foo():
|
| 624 |
+
l = listobject.new_list(int32)
|
| 625 |
+
l.append(0)
|
| 626 |
+
return l.pop(), len(l)
|
| 627 |
+
|
| 628 |
+
self.assertEqual(foo(), (0, 0))
|
| 629 |
+
|
| 630 |
+
def test_list_pop_singleton_index(self):
|
| 631 |
+
@njit
|
| 632 |
+
def foo(i):
|
| 633 |
+
l = listobject.new_list(int32)
|
| 634 |
+
l.append(0)
|
| 635 |
+
return l.pop(i), len(l)
|
| 636 |
+
|
| 637 |
+
self.assertEqual(foo(0), (0, 0))
|
| 638 |
+
self.assertEqual(foo(-1), (0, 0))
|
| 639 |
+
|
| 640 |
+
def test_list_pop_multiple(self):
|
| 641 |
+
@njit
|
| 642 |
+
def foo():
|
| 643 |
+
l = listobject.new_list(int32)
|
| 644 |
+
for j in (10, 11, 12):
|
| 645 |
+
l.append(j)
|
| 646 |
+
return l.pop(), len(l)
|
| 647 |
+
|
| 648 |
+
self.assertEqual(foo(), (12, 2))
|
| 649 |
+
|
| 650 |
+
def test_list_pop_multiple_index(self):
|
| 651 |
+
@njit
|
| 652 |
+
def foo(i):
|
| 653 |
+
l = listobject.new_list(int32)
|
| 654 |
+
for j in (10, 11, 12):
|
| 655 |
+
l.append(j)
|
| 656 |
+
return l.pop(i), len(l)
|
| 657 |
+
|
| 658 |
+
for i, n in ((0, 10), (1, 11), (2, 12)):
|
| 659 |
+
self.assertEqual(foo(i), (n, 2))
|
| 660 |
+
|
| 661 |
+
for i, n in ((-3, 10), (-2, 11), (-1, 12)):
|
| 662 |
+
self.assertEqual(foo(i), (n, 2))
|
| 663 |
+
|
| 664 |
+
def test_list_pop_integer_types_as_index(self):
|
| 665 |
+
|
| 666 |
+
@njit
|
| 667 |
+
def foo(i):
|
| 668 |
+
l = listobject.new_list(int32)
|
| 669 |
+
l.append(0)
|
| 670 |
+
return l.pop(i)
|
| 671 |
+
|
| 672 |
+
# try all signed integers and make sure they are cast
|
| 673 |
+
for t in (types.signed_domain
|
| 674 |
+
):
|
| 675 |
+
self.assertEqual(foo((t(0))), 0)
|
| 676 |
+
|
| 677 |
+
def test_list_pop_empty_index_error_no_index(self):
|
| 678 |
+
self.disable_leak_check()
|
| 679 |
+
|
| 680 |
+
@njit
|
| 681 |
+
def foo():
|
| 682 |
+
l = listobject.new_list(int32)
|
| 683 |
+
l.pop()
|
| 684 |
+
|
| 685 |
+
with self.assertRaises(IndexError) as raises:
|
| 686 |
+
foo()
|
| 687 |
+
self.assertIn(
|
| 688 |
+
"pop from empty list",
|
| 689 |
+
str(raises.exception),
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
def test_list_pop_empty_index_error_with_index(self):
|
| 693 |
+
self.disable_leak_check()
|
| 694 |
+
|
| 695 |
+
@njit
|
| 696 |
+
def foo(i):
|
| 697 |
+
l = listobject.new_list(int32)
|
| 698 |
+
l.pop(i)
|
| 699 |
+
|
| 700 |
+
with self.assertRaises(IndexError) as raises:
|
| 701 |
+
foo(-1)
|
| 702 |
+
self.assertIn(
|
| 703 |
+
"pop from empty list",
|
| 704 |
+
str(raises.exception),
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
with self.assertRaises(IndexError) as raises:
|
| 708 |
+
foo(0)
|
| 709 |
+
self.assertIn(
|
| 710 |
+
"pop from empty list",
|
| 711 |
+
str(raises.exception),
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
with self.assertRaises(IndexError) as raises:
|
| 715 |
+
foo(1)
|
| 716 |
+
self.assertIn(
|
| 717 |
+
"pop from empty list",
|
| 718 |
+
str(raises.exception),
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
def test_list_pop_mutiple_index_error_with_index(self):
|
| 722 |
+
self.disable_leak_check()
|
| 723 |
+
|
| 724 |
+
@njit
|
| 725 |
+
def foo(i):
|
| 726 |
+
l = listobject.new_list(int32)
|
| 727 |
+
for j in (10, 11, 12):
|
| 728 |
+
l.append(j)
|
| 729 |
+
l.pop(i)
|
| 730 |
+
|
| 731 |
+
with self.assertRaises(IndexError) as raises:
|
| 732 |
+
foo(-4)
|
| 733 |
+
self.assertIn(
|
| 734 |
+
"list index out of range",
|
| 735 |
+
str(raises.exception),
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
with self.assertRaises(IndexError) as raises:
|
| 739 |
+
foo(3)
|
| 740 |
+
self.assertIn(
|
| 741 |
+
"list index out of range",
|
| 742 |
+
str(raises.exception),
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
def test_list_pop_singleton_typing_error_on_index(self):
|
| 746 |
+
self.disable_leak_check()
|
| 747 |
+
|
| 748 |
+
@njit
|
| 749 |
+
def foo(i):
|
| 750 |
+
l = listobject.new_list(int32)
|
| 751 |
+
l.append(0)
|
| 752 |
+
# slice with a non-{integer,slice}
|
| 753 |
+
return l.pop(i)
|
| 754 |
+
|
| 755 |
+
for i in "xyz", 1.0, 1j:
|
| 756 |
+
with self.assertRaises(TypingError) as raises:
|
| 757 |
+
foo(i)
|
| 758 |
+
self.assertIn(
|
| 759 |
+
"argument for pop must be an integer",
|
| 760 |
+
str(raises.exception),
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class TestListObjectDelitem(MemoryLeakMixin, TestCase):
|
| 765 |
+
"""Test list delitem.
|
| 766 |
+
"""
|
| 767 |
+
|
| 768 |
+
def test_list_singleton_delitem_index(self):
|
| 769 |
+
|
| 770 |
+
@njit
|
| 771 |
+
def foo():
|
| 772 |
+
l = listobject.new_list(int32)
|
| 773 |
+
l.append(0)
|
| 774 |
+
del l[0]
|
| 775 |
+
return len(l)
|
| 776 |
+
self.assertEqual(foo(), 0)
|
| 777 |
+
|
| 778 |
+
def test_list_singleton_delitem_slice_defaults(self):
|
| 779 |
+
|
| 780 |
+
@njit
|
| 781 |
+
def foo():
|
| 782 |
+
l = listobject.new_list(int32)
|
| 783 |
+
l.append(0)
|
| 784 |
+
del l[:]
|
| 785 |
+
return len(l)
|
| 786 |
+
self.assertEqual(foo(), 0)
|
| 787 |
+
|
| 788 |
+
def test_list_singleton_delitem_slice_start(self):
|
| 789 |
+
|
| 790 |
+
@njit
|
| 791 |
+
def foo():
|
| 792 |
+
l = listobject.new_list(int32)
|
| 793 |
+
l.append(0)
|
| 794 |
+
del l[0:]
|
| 795 |
+
return len(l)
|
| 796 |
+
self.assertEqual(foo(), 0)
|
| 797 |
+
|
| 798 |
+
def test_list_singleton_delitem_slice_stop(self):
|
| 799 |
+
|
| 800 |
+
@njit
|
| 801 |
+
def foo():
|
| 802 |
+
l = listobject.new_list(int32)
|
| 803 |
+
l.append(0)
|
| 804 |
+
del l[:1]
|
| 805 |
+
return len(l)
|
| 806 |
+
self.assertEqual(foo(), 0)
|
| 807 |
+
|
| 808 |
+
def test_list_singleton_delitem_slice_start_stop(self):
|
| 809 |
+
|
| 810 |
+
@njit
|
| 811 |
+
def foo():
|
| 812 |
+
l = listobject.new_list(int32)
|
| 813 |
+
l.append(0)
|
| 814 |
+
del l[0:1]
|
| 815 |
+
return len(l)
|
| 816 |
+
self.assertEqual(foo(), 0)
|
| 817 |
+
|
| 818 |
+
def test_list_singleton_delitem_slice_start_step(self):
|
| 819 |
+
|
| 820 |
+
@njit
|
| 821 |
+
def foo():
|
| 822 |
+
l = listobject.new_list(int32)
|
| 823 |
+
l.append(0)
|
| 824 |
+
del l[0::1]
|
| 825 |
+
return len(l)
|
| 826 |
+
self.assertEqual(foo(), 0)
|
| 827 |
+
|
| 828 |
+
def test_list_singleton_delitem_slice_start_stop_step(self):
|
| 829 |
+
|
| 830 |
+
@njit
|
| 831 |
+
def foo():
|
| 832 |
+
l = listobject.new_list(int32)
|
| 833 |
+
l.append(0)
|
| 834 |
+
del l[0:1:1]
|
| 835 |
+
return len(l)
|
| 836 |
+
self.assertEqual(foo(), 0)
|
| 837 |
+
|
| 838 |
+
def test_list_multiple_delitem(self):
|
| 839 |
+
|
| 840 |
+
@njit
|
| 841 |
+
def foo():
|
| 842 |
+
l = listobject.new_list(int32)
|
| 843 |
+
for j in (10, 11, 12):
|
| 844 |
+
l.append(j)
|
| 845 |
+
del l[0]
|
| 846 |
+
return len(l), l[0], l[1]
|
| 847 |
+
self.assertEqual(foo(), (2, 11, 12))
|
| 848 |
+
|
| 849 |
+
def test_list_multiple_delitem_slice(self):
|
| 850 |
+
|
| 851 |
+
@njit
|
| 852 |
+
def foo():
|
| 853 |
+
l = listobject.new_list(int32)
|
| 854 |
+
for j in (10, 11, 12):
|
| 855 |
+
l.append(j)
|
| 856 |
+
del l[:]
|
| 857 |
+
return len(l)
|
| 858 |
+
self.assertEqual(foo(), 0)
|
| 859 |
+
|
| 860 |
+
def test_list_multiple_delitem_off_by_one(self):
|
| 861 |
+
# this was exposing a nasty off-by-one error, leaving it in to detect
|
| 862 |
+
# and regressions
|
| 863 |
+
@njit
|
| 864 |
+
def foo():
|
| 865 |
+
l = listobject.new_list(int32)
|
| 866 |
+
for j in range(10, 20):
|
| 867 |
+
l.append(j)
|
| 868 |
+
k = listobject.new_list(int32)
|
| 869 |
+
for j in range(10, 20):
|
| 870 |
+
k.append(j)
|
| 871 |
+
# should be a no-op
|
| 872 |
+
del l[-9:-20]
|
| 873 |
+
return k == l
|
| 874 |
+
self.assertTrue(foo())
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class TestContains(MemoryLeakMixin, TestCase):
|
| 878 |
+
"""Test list contains. """
|
| 879 |
+
|
| 880 |
+
def test_list_contains_empty(self):
|
| 881 |
+
@njit
|
| 882 |
+
def foo(i):
|
| 883 |
+
l = listobject.new_list(int32)
|
| 884 |
+
return i in l
|
| 885 |
+
|
| 886 |
+
self.assertFalse(foo(0))
|
| 887 |
+
self.assertFalse(foo(1))
|
| 888 |
+
|
| 889 |
+
def test_list_contains_singleton(self):
|
| 890 |
+
@njit
|
| 891 |
+
def foo(i):
|
| 892 |
+
l = listobject.new_list(int32)
|
| 893 |
+
l.append(0)
|
| 894 |
+
return i in l
|
| 895 |
+
|
| 896 |
+
self.assertTrue(foo(0))
|
| 897 |
+
self.assertFalse(foo(1))
|
| 898 |
+
|
| 899 |
+
def test_list_contains_multiple(self):
|
| 900 |
+
@njit
|
| 901 |
+
def foo(i):
|
| 902 |
+
l = listobject.new_list(int32)
|
| 903 |
+
for j in range(10, 20):
|
| 904 |
+
l.append(j)
|
| 905 |
+
return i in l
|
| 906 |
+
|
| 907 |
+
for i in range(10, 20):
|
| 908 |
+
self.assertTrue(foo(i))
|
| 909 |
+
|
| 910 |
+
for i in range(20, 30):
|
| 911 |
+
self.assertFalse(foo(i))
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class TestCount(MemoryLeakMixin, TestCase):
|
| 915 |
+
"""Test list count. """
|
| 916 |
+
|
| 917 |
+
def test_list_count_empty(self):
|
| 918 |
+
@njit
|
| 919 |
+
def foo(i):
|
| 920 |
+
l = listobject.new_list(int32)
|
| 921 |
+
return l.count(i)
|
| 922 |
+
|
| 923 |
+
self.assertEqual(foo(10), 0)
|
| 924 |
+
|
| 925 |
+
def test_list_count_singleton(self):
|
| 926 |
+
@njit
|
| 927 |
+
def foo(i):
|
| 928 |
+
l = listobject.new_list(int32)
|
| 929 |
+
l.append(10)
|
| 930 |
+
return l.count(i)
|
| 931 |
+
|
| 932 |
+
self.assertEqual(foo(1), 0)
|
| 933 |
+
self.assertEqual(foo(10), 1)
|
| 934 |
+
|
| 935 |
+
def test_list_count_mutiple(self):
|
| 936 |
+
@njit
|
| 937 |
+
def foo(i):
|
| 938 |
+
l = listobject.new_list(int32)
|
| 939 |
+
for j in [11, 12, 12, 13, 13, 13]:
|
| 940 |
+
l.append(j)
|
| 941 |
+
return l.count(i)
|
| 942 |
+
|
| 943 |
+
self.assertEqual(foo(10), 0)
|
| 944 |
+
self.assertEqual(foo(11), 1)
|
| 945 |
+
self.assertEqual(foo(12), 2)
|
| 946 |
+
self.assertEqual(foo(13), 3)
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
class TestExtend(MemoryLeakMixin, TestCase):
|
| 950 |
+
"""Test list extend. """
|
| 951 |
+
|
| 952 |
+
def test_list_extend_empty(self):
|
| 953 |
+
@njit
|
| 954 |
+
def foo(items):
|
| 955 |
+
l = listobject.new_list(int32)
|
| 956 |
+
l.extend(items)
|
| 957 |
+
return len(l)
|
| 958 |
+
|
| 959 |
+
self.assertEqual(foo((1,)), 1)
|
| 960 |
+
self.assertEqual(foo((1,2)), 2)
|
| 961 |
+
self.assertEqual(foo((1,2,3)), 3)
|
| 962 |
+
|
| 963 |
+
def test_list_extend_typing_error_non_iterable(self):
|
| 964 |
+
self.disable_leak_check()
|
| 965 |
+
|
| 966 |
+
@njit
|
| 967 |
+
def foo():
|
| 968 |
+
l = listobject.new_list(int32)
|
| 969 |
+
l.extend(1)
|
| 970 |
+
|
| 971 |
+
with self.assertRaises(TypingError) as raises:
|
| 972 |
+
foo()
|
| 973 |
+
self.assertIn(
|
| 974 |
+
"extend argument must be iterable",
|
| 975 |
+
str(raises.exception),
|
| 976 |
+
)
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
class TestInsert(MemoryLeakMixin, TestCase):
|
| 980 |
+
"""Test list insert. """
|
| 981 |
+
|
| 982 |
+
def test_list_insert_empty(self):
|
| 983 |
+
@njit
|
| 984 |
+
def foo(i):
|
| 985 |
+
l = listobject.new_list(int32)
|
| 986 |
+
l.insert(i, 1)
|
| 987 |
+
return len(l), l[0]
|
| 988 |
+
|
| 989 |
+
for i in (-10, -5, -1, 0, 1, 4, 9):
|
| 990 |
+
self.assertEqual(foo(i), (1, 1))
|
| 991 |
+
|
| 992 |
+
def test_list_insert_singleton(self):
|
| 993 |
+
@njit
|
| 994 |
+
def foo(i):
|
| 995 |
+
l = listobject.new_list(int32)
|
| 996 |
+
l.append(0)
|
| 997 |
+
l.insert(i, 1)
|
| 998 |
+
return len(l), l[0], l[1]
|
| 999 |
+
|
| 1000 |
+
# insert before
|
| 1001 |
+
for i in (-10, -3, -2, -1, 0):
|
| 1002 |
+
self.assertEqual(foo(i), (2, 1, 0))
|
| 1003 |
+
|
| 1004 |
+
# insert after
|
| 1005 |
+
for i in (1, 2, 3, 10):
|
| 1006 |
+
self.assertEqual(foo(i), (2, 0, 1))
|
| 1007 |
+
|
| 1008 |
+
def test_list_insert_multiple(self):
|
| 1009 |
+
@njit
|
| 1010 |
+
def foo(i):
|
| 1011 |
+
l = listobject.new_list(int32)
|
| 1012 |
+
for j in range(10):
|
| 1013 |
+
l.append(0)
|
| 1014 |
+
l.insert(i, 1)
|
| 1015 |
+
return len(l), l[i]
|
| 1016 |
+
|
| 1017 |
+
for i in (0, 4, 9):
|
| 1018 |
+
self.assertEqual(foo(i), (11, 1))
|
| 1019 |
+
|
| 1020 |
+
def test_list_insert_multiple_before(self):
|
| 1021 |
+
@njit
|
| 1022 |
+
def foo(i):
|
| 1023 |
+
l = listobject.new_list(int32)
|
| 1024 |
+
for j in range(10):
|
| 1025 |
+
l.append(0)
|
| 1026 |
+
l.insert(i, 1)
|
| 1027 |
+
return len(l), l[0]
|
| 1028 |
+
|
| 1029 |
+
for i in (-12, -11, -10, 0):
|
| 1030 |
+
self.assertEqual(foo(i), (11, 1))
|
| 1031 |
+
|
| 1032 |
+
def test_list_insert_multiple_after(self):
|
| 1033 |
+
@njit
|
| 1034 |
+
def foo(i):
|
| 1035 |
+
l = listobject.new_list(int32)
|
| 1036 |
+
for j in range(10):
|
| 1037 |
+
l.append(0)
|
| 1038 |
+
l.insert(i, 1)
|
| 1039 |
+
return len(l), l[10]
|
| 1040 |
+
|
| 1041 |
+
for i in (10, 11, 12):
|
| 1042 |
+
self.assertEqual(foo(i), (11, 1))
|
| 1043 |
+
|
| 1044 |
+
def test_list_insert_typing_error(self):
|
| 1045 |
+
self.disable_leak_check()
|
| 1046 |
+
|
| 1047 |
+
@njit
|
| 1048 |
+
def foo():
|
| 1049 |
+
l = listobject.new_list(int32)
|
| 1050 |
+
l.insert("a", 0)
|
| 1051 |
+
|
| 1052 |
+
with self.assertRaises(TypingError) as raises:
|
| 1053 |
+
foo()
|
| 1054 |
+
self.assertIn(
|
| 1055 |
+
"list insert indices must be integers",
|
| 1056 |
+
str(raises.exception),
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
class TestRemove(MemoryLeakMixin, TestCase):
|
| 1061 |
+
"""Test list remove. """
|
| 1062 |
+
|
| 1063 |
+
def test_list_remove_empty(self):
|
| 1064 |
+
self.disable_leak_check()
|
| 1065 |
+
|
| 1066 |
+
@njit
|
| 1067 |
+
def foo():
|
| 1068 |
+
l = listobject.new_list(int32)
|
| 1069 |
+
l.remove(0)
|
| 1070 |
+
|
| 1071 |
+
with self.assertRaises(ValueError):
|
| 1072 |
+
foo()
|
| 1073 |
+
|
| 1074 |
+
def test_list_remove_singleton(self):
|
| 1075 |
+
@njit
|
| 1076 |
+
def foo():
|
| 1077 |
+
l = listobject.new_list(int32)
|
| 1078 |
+
l.append(0)
|
| 1079 |
+
l.remove(0)
|
| 1080 |
+
return len(l)
|
| 1081 |
+
|
| 1082 |
+
self.assertEqual(foo(), 0)
|
| 1083 |
+
|
| 1084 |
+
def test_list_remove_singleton_value_error(self):
|
| 1085 |
+
self.disable_leak_check()
|
| 1086 |
+
|
| 1087 |
+
@njit
|
| 1088 |
+
def foo():
|
| 1089 |
+
l = listobject.new_list(int32)
|
| 1090 |
+
l.append(1)
|
| 1091 |
+
l.remove(0)
|
| 1092 |
+
|
| 1093 |
+
with self.assertRaises(ValueError):
|
| 1094 |
+
foo()
|
| 1095 |
+
|
| 1096 |
+
def test_list_remove_multiple(self):
|
| 1097 |
+
@njit
|
| 1098 |
+
def foo():
|
| 1099 |
+
l = listobject.new_list(int32)
|
| 1100 |
+
for j in range(10, 20):
|
| 1101 |
+
l.append(j)
|
| 1102 |
+
l.remove(13)
|
| 1103 |
+
l.remove(19)
|
| 1104 |
+
return len(l)
|
| 1105 |
+
|
| 1106 |
+
self.assertEqual(foo(), 8)
|
| 1107 |
+
|
| 1108 |
+
def test_list_remove_multiple_value_error(self):
|
| 1109 |
+
self.disable_leak_check()
|
| 1110 |
+
|
| 1111 |
+
@njit
|
| 1112 |
+
def foo():
|
| 1113 |
+
l = listobject.new_list(int32)
|
| 1114 |
+
for j in range(10, 20):
|
| 1115 |
+
l.append(j)
|
| 1116 |
+
l.remove(23)
|
| 1117 |
+
|
| 1118 |
+
with self.assertRaises(ValueError):
|
| 1119 |
+
foo()
|
| 1120 |
+
|
| 1121 |
+
|
| 1122 |
+
class TestClear(MemoryLeakMixin, TestCase):
|
| 1123 |
+
"""Test list clear. """
|
| 1124 |
+
|
| 1125 |
+
def test_list_clear_empty(self):
|
| 1126 |
+
@njit
|
| 1127 |
+
def foo():
|
| 1128 |
+
l = listobject.new_list(int32)
|
| 1129 |
+
l.clear()
|
| 1130 |
+
return len(l)
|
| 1131 |
+
|
| 1132 |
+
self.assertEqual(foo(), 0)
|
| 1133 |
+
|
| 1134 |
+
def test_list_clear_singleton(self):
|
| 1135 |
+
@njit
|
| 1136 |
+
def foo():
|
| 1137 |
+
l = listobject.new_list(int32)
|
| 1138 |
+
l.append(0)
|
| 1139 |
+
l.clear()
|
| 1140 |
+
return len(l)
|
| 1141 |
+
|
| 1142 |
+
self.assertEqual(foo(), 0)
|
| 1143 |
+
|
| 1144 |
+
def test_list_clear_multiple(self):
|
| 1145 |
+
@njit
|
| 1146 |
+
def foo():
|
| 1147 |
+
l = listobject.new_list(int32)
|
| 1148 |
+
for j in range(10):
|
| 1149 |
+
l.append(0)
|
| 1150 |
+
l.clear()
|
| 1151 |
+
return len(l)
|
| 1152 |
+
self.assertEqual(foo(), 0)
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
class TestReverse(MemoryLeakMixin, TestCase):
|
| 1156 |
+
"""Test list reverse. """
|
| 1157 |
+
|
| 1158 |
+
def test_list_reverse_empty(self):
|
| 1159 |
+
@njit
|
| 1160 |
+
def foo():
|
| 1161 |
+
l = listobject.new_list(int32)
|
| 1162 |
+
l.reverse()
|
| 1163 |
+
return len(l)
|
| 1164 |
+
|
| 1165 |
+
self.assertEqual(foo(), 0)
|
| 1166 |
+
|
| 1167 |
+
def test_list_reverse_singleton(self):
|
| 1168 |
+
@njit
|
| 1169 |
+
def foo():
|
| 1170 |
+
l = listobject.new_list(int32)
|
| 1171 |
+
l.append(0)
|
| 1172 |
+
l.reverse()
|
| 1173 |
+
return len(l), l[0]
|
| 1174 |
+
|
| 1175 |
+
self.assertEqual(foo(), (1, 0))
|
| 1176 |
+
|
| 1177 |
+
def test_list_reverse_multiple(self):
|
| 1178 |
+
@njit
|
| 1179 |
+
def foo():
|
| 1180 |
+
l = listobject.new_list(int32)
|
| 1181 |
+
for j in range(10, 13):
|
| 1182 |
+
l.append(j)
|
| 1183 |
+
l.reverse()
|
| 1184 |
+
return len(l), l[0], l[1], l[2]
|
| 1185 |
+
self.assertEqual(foo(), (3, 12, 11, 10))
|
| 1186 |
+
|
| 1187 |
+
|
| 1188 |
+
class TestCopy(MemoryLeakMixin, TestCase):
|
| 1189 |
+
"""Test list copy. """
|
| 1190 |
+
|
| 1191 |
+
def test_list_copy_empty(self):
|
| 1192 |
+
@njit
|
| 1193 |
+
def foo():
|
| 1194 |
+
l = listobject.new_list(int32)
|
| 1195 |
+
n = l.copy()
|
| 1196 |
+
return len(l), len(n)
|
| 1197 |
+
|
| 1198 |
+
self.assertEqual(foo(), (0, 0))
|
| 1199 |
+
|
| 1200 |
+
def test_list_copy_singleton(self):
|
| 1201 |
+
@njit
|
| 1202 |
+
def foo():
|
| 1203 |
+
l = listobject.new_list(int32)
|
| 1204 |
+
l.append(0)
|
| 1205 |
+
n = l.copy()
|
| 1206 |
+
return len(l), len(n), l[0], n[0]
|
| 1207 |
+
|
| 1208 |
+
self.assertEqual(foo(), (1, 1, 0, 0))
|
| 1209 |
+
|
| 1210 |
+
def test_list_copy_multiple(self):
|
| 1211 |
+
@njit
|
| 1212 |
+
def foo():
|
| 1213 |
+
l = listobject.new_list(int32)
|
| 1214 |
+
for j in range(10, 13):
|
| 1215 |
+
l.append(j)
|
| 1216 |
+
n = l.copy()
|
| 1217 |
+
return len(l), len(n), l[0], l[1], l[2], l[0], l[1], l[2]
|
| 1218 |
+
|
| 1219 |
+
self.assertEqual(foo(), (3, 3, 10, 11, 12, 10, 11, 12))
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
class TestIndex(MemoryLeakMixin, TestCase):
|
| 1223 |
+
|
| 1224 |
+
def test_index_singleton(self):
|
| 1225 |
+
@njit
|
| 1226 |
+
def foo():
|
| 1227 |
+
l = listobject.new_list(int32)
|
| 1228 |
+
l.append(1)
|
| 1229 |
+
return l.index(1)
|
| 1230 |
+
|
| 1231 |
+
self.assertEqual(foo(), 0)
|
| 1232 |
+
|
| 1233 |
+
def test_index_multiple(self):
|
| 1234 |
+
@njit
|
| 1235 |
+
def foo(i):
|
| 1236 |
+
l = listobject.new_list(int32)
|
| 1237 |
+
for j in range(10, 20):
|
| 1238 |
+
l.append(j)
|
| 1239 |
+
return l.index(i)
|
| 1240 |
+
|
| 1241 |
+
for i,v in zip(range(10), range(10,20)):
|
| 1242 |
+
self.assertEqual(foo(v), i)
|
| 1243 |
+
|
| 1244 |
+
def test_index_duplicate(self):
|
| 1245 |
+
@njit
|
| 1246 |
+
def foo():
|
| 1247 |
+
l = listobject.new_list(int32)
|
| 1248 |
+
for _ in range(10, 20):
|
| 1249 |
+
l.append(1)
|
| 1250 |
+
return l.index(1)
|
| 1251 |
+
|
| 1252 |
+
self.assertEqual(foo(), 0)
|
| 1253 |
+
|
| 1254 |
+
def test_index_duplicate_with_start(self):
|
| 1255 |
+
@njit
|
| 1256 |
+
def foo(start):
|
| 1257 |
+
l = listobject.new_list(int32)
|
| 1258 |
+
for _ in range(10, 20):
|
| 1259 |
+
l.append(1)
|
| 1260 |
+
return l.index(1, start)
|
| 1261 |
+
|
| 1262 |
+
for i in range(10):
|
| 1263 |
+
self.assertEqual(foo(i), i)
|
| 1264 |
+
|
| 1265 |
+
def test_index_singleton_value_error(self):
|
| 1266 |
+
self.disable_leak_check()
|
| 1267 |
+
|
| 1268 |
+
@njit
|
| 1269 |
+
def foo():
|
| 1270 |
+
l = listobject.new_list(int32)
|
| 1271 |
+
l.append(0)
|
| 1272 |
+
return l.index(1)
|
| 1273 |
+
|
| 1274 |
+
with self.assertRaises(ValueError) as raises:
|
| 1275 |
+
foo()
|
| 1276 |
+
self.assertIn(
|
| 1277 |
+
"item not in list",
|
| 1278 |
+
str(raises.exception),
|
| 1279 |
+
)
|
| 1280 |
+
|
| 1281 |
+
def test_index_multiple_value_error(self):
|
| 1282 |
+
self.disable_leak_check()
|
| 1283 |
+
|
| 1284 |
+
@njit
|
| 1285 |
+
def foo():
|
| 1286 |
+
l = listobject.new_list(int32)
|
| 1287 |
+
for j in range(10, 20):
|
| 1288 |
+
l.append(j)
|
| 1289 |
+
return l.index(23)
|
| 1290 |
+
|
| 1291 |
+
with self.assertRaises(ValueError) as raises:
|
| 1292 |
+
foo()
|
| 1293 |
+
self.assertIn(
|
| 1294 |
+
"item not in list",
|
| 1295 |
+
str(raises.exception),
|
| 1296 |
+
)
|
| 1297 |
+
|
| 1298 |
+
def test_index_multiple_value_error_start(self):
|
| 1299 |
+
self.disable_leak_check()
|
| 1300 |
+
|
| 1301 |
+
@njit
|
| 1302 |
+
def foo(start):
|
| 1303 |
+
l = listobject.new_list(int32)
|
| 1304 |
+
for j in range(10, 20):
|
| 1305 |
+
l.append(j)
|
| 1306 |
+
return l.index(10, start)
|
| 1307 |
+
|
| 1308 |
+
self.assertEqual(foo(0), 0)
|
| 1309 |
+
for i in range(1,10):
|
| 1310 |
+
with self.assertRaises(ValueError) as raises:
|
| 1311 |
+
foo(i)
|
| 1312 |
+
self.assertIn(
|
| 1313 |
+
"item not in list",
|
| 1314 |
+
str(raises.exception),
|
| 1315 |
+
)
|
| 1316 |
+
|
| 1317 |
+
def test_index_multiple_value_error_end(self):
|
| 1318 |
+
self.disable_leak_check()
|
| 1319 |
+
|
| 1320 |
+
@njit
|
| 1321 |
+
def foo(end):
|
| 1322 |
+
l = listobject.new_list(int32)
|
| 1323 |
+
for j in range(10, 20):
|
| 1324 |
+
l.append(j)
|
| 1325 |
+
return l.index(19, 0, end)
|
| 1326 |
+
|
| 1327 |
+
self.assertEqual(foo(10), 9)
|
| 1328 |
+
for i in range(0,9):
|
| 1329 |
+
with self.assertRaises(ValueError) as raises:
|
| 1330 |
+
foo(i)
|
| 1331 |
+
self.assertIn(
|
| 1332 |
+
"item not in list",
|
| 1333 |
+
str(raises.exception),
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
def test_index_typing_error_start(self):
|
| 1337 |
+
self.disable_leak_check()
|
| 1338 |
+
|
| 1339 |
+
@njit
|
| 1340 |
+
def foo():
|
| 1341 |
+
l = listobject.new_list(int32)
|
| 1342 |
+
l.append(0)
|
| 1343 |
+
return l.index(0, start="a")
|
| 1344 |
+
|
| 1345 |
+
with self.assertRaises(TypingError) as raises:
|
| 1346 |
+
foo()
|
| 1347 |
+
self.assertIn(
|
| 1348 |
+
"start argument for index must be an integer",
|
| 1349 |
+
str(raises.exception),
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
def test_index_typing_error_end(self):
|
| 1353 |
+
self.disable_leak_check()
|
| 1354 |
+
|
| 1355 |
+
@njit
|
| 1356 |
+
def foo():
|
| 1357 |
+
l = listobject.new_list(int32)
|
| 1358 |
+
l.append(0)
|
| 1359 |
+
return l.index(0, end="a")
|
| 1360 |
+
|
| 1361 |
+
with self.assertRaises(TypingError) as raises:
|
| 1362 |
+
foo()
|
| 1363 |
+
self.assertIn(
|
| 1364 |
+
"end argument for index must be an integer",
|
| 1365 |
+
str(raises.exception),
|
| 1366 |
+
)
|
| 1367 |
+
|
| 1368 |
+
|
| 1369 |
+
class TestEqualNotEqual(MemoryLeakMixin, TestCase):
|
| 1370 |
+
"""Test list equal and not equal. """
|
| 1371 |
+
|
| 1372 |
+
def test_list_empty_equal(self):
|
| 1373 |
+
@njit
|
| 1374 |
+
def foo():
|
| 1375 |
+
t = listobject.new_list(int32)
|
| 1376 |
+
o = listobject.new_list(int32)
|
| 1377 |
+
return t == o, t != o
|
| 1378 |
+
|
| 1379 |
+
self.assertEqual(foo(), (True, False))
|
| 1380 |
+
|
| 1381 |
+
def test_list_singleton_equal(self):
|
| 1382 |
+
@njit
|
| 1383 |
+
def foo():
|
| 1384 |
+
t = listobject.new_list(int32)
|
| 1385 |
+
t.append(0)
|
| 1386 |
+
o = listobject.new_list(int32)
|
| 1387 |
+
o.append(0)
|
| 1388 |
+
return t == o, t != o
|
| 1389 |
+
|
| 1390 |
+
self.assertEqual(foo(), (True, False))
|
| 1391 |
+
|
| 1392 |
+
def test_list_singleton_not_equal(self):
|
| 1393 |
+
@njit
|
| 1394 |
+
def foo():
|
| 1395 |
+
t = listobject.new_list(int32)
|
| 1396 |
+
t.append(0)
|
| 1397 |
+
o = listobject.new_list(int32)
|
| 1398 |
+
o.append(1)
|
| 1399 |
+
return t == o, t != o
|
| 1400 |
+
|
| 1401 |
+
self.assertEqual(foo(), (False, True))
|
| 1402 |
+
|
| 1403 |
+
def test_list_length_mismatch(self):
|
| 1404 |
+
@njit
|
| 1405 |
+
def foo():
|
| 1406 |
+
t = listobject.new_list(int32)
|
| 1407 |
+
t.append(0)
|
| 1408 |
+
o = listobject.new_list(int32)
|
| 1409 |
+
return t == o, t != o
|
| 1410 |
+
|
| 1411 |
+
self.assertEqual(foo(), (False, True))
|
| 1412 |
+
|
| 1413 |
+
def test_list_multiple_equal(self):
|
| 1414 |
+
@njit
|
| 1415 |
+
def foo():
|
| 1416 |
+
t = listobject.new_list(int32)
|
| 1417 |
+
o = listobject.new_list(int32)
|
| 1418 |
+
for i in range(10):
|
| 1419 |
+
t.append(i)
|
| 1420 |
+
o.append(i)
|
| 1421 |
+
return t == o, t != o
|
| 1422 |
+
|
| 1423 |
+
self.assertEqual(foo(), (True, False))
|
| 1424 |
+
|
| 1425 |
+
def test_list_multiple_not_equal(self):
|
| 1426 |
+
@njit
|
| 1427 |
+
def foo():
|
| 1428 |
+
t = listobject.new_list(int32)
|
| 1429 |
+
o = listobject.new_list(int32)
|
| 1430 |
+
for i in range(10):
|
| 1431 |
+
t.append(i)
|
| 1432 |
+
o.append(i)
|
| 1433 |
+
o[-1] = 42
|
| 1434 |
+
return t == o, t != o
|
| 1435 |
+
|
| 1436 |
+
self.assertEqual(foo(), (False, True))
|
| 1437 |
+
|
| 1438 |
+
|
| 1439 |
+
class TestIter(MemoryLeakMixin, TestCase):
|
| 1440 |
+
"""Test list iter. """
|
| 1441 |
+
|
| 1442 |
+
def test_list_iter(self):
|
| 1443 |
+
@njit
|
| 1444 |
+
def foo(items):
|
| 1445 |
+
l = listobject.new_list(int32)
|
| 1446 |
+
l.extend(items)
|
| 1447 |
+
# use a simple sum to check this w/o having to return a list
|
| 1448 |
+
r = 0
|
| 1449 |
+
for j in l:
|
| 1450 |
+
r += j
|
| 1451 |
+
return r
|
| 1452 |
+
|
| 1453 |
+
items = (1, 2, 3, 4)
|
| 1454 |
+
|
| 1455 |
+
self.assertEqual(
|
| 1456 |
+
foo(items),
|
| 1457 |
+
sum(items)
|
| 1458 |
+
)
|
| 1459 |
+
|
| 1460 |
+
def test_list_iter_self_mutation(self):
|
| 1461 |
+
self.disable_leak_check()
|
| 1462 |
+
|
| 1463 |
+
@njit
|
| 1464 |
+
def foo():
|
| 1465 |
+
l = listobject.new_list(int32)
|
| 1466 |
+
l.extend((1, 2, 3, 4))
|
| 1467 |
+
for i in l:
|
| 1468 |
+
l.append(i)
|
| 1469 |
+
|
| 1470 |
+
with self.assertRaises(RuntimeError) as raises:
|
| 1471 |
+
foo()
|
| 1472 |
+
self.assertIn(
|
| 1473 |
+
'list was mutated during iteration'.format(**locals()),
|
| 1474 |
+
str(raises.exception),
|
| 1475 |
+
)
|
| 1476 |
+
|
| 1477 |
+
|
| 1478 |
+
class TestStringItem(MemoryLeakMixin, TestCase):
|
| 1479 |
+
"""Test list can take strings as items. """
|
| 1480 |
+
|
| 1481 |
+
def test_string_item(self):
|
| 1482 |
+
@njit
|
| 1483 |
+
def foo():
|
| 1484 |
+
l = listobject.new_list(types.unicode_type)
|
| 1485 |
+
l.append('a')
|
| 1486 |
+
l.append('b')
|
| 1487 |
+
l.append('c')
|
| 1488 |
+
l.append('d')
|
| 1489 |
+
return l[0], l[1], l[2], l[3]
|
| 1490 |
+
|
| 1491 |
+
items = foo()
|
| 1492 |
+
self.assertEqual(['a', 'b', 'c', 'd'], list(items))
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
class TestItemCasting(TestCase):
|
| 1496 |
+
|
| 1497 |
+
@njit
|
| 1498 |
+
def foo(fromty, toty):
|
| 1499 |
+
l = listobject.new_list(toty)
|
| 1500 |
+
l.append(fromty(0))
|
| 1501 |
+
|
| 1502 |
+
def check_good(self, fromty, toty):
|
| 1503 |
+
TestItemCasting.foo(fromty, toty)
|
| 1504 |
+
|
| 1505 |
+
def check_bad(self, fromty, toty):
|
| 1506 |
+
with self.assertRaises(TypingError) as raises:
|
| 1507 |
+
TestItemCasting.foo(fromty, toty)
|
| 1508 |
+
self.assertIn(
|
| 1509 |
+
'cannot safely cast {fromty} to {toty}'.format(**locals()),
|
| 1510 |
+
str(raises.exception),
|
| 1511 |
+
)
|
| 1512 |
+
|
| 1513 |
+
def test_cast_int_to(self):
|
| 1514 |
+
self.check_good(types.int32, types.float32)
|
| 1515 |
+
self.check_good(types.int32, types.float64)
|
| 1516 |
+
self.check_good(types.int32, types.complex128)
|
| 1517 |
+
self.check_good(types.int64, types.complex128)
|
| 1518 |
+
self.check_bad(types.int32, types.complex64)
|
| 1519 |
+
self.check_good(types.int8, types.complex64)
|
| 1520 |
+
|
| 1521 |
+
def test_cast_float_to(self):
|
| 1522 |
+
self.check_good(types.float32, types.float64)
|
| 1523 |
+
self.check_good(types.float32, types.complex64)
|
| 1524 |
+
self.check_good(types.float64, types.complex128)
|
| 1525 |
+
|
| 1526 |
+
def test_cast_bool_to(self):
|
| 1527 |
+
self.check_good(types.boolean, types.int32)
|
| 1528 |
+
self.check_good(types.boolean, types.float64)
|
| 1529 |
+
self.check_good(types.boolean, types.complex128)
|
| 1530 |
+
|
| 1531 |
+
def test_cast_fail_unicode_int(self):
|
| 1532 |
+
|
| 1533 |
+
@njit
|
| 1534 |
+
def foo():
|
| 1535 |
+
l = listobject.new_list(int32)
|
| 1536 |
+
l.append("xyz")
|
| 1537 |
+
|
| 1538 |
+
with self.assertRaises(TypingError) as raises:
|
| 1539 |
+
foo()
|
| 1540 |
+
self.assertIn(
|
| 1541 |
+
'cannot safely cast unicode_type to int32',
|
| 1542 |
+
str(raises.exception),
|
| 1543 |
+
)
|
| 1544 |
+
|
| 1545 |
+
def test_cast_fail_int_unicode(self):
|
| 1546 |
+
|
| 1547 |
+
@njit
|
| 1548 |
+
def foo():
|
| 1549 |
+
l = listobject.new_list(types.unicode_type)
|
| 1550 |
+
l.append(int32(0))
|
| 1551 |
+
|
| 1552 |
+
with self.assertRaises(TypingError) as raises:
|
| 1553 |
+
foo()
|
| 1554 |
+
self.assertIn(
|
| 1555 |
+
'Cannot cast int32 to unicode_type',
|
| 1556 |
+
str(raises.exception),
|
| 1557 |
+
)
|
| 1558 |
+
|
| 1559 |
+
|
| 1560 |
+
@register_jitable
|
| 1561 |
+
def make_test_list():
|
| 1562 |
+
l = listobject.new_list(int32)
|
| 1563 |
+
l.append(int32(1))
|
| 1564 |
+
return l
|
| 1565 |
+
|
| 1566 |
+
|
| 1567 |
+
class TestImmutable(MemoryLeakMixin, TestCase):
|
| 1568 |
+
|
| 1569 |
+
def test_is_immutable(self):
|
| 1570 |
+
@njit
|
| 1571 |
+
def foo():
|
| 1572 |
+
l = make_test_list()
|
| 1573 |
+
return l._is_mutable()
|
| 1574 |
+
self.assertTrue(foo())
|
| 1575 |
+
|
| 1576 |
+
def test_make_immutable_is_immutable(self):
|
| 1577 |
+
@njit
|
| 1578 |
+
def foo():
|
| 1579 |
+
l = make_test_list()
|
| 1580 |
+
l._make_immutable()
|
| 1581 |
+
return l._is_mutable()
|
| 1582 |
+
self.assertFalse(foo())
|
| 1583 |
+
|
| 1584 |
+
def test_length_still_works_when_immutable(self):
|
| 1585 |
+
@njit
|
| 1586 |
+
def foo():
|
| 1587 |
+
l = make_test_list()
|
| 1588 |
+
l._make_immutable()
|
| 1589 |
+
return len(l),l._is_mutable()
|
| 1590 |
+
length, mutable = foo()
|
| 1591 |
+
self.assertEqual(length, 1)
|
| 1592 |
+
self.assertFalse(mutable)
|
| 1593 |
+
|
| 1594 |
+
def test_getitem_still_works_when_immutable(self):
|
| 1595 |
+
@njit
|
| 1596 |
+
def foo():
|
| 1597 |
+
l = make_test_list()
|
| 1598 |
+
l._make_immutable()
|
| 1599 |
+
return l[0], l._is_mutable()
|
| 1600 |
+
test_item, mutable = foo()
|
| 1601 |
+
self.assertEqual(test_item, 1)
|
| 1602 |
+
self.assertFalse(mutable)
|
| 1603 |
+
|
| 1604 |
+
def test_append_fails(self):
|
| 1605 |
+
self.disable_leak_check()
|
| 1606 |
+
|
| 1607 |
+
@njit
|
| 1608 |
+
def foo():
|
| 1609 |
+
l = make_test_list()
|
| 1610 |
+
l._make_immutable()
|
| 1611 |
+
l.append(int32(1))
|
| 1612 |
+
with self.assertRaises(ValueError) as raises:
|
| 1613 |
+
foo()
|
| 1614 |
+
self.assertIn(
|
| 1615 |
+
'list is immutable',
|
| 1616 |
+
str(raises.exception),
|
| 1617 |
+
)
|
| 1618 |
+
|
| 1619 |
+
def test_mutation_fails(self):
|
| 1620 |
+
""" Test that any attempt to mutate an immutable typed list fails. """
|
| 1621 |
+
self.disable_leak_check()
|
| 1622 |
+
|
| 1623 |
+
def generate_function(line):
|
| 1624 |
+
context = {}
|
| 1625 |
+
exec(dedent("""
|
| 1626 |
+
from numba.typed import listobject
|
| 1627 |
+
from numba import int32
|
| 1628 |
+
def bar():
|
| 1629 |
+
lst = listobject.new_list(int32)
|
| 1630 |
+
lst.append(int32(1))
|
| 1631 |
+
lst._make_immutable()
|
| 1632 |
+
zero = int32(0)
|
| 1633 |
+
{}
|
| 1634 |
+
""".format(line)), context)
|
| 1635 |
+
return njit(context["bar"])
|
| 1636 |
+
for line in ("lst.append(zero)",
|
| 1637 |
+
"lst[0] = zero",
|
| 1638 |
+
"lst.pop()",
|
| 1639 |
+
"del lst[0]",
|
| 1640 |
+
"lst.extend((zero,))",
|
| 1641 |
+
"lst.insert(0, zero)",
|
| 1642 |
+
"lst.clear()",
|
| 1643 |
+
"lst.reverse()",
|
| 1644 |
+
"lst.sort()",
|
| 1645 |
+
):
|
| 1646 |
+
foo = generate_function(line)
|
| 1647 |
+
with self.assertRaises(ValueError) as raises:
|
| 1648 |
+
foo()
|
| 1649 |
+
self.assertIn(
|
| 1650 |
+
"list is immutable",
|
| 1651 |
+
str(raises.exception),
|
| 1652 |
+
)
|
lib/python3.10/site-packages/numba/tests/test_literal_dispatch.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import numba
|
| 4 |
+
import unittest
|
| 5 |
+
from numba.tests.support import TestCase
|
| 6 |
+
from numba import njit
|
| 7 |
+
from numba.core import types, errors, cgutils
|
| 8 |
+
from numba.core.typing import signature
|
| 9 |
+
from numba.core.datamodel import models
|
| 10 |
+
from numba.core.extending import (
|
| 11 |
+
overload, SentryLiteralArgs, overload_method, register_model, intrinsic,
|
| 12 |
+
)
|
| 13 |
+
from numba.misc.special import literally
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestLiteralDispatch(TestCase):
|
| 17 |
+
def check_literal_basic(self, literal_args):
|
| 18 |
+
@njit
|
| 19 |
+
def foo(x):
|
| 20 |
+
return literally(x)
|
| 21 |
+
|
| 22 |
+
# Test with int
|
| 23 |
+
for lit in literal_args:
|
| 24 |
+
self.assertEqual(foo(lit), lit)
|
| 25 |
+
|
| 26 |
+
for lit, sig in zip(literal_args, foo.signatures):
|
| 27 |
+
self.assertEqual(sig[0].literal_value, lit)
|
| 28 |
+
|
| 29 |
+
def test_literal_basic(self):
|
| 30 |
+
self.check_literal_basic([123, 321])
|
| 31 |
+
self.check_literal_basic(["abc", "cb123"])
|
| 32 |
+
|
| 33 |
+
def test_literal_nested(self):
|
| 34 |
+
@njit
|
| 35 |
+
def foo(x):
|
| 36 |
+
return literally(x) * 2
|
| 37 |
+
|
| 38 |
+
@njit
|
| 39 |
+
def bar(y, x):
|
| 40 |
+
return foo(y) + x
|
| 41 |
+
|
| 42 |
+
y, x = 3, 7
|
| 43 |
+
self.assertEqual(bar(y, x), y * 2 + x)
|
| 44 |
+
[foo_sig] = foo.signatures
|
| 45 |
+
self.assertEqual(foo_sig[0], types.literal(y))
|
| 46 |
+
[bar_sig] = bar.signatures
|
| 47 |
+
self.assertEqual(bar_sig[0], types.literal(y))
|
| 48 |
+
self.assertNotIsInstance(bar_sig[1], types.Literal)
|
| 49 |
+
|
| 50 |
+
def test_literally_freevar(self):
|
| 51 |
+
# Try referring to numba.literally not in the globals
|
| 52 |
+
import numba
|
| 53 |
+
|
| 54 |
+
@njit
|
| 55 |
+
def foo(x):
|
| 56 |
+
return numba.literally(x)
|
| 57 |
+
|
| 58 |
+
self.assertEqual(foo(123), 123)
|
| 59 |
+
self.assertEqual(foo.signatures[0][0], types.literal(123))
|
| 60 |
+
|
| 61 |
+
def test_mutual_recursion_literal(self):
|
| 62 |
+
def get_functions(decor):
|
| 63 |
+
@decor
|
| 64 |
+
def outer_fac(n, value):
|
| 65 |
+
if n < 1:
|
| 66 |
+
return value
|
| 67 |
+
return n * inner_fac(n - 1, value)
|
| 68 |
+
|
| 69 |
+
@decor
|
| 70 |
+
def inner_fac(n, value):
|
| 71 |
+
if n < 1:
|
| 72 |
+
return literally(value)
|
| 73 |
+
return n * outer_fac(n - 1, value)
|
| 74 |
+
|
| 75 |
+
return outer_fac, inner_fac
|
| 76 |
+
|
| 77 |
+
ref_outer_fac, ref_inner_fac = get_functions(lambda x: x)
|
| 78 |
+
outer_fac, inner_fac = get_functions(njit)
|
| 79 |
+
|
| 80 |
+
self.assertEqual(outer_fac(10, 12), ref_outer_fac(10, 12))
|
| 81 |
+
self.assertEqual(outer_fac.signatures[0][1].literal_value, 12)
|
| 82 |
+
self.assertEqual(inner_fac.signatures[0][1].literal_value, 12)
|
| 83 |
+
|
| 84 |
+
self.assertEqual(inner_fac(11, 13), ref_inner_fac(11, 13))
|
| 85 |
+
self.assertEqual(outer_fac.signatures[1][1].literal_value, 13)
|
| 86 |
+
self.assertEqual(inner_fac.signatures[1][1].literal_value, 13)
|
| 87 |
+
|
| 88 |
+
def test_literal_nested_multi_arg(self):
|
| 89 |
+
@njit
|
| 90 |
+
def foo(a, b, c):
|
| 91 |
+
return inner(a, c)
|
| 92 |
+
|
| 93 |
+
@njit
|
| 94 |
+
def inner(x, y):
|
| 95 |
+
return x + literally(y)
|
| 96 |
+
|
| 97 |
+
kwargs = dict(a=1, b=2, c=3)
|
| 98 |
+
got = foo(**kwargs)
|
| 99 |
+
expect = (lambda a, b, c: a + c)(**kwargs)
|
| 100 |
+
self.assertEqual(got, expect)
|
| 101 |
+
[foo_sig] = foo.signatures
|
| 102 |
+
self.assertEqual(foo_sig[2], types.literal(3))
|
| 103 |
+
|
| 104 |
+
def test_unsupported_literal_type(self):
|
| 105 |
+
@njit
|
| 106 |
+
def foo(a, b, c):
|
| 107 |
+
return inner(a, c)
|
| 108 |
+
|
| 109 |
+
@njit
|
| 110 |
+
def inner(x, y):
|
| 111 |
+
return x + literally(y)
|
| 112 |
+
|
| 113 |
+
arr = np.arange(10)
|
| 114 |
+
with self.assertRaises(errors.LiteralTypingError) as raises:
|
| 115 |
+
foo(a=1, b=2, c=arr)
|
| 116 |
+
self.assertIn("numpy.ndarray", str(raises.exception))
|
| 117 |
+
|
| 118 |
+
def test_biliteral(self):
|
| 119 |
+
# Test usecase with more than one literal call
|
| 120 |
+
@njit
|
| 121 |
+
def foo(a, b, c):
|
| 122 |
+
return inner(a, b) + inner(b, c)
|
| 123 |
+
|
| 124 |
+
@njit
|
| 125 |
+
def inner(x, y):
|
| 126 |
+
return x + literally(y)
|
| 127 |
+
|
| 128 |
+
kwargs = dict(a=1, b=2, c=3)
|
| 129 |
+
got = foo(**kwargs)
|
| 130 |
+
expect = (lambda a, b, c: a + b + b + c)(**kwargs)
|
| 131 |
+
self.assertEqual(got, expect)
|
| 132 |
+
[(type_a, type_b, type_c)] = foo.signatures
|
| 133 |
+
self.assertNotIsInstance(type_a, types.Literal)
|
| 134 |
+
self.assertIsInstance(type_b, types.Literal)
|
| 135 |
+
self.assertEqual(type_b.literal_value, 2)
|
| 136 |
+
self.assertIsInstance(type_c, types.Literal)
|
| 137 |
+
self.assertEqual(type_c.literal_value, 3)
|
| 138 |
+
|
| 139 |
+
def test_literally_varargs(self):
|
| 140 |
+
@njit
|
| 141 |
+
def foo(a, *args):
|
| 142 |
+
return literally(args)
|
| 143 |
+
|
| 144 |
+
with self.assertRaises(errors.LiteralTypingError):
|
| 145 |
+
foo(1, 2, 3)
|
| 146 |
+
|
| 147 |
+
@njit
|
| 148 |
+
def bar(a, b):
|
| 149 |
+
foo(a, b)
|
| 150 |
+
|
| 151 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 152 |
+
bar(1, 2)
|
| 153 |
+
self.assertIn(
|
| 154 |
+
"Cannot request literal type",
|
| 155 |
+
str(raises.exception),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
@unittest.expectedFailure
|
| 159 |
+
def test_literally_defaults(self):
|
| 160 |
+
# Problem with OmittedArg
|
| 161 |
+
@njit
|
| 162 |
+
def foo(a, b=1):
|
| 163 |
+
return (a, literally(b))
|
| 164 |
+
foo(a=1)
|
| 165 |
+
|
| 166 |
+
@unittest.expectedFailure
|
| 167 |
+
def test_literally_defaults_inner(self):
|
| 168 |
+
# Problem with Omitted
|
| 169 |
+
@njit
|
| 170 |
+
def foo(a, b=1):
|
| 171 |
+
return (a, literally(b))
|
| 172 |
+
|
| 173 |
+
@njit
|
| 174 |
+
def bar(a):
|
| 175 |
+
return foo(a) + 1
|
| 176 |
+
|
| 177 |
+
bar(1)
|
| 178 |
+
|
| 179 |
+
def test_literally_from_module(self):
|
| 180 |
+
# Problem with Omitted
|
| 181 |
+
@njit
|
| 182 |
+
def foo(x):
|
| 183 |
+
return numba.literally(x)
|
| 184 |
+
|
| 185 |
+
got = foo(123)
|
| 186 |
+
self.assertEqual(got, foo.py_func(123))
|
| 187 |
+
self.assertIsInstance(foo.signatures[0][0], types.Literal)
|
| 188 |
+
|
| 189 |
+
def test_non_literal(self):
|
| 190 |
+
@njit
|
| 191 |
+
def foo(a, b):
|
| 192 |
+
return literally(1 + a)
|
| 193 |
+
|
| 194 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 195 |
+
foo(1, 2)
|
| 196 |
+
self.assertIn(
|
| 197 |
+
"Invalid use of non-Literal type",
|
| 198 |
+
str(raises.exception),
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def test_inlined_literal(self):
|
| 202 |
+
# Check that literally accepts inlined literal
|
| 203 |
+
@njit
|
| 204 |
+
def foo(a, b):
|
| 205 |
+
v = 1000
|
| 206 |
+
return a + literally(v) + literally(b)
|
| 207 |
+
|
| 208 |
+
got = foo(1, 2)
|
| 209 |
+
self.assertEqual(got, foo.py_func(1, 2))
|
| 210 |
+
|
| 211 |
+
@njit
|
| 212 |
+
def bar():
|
| 213 |
+
a = 100
|
| 214 |
+
b = 9
|
| 215 |
+
return foo(a=b, b=a)
|
| 216 |
+
|
| 217 |
+
got = bar()
|
| 218 |
+
self.assertEqual(got, bar.py_func())
|
| 219 |
+
|
| 220 |
+
def test_aliased_variable(self):
|
| 221 |
+
@njit
|
| 222 |
+
def foo(a, b, c):
|
| 223 |
+
def closure(d):
|
| 224 |
+
return literally(d) + 10 * inner(a, b)
|
| 225 |
+
# The inlining of the closure will create an alias to c
|
| 226 |
+
return closure(c)
|
| 227 |
+
|
| 228 |
+
@njit
|
| 229 |
+
def inner(x, y):
|
| 230 |
+
return x + literally(y)
|
| 231 |
+
|
| 232 |
+
kwargs = dict(a=1, b=2, c=3)
|
| 233 |
+
got = foo(**kwargs)
|
| 234 |
+
expect = (lambda a, b, c: c + 10 * (a + b))(**kwargs)
|
| 235 |
+
self.assertEqual(got, expect)
|
| 236 |
+
[(type_a, type_b, type_c)] = foo.signatures
|
| 237 |
+
self.assertNotIsInstance(type_a, types.Literal)
|
| 238 |
+
self.assertIsInstance(type_b, types.Literal)
|
| 239 |
+
self.assertEqual(type_b.literal_value, 2)
|
| 240 |
+
self.assertIsInstance(type_c, types.Literal)
|
| 241 |
+
self.assertEqual(type_c.literal_value, 3)
|
| 242 |
+
|
| 243 |
+
def test_overload_explicit(self):
|
| 244 |
+
# This test represents a more controlled usage with ensuring literal
|
| 245 |
+
# typing for an argument.
|
| 246 |
+
def do_this(x, y):
|
| 247 |
+
return x + y
|
| 248 |
+
|
| 249 |
+
@overload(do_this)
|
| 250 |
+
def ov_do_this(x, y):
|
| 251 |
+
SentryLiteralArgs(['x']).for_function(ov_do_this).bind(x, y)
|
| 252 |
+
return lambda x, y: x + y
|
| 253 |
+
|
| 254 |
+
@njit
|
| 255 |
+
def foo(a, b):
|
| 256 |
+
return do_this(a, b)
|
| 257 |
+
|
| 258 |
+
a = 123
|
| 259 |
+
b = 321
|
| 260 |
+
r = foo(a, b)
|
| 261 |
+
self.assertEqual(r, a + b)
|
| 262 |
+
[type_a, type_b] = foo.signatures[0]
|
| 263 |
+
self.assertIsInstance(type_a, types.Literal)
|
| 264 |
+
self.assertEqual(type_a.literal_value, a)
|
| 265 |
+
self.assertNotIsInstance(type_b, types.Literal)
|
| 266 |
+
|
| 267 |
+
def test_overload_implicit(self):
|
| 268 |
+
# This test represents the preferred usage style for using literally
|
| 269 |
+
# in overload. Here, literally() is used inside the "implementation"
|
| 270 |
+
# function of the overload.
|
| 271 |
+
def do_this(x, y):
|
| 272 |
+
return x + y
|
| 273 |
+
|
| 274 |
+
@njit
|
| 275 |
+
def hidden(x, y):
|
| 276 |
+
return literally(x) + y
|
| 277 |
+
|
| 278 |
+
@overload(do_this)
|
| 279 |
+
def ov_do_this(x, y):
|
| 280 |
+
if isinstance(x, types.Integer):
|
| 281 |
+
# At this point, `x` can be a literal or not
|
| 282 |
+
return lambda x, y: hidden(x, y)
|
| 283 |
+
|
| 284 |
+
@njit
|
| 285 |
+
def foo(a, b):
|
| 286 |
+
return do_this(a, b)
|
| 287 |
+
|
| 288 |
+
a = 123
|
| 289 |
+
b = 321
|
| 290 |
+
r = foo(a, b)
|
| 291 |
+
self.assertEqual(r, a + b)
|
| 292 |
+
[type_a, type_b] = foo.signatures[0]
|
| 293 |
+
self.assertIsInstance(type_a, types.Literal)
|
| 294 |
+
self.assertEqual(type_a.literal_value, a)
|
| 295 |
+
self.assertNotIsInstance(type_b, types.Literal)
|
| 296 |
+
|
| 297 |
+
def test_overload_error_loop(self):
|
| 298 |
+
# Test a case where a infinite compiling loop is caused because a
|
| 299 |
+
# literal type is requested but an error would raise for the
|
| 300 |
+
# literal-ized code path. This causes the overload resolution to
|
| 301 |
+
# retry by "de-literal-izing" the values.
|
| 302 |
+
def do_this(x, y):
|
| 303 |
+
return x + y
|
| 304 |
+
|
| 305 |
+
@njit
|
| 306 |
+
def hidden(x, y):
|
| 307 |
+
return literally(x) + y
|
| 308 |
+
|
| 309 |
+
@overload(do_this)
|
| 310 |
+
def ov_do_this(x, y):
|
| 311 |
+
if isinstance(y, types.IntegerLiteral):
|
| 312 |
+
# This error is however suppressed because a non-literal
|
| 313 |
+
# version is valid.
|
| 314 |
+
raise errors.NumbaValueError("oops")
|
| 315 |
+
else:
|
| 316 |
+
def impl(x, y):
|
| 317 |
+
return hidden(x, y)
|
| 318 |
+
return impl
|
| 319 |
+
|
| 320 |
+
@njit
|
| 321 |
+
def foo(a, b):
|
| 322 |
+
return do_this(a, literally(b))
|
| 323 |
+
|
| 324 |
+
# Expect raising CompilerError to stop re-compiling with duplicated
|
| 325 |
+
# literal typing request.
|
| 326 |
+
with self.assertRaises(errors.CompilerError) as raises:
|
| 327 |
+
foo(a=123, b=321)
|
| 328 |
+
self.assertIn("Repeated literal typing request",
|
| 329 |
+
str(raises.exception))
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class TestLiteralDispatchWithCustomType(TestCase):
|
| 333 |
+
def make_dummy_type(self):
|
| 334 |
+
class Dummy(object):
|
| 335 |
+
def lit(self, a):
|
| 336 |
+
return a
|
| 337 |
+
|
| 338 |
+
class DummyType(types.Type):
|
| 339 |
+
def __init__(self):
|
| 340 |
+
super(DummyType, self).__init__(name="dummy")
|
| 341 |
+
|
| 342 |
+
@register_model(DummyType)
|
| 343 |
+
class DummyTypeModel(models.StructModel):
|
| 344 |
+
def __init__(self, dmm, fe_type):
|
| 345 |
+
members = []
|
| 346 |
+
super(DummyTypeModel, self).__init__(dmm, fe_type, members)
|
| 347 |
+
|
| 348 |
+
@intrinsic
|
| 349 |
+
def init_dummy(typingctx):
|
| 350 |
+
def codegen(context, builder, signature, args):
|
| 351 |
+
dummy = cgutils.create_struct_proxy(
|
| 352 |
+
signature.return_type)(context, builder)
|
| 353 |
+
|
| 354 |
+
return dummy._getvalue()
|
| 355 |
+
|
| 356 |
+
sig = signature(DummyType())
|
| 357 |
+
return sig, codegen
|
| 358 |
+
|
| 359 |
+
@overload(Dummy)
|
| 360 |
+
def dummy_overload():
|
| 361 |
+
def ctor():
|
| 362 |
+
return init_dummy()
|
| 363 |
+
|
| 364 |
+
return ctor
|
| 365 |
+
|
| 366 |
+
return (DummyType, Dummy)
|
| 367 |
+
|
| 368 |
+
def test_overload_method(self):
|
| 369 |
+
# from issue #5011
|
| 370 |
+
DummyType, Dummy = self.make_dummy_type()
|
| 371 |
+
|
| 372 |
+
@overload_method(DummyType, 'lit')
|
| 373 |
+
def lit_overload(self, a):
|
| 374 |
+
def impl(self, a):
|
| 375 |
+
return literally(a) # <-- using literally here
|
| 376 |
+
|
| 377 |
+
return impl
|
| 378 |
+
|
| 379 |
+
@njit
|
| 380 |
+
def test_impl(a):
|
| 381 |
+
d = Dummy()
|
| 382 |
+
|
| 383 |
+
return d.lit(a)
|
| 384 |
+
|
| 385 |
+
# Successful case
|
| 386 |
+
self.assertEqual(test_impl(5), 5)
|
| 387 |
+
|
| 388 |
+
# Failing case
|
| 389 |
+
@njit
|
| 390 |
+
def inside(a):
|
| 391 |
+
return test_impl(a + 1)
|
| 392 |
+
|
| 393 |
+
with self.assertRaises(errors.TypingError) as raises:
|
| 394 |
+
inside(4)
|
| 395 |
+
|
| 396 |
+
self.assertIn("Cannot request literal type.", str(raises.exception))
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
if __name__ == '__main__':
|
| 400 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_looplifting.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 6 |
+
from numba.tests.support import TestCase, tag, MemoryLeakMixin
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
looplift_flags = Flags()
|
| 11 |
+
looplift_flags.force_pyobject = True
|
| 12 |
+
looplift_flags.enable_looplift = True
|
| 13 |
+
|
| 14 |
+
pyobject_looplift_flags = looplift_flags.copy()
|
| 15 |
+
pyobject_looplift_flags.enable_pyobject_looplift = True
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def compile_isolated(pyfunc, argtypes, **kwargs):
|
| 19 |
+
from numba.core.registry import cpu_target
|
| 20 |
+
|
| 21 |
+
kwargs.setdefault('return_type', None)
|
| 22 |
+
kwargs.setdefault('locals', {})
|
| 23 |
+
return compile_extra(
|
| 24 |
+
cpu_target.typing_context,
|
| 25 |
+
cpu_target.target_context,
|
| 26 |
+
pyfunc,
|
| 27 |
+
argtypes,
|
| 28 |
+
**kwargs,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def lift1(x):
|
| 33 |
+
# Outer needs object mode because of np.empty()
|
| 34 |
+
a = np.empty(3)
|
| 35 |
+
for i in range(a.size):
|
| 36 |
+
# Inner is nopython-compliant
|
| 37 |
+
a[i] = x
|
| 38 |
+
return a
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def lift2(x):
|
| 42 |
+
# Outer needs object mode because of np.empty()
|
| 43 |
+
a = np.empty((3, 4))
|
| 44 |
+
for i in range(a.shape[0]):
|
| 45 |
+
for j in range(a.shape[1]):
|
| 46 |
+
# Inner is nopython-compliant
|
| 47 |
+
a[i, j] = x
|
| 48 |
+
return a
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def lift3(x):
|
| 52 |
+
# Output variable from the loop
|
| 53 |
+
_ = object()
|
| 54 |
+
a = np.arange(5, dtype=np.int64)
|
| 55 |
+
c = 0
|
| 56 |
+
for i in range(a.shape[0]):
|
| 57 |
+
c += a[i] * x
|
| 58 |
+
return c
|
| 59 |
+
|
| 60 |
+
def lift4(x):
|
| 61 |
+
# Output two variables from the loop
|
| 62 |
+
_ = object()
|
| 63 |
+
a = np.arange(5, dtype=np.int64)
|
| 64 |
+
c = 0
|
| 65 |
+
d = 0
|
| 66 |
+
for i in range(a.shape[0]):
|
| 67 |
+
c += a[i] * x
|
| 68 |
+
d += c
|
| 69 |
+
return c + d
|
| 70 |
+
|
| 71 |
+
def lift5(x):
|
| 72 |
+
_ = object()
|
| 73 |
+
a = np.arange(4)
|
| 74 |
+
for i in range(a.shape[0]):
|
| 75 |
+
# Inner has a break statement
|
| 76 |
+
if i > 2:
|
| 77 |
+
break
|
| 78 |
+
return a
|
| 79 |
+
|
| 80 |
+
def lift_gen1(x):
|
| 81 |
+
# Outer needs object mode because of np.empty()
|
| 82 |
+
a = np.empty(3)
|
| 83 |
+
yield 0
|
| 84 |
+
for i in range(a.size):
|
| 85 |
+
# Inner is nopython-compliant
|
| 86 |
+
a[i] = x
|
| 87 |
+
yield np.sum(a)
|
| 88 |
+
|
| 89 |
+
def lift_issue2561():
|
| 90 |
+
np.empty(1) # This forces objectmode because no nrt
|
| 91 |
+
for i in range(10):
|
| 92 |
+
for j in range(10):
|
| 93 |
+
return 1
|
| 94 |
+
return 2
|
| 95 |
+
|
| 96 |
+
def reject1(x):
|
| 97 |
+
a = np.arange(4)
|
| 98 |
+
for i in range(a.shape[0]):
|
| 99 |
+
# Inner returns a variable from outer "scope" => cannot loop-lift
|
| 100 |
+
return a
|
| 101 |
+
return a
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def reject_gen1(x):
|
| 105 |
+
_ = object()
|
| 106 |
+
a = np.arange(4)
|
| 107 |
+
for i in range(a.shape[0]):
|
| 108 |
+
# Inner is a generator => cannot loop-lift
|
| 109 |
+
yield a[i]
|
| 110 |
+
|
| 111 |
+
def reject_gen2(x):
|
| 112 |
+
_ = object()
|
| 113 |
+
a = np.arange(3)
|
| 114 |
+
for i in range(a.size):
|
| 115 |
+
# Middle has a yield => cannot loop-lift
|
| 116 |
+
res = a[i] + x
|
| 117 |
+
for j in range(i):
|
| 118 |
+
# Inner is nopython-compliant, but the current algorithm isn't
|
| 119 |
+
# able to separate it.
|
| 120 |
+
res = res ** 2
|
| 121 |
+
yield res
|
| 122 |
+
|
| 123 |
+
def reject_npm1(x):
|
| 124 |
+
a = np.empty(3, dtype=np.int32)
|
| 125 |
+
for i in range(a.size):
|
| 126 |
+
# Inner uses object() => cannot loop-lift
|
| 127 |
+
_ = object()
|
| 128 |
+
a[i] = np.arange(i + 1)[i]
|
| 129 |
+
|
| 130 |
+
return a
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class TestLoopLifting(MemoryLeakMixin, TestCase):
|
| 134 |
+
|
| 135 |
+
def try_lift(self, pyfunc, argtypes):
|
| 136 |
+
from numba.core.registry import cpu_target
|
| 137 |
+
|
| 138 |
+
cres = compile_extra(
|
| 139 |
+
cpu_target.typing_context,
|
| 140 |
+
cpu_target.target_context,
|
| 141 |
+
pyfunc, argtypes,
|
| 142 |
+
return_type=None, flags=looplift_flags, locals={},
|
| 143 |
+
)
|
| 144 |
+
# One lifted loop
|
| 145 |
+
self.assertEqual(len(cres.lifted), 1)
|
| 146 |
+
return cres
|
| 147 |
+
|
| 148 |
+
def assert_lifted_native(self, cres):
|
| 149 |
+
# Check if we have lifted in nopython mode
|
| 150 |
+
jitloop = cres.lifted[0]
|
| 151 |
+
[loopcres] = jitloop.overloads.values()
|
| 152 |
+
self.assertTrue(loopcres.fndesc.native) # Lifted function is native
|
| 153 |
+
|
| 154 |
+
def check_lift_ok(self, pyfunc, argtypes, args):
|
| 155 |
+
"""
|
| 156 |
+
Check that pyfunc can loop-lift even in nopython mode.
|
| 157 |
+
"""
|
| 158 |
+
cres = self.try_lift(pyfunc, argtypes)
|
| 159 |
+
expected = pyfunc(*args)
|
| 160 |
+
got = cres.entry_point(*args)
|
| 161 |
+
self.assert_lifted_native(cres)
|
| 162 |
+
# Check return values
|
| 163 |
+
self.assertPreciseEqual(expected, got)
|
| 164 |
+
|
| 165 |
+
def check_lift_generator_ok(self, pyfunc, argtypes, args):
|
| 166 |
+
"""
|
| 167 |
+
Check that pyfunc (a generator function) can loop-lift even in
|
| 168 |
+
nopython mode.
|
| 169 |
+
"""
|
| 170 |
+
cres = self.try_lift(pyfunc, argtypes)
|
| 171 |
+
expected = list(pyfunc(*args))
|
| 172 |
+
got = list(cres.entry_point(*args))
|
| 173 |
+
self.assert_lifted_native(cres)
|
| 174 |
+
# Check return values
|
| 175 |
+
self.assertPreciseEqual(expected, got)
|
| 176 |
+
|
| 177 |
+
def check_no_lift(self, pyfunc, argtypes, args):
|
| 178 |
+
"""
|
| 179 |
+
Check that pyfunc can't loop-lift.
|
| 180 |
+
"""
|
| 181 |
+
cres = compile_isolated(pyfunc, argtypes,
|
| 182 |
+
flags=looplift_flags)
|
| 183 |
+
self.assertFalse(cres.lifted)
|
| 184 |
+
expected = pyfunc(*args)
|
| 185 |
+
got = cres.entry_point(*args)
|
| 186 |
+
# Check return values
|
| 187 |
+
self.assertPreciseEqual(expected, got)
|
| 188 |
+
|
| 189 |
+
def check_no_lift_generator(self, pyfunc, argtypes, args):
|
| 190 |
+
"""
|
| 191 |
+
Check that pyfunc (a generator function) can't loop-lift.
|
| 192 |
+
"""
|
| 193 |
+
cres = compile_isolated(pyfunc, argtypes,
|
| 194 |
+
flags=looplift_flags)
|
| 195 |
+
self.assertFalse(cres.lifted)
|
| 196 |
+
expected = list(pyfunc(*args))
|
| 197 |
+
got = list(cres.entry_point(*args))
|
| 198 |
+
self.assertPreciseEqual(expected, got)
|
| 199 |
+
|
| 200 |
+
def test_lift1(self):
|
| 201 |
+
self.check_lift_ok(lift1, (types.intp,), (123,))
|
| 202 |
+
|
| 203 |
+
def test_lift2(self):
|
| 204 |
+
self.check_lift_ok(lift2, (types.intp,), (123,))
|
| 205 |
+
|
| 206 |
+
def test_lift3(self):
|
| 207 |
+
self.check_lift_ok(lift3, (types.intp,), (123,))
|
| 208 |
+
|
| 209 |
+
def test_lift4(self):
|
| 210 |
+
self.check_lift_ok(lift4, (types.intp,), (123,))
|
| 211 |
+
|
| 212 |
+
def test_lift5(self):
|
| 213 |
+
self.check_lift_ok(lift5, (types.intp,), (123,))
|
| 214 |
+
|
| 215 |
+
def test_lift_issue2561(self):
|
| 216 |
+
self.check_lift_ok(lift_issue2561, (), ())
|
| 217 |
+
|
| 218 |
+
def test_lift_gen1(self):
|
| 219 |
+
self.check_lift_generator_ok(lift_gen1, (types.intp,), (123,))
|
| 220 |
+
|
| 221 |
+
def test_reject1(self):
|
| 222 |
+
self.check_no_lift(reject1, (types.intp,), (123,))
|
| 223 |
+
|
| 224 |
+
def test_reject_gen1(self):
|
| 225 |
+
self.check_no_lift_generator(reject_gen1, (types.intp,), (123,))
|
| 226 |
+
|
| 227 |
+
def test_reject_gen2(self):
|
| 228 |
+
self.check_no_lift_generator(reject_gen2, (types.intp,), (123,))
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class TestLoopLiftingAnnotate(TestCase):
|
| 232 |
+
def test_annotate_1(self):
|
| 233 |
+
"""
|
| 234 |
+
Verify that annotation works as expected with one lifted loop
|
| 235 |
+
"""
|
| 236 |
+
from numba import jit
|
| 237 |
+
|
| 238 |
+
# dummy function to force objmode
|
| 239 |
+
def bar():
|
| 240 |
+
pass
|
| 241 |
+
|
| 242 |
+
def foo(x):
|
| 243 |
+
bar() # force obj
|
| 244 |
+
for i in range(x.size):
|
| 245 |
+
x[i] += 1
|
| 246 |
+
|
| 247 |
+
return x
|
| 248 |
+
|
| 249 |
+
cfoo = jit(forceobj=True)(foo)
|
| 250 |
+
|
| 251 |
+
x = np.arange(10)
|
| 252 |
+
xcopy = x.copy()
|
| 253 |
+
r = cfoo(x)
|
| 254 |
+
np.testing.assert_equal(r, xcopy + 1)
|
| 255 |
+
|
| 256 |
+
buf = StringIO()
|
| 257 |
+
cfoo.inspect_types(file=buf)
|
| 258 |
+
annotation = buf.getvalue()
|
| 259 |
+
buf.close()
|
| 260 |
+
|
| 261 |
+
self.assertIn("The function contains lifted loops", annotation)
|
| 262 |
+
line = foo.__code__.co_firstlineno + 2 # 2 lines down from func head
|
| 263 |
+
self.assertIn("Loop at line {line}".format(line=line), annotation)
|
| 264 |
+
self.assertIn("Has 1 overloads", annotation)
|
| 265 |
+
|
| 266 |
+
def test_annotate_2(self):
|
| 267 |
+
"""
|
| 268 |
+
Verify that annotation works as expected with two lifted loops
|
| 269 |
+
"""
|
| 270 |
+
from numba import jit
|
| 271 |
+
|
| 272 |
+
# dummy function to force objmode
|
| 273 |
+
def bar():
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
def foo(x):
|
| 277 |
+
bar() # force obj
|
| 278 |
+
# first lifted loop
|
| 279 |
+
for i in range(x.size):
|
| 280 |
+
x[i] += 1
|
| 281 |
+
# second lifted loop
|
| 282 |
+
for j in range(x.size):
|
| 283 |
+
x[j] *= 2
|
| 284 |
+
return x
|
| 285 |
+
|
| 286 |
+
cfoo = jit(forceobj=True)(foo)
|
| 287 |
+
|
| 288 |
+
x = np.arange(10)
|
| 289 |
+
xcopy = x.copy()
|
| 290 |
+
r = cfoo(x)
|
| 291 |
+
np.testing.assert_equal(r, (xcopy + 1) * 2)
|
| 292 |
+
|
| 293 |
+
buf = StringIO()
|
| 294 |
+
cfoo.inspect_types(file=buf)
|
| 295 |
+
annotation = buf.getvalue()
|
| 296 |
+
buf.close()
|
| 297 |
+
|
| 298 |
+
self.assertIn("The function contains lifted loops", annotation)
|
| 299 |
+
line1 = foo.__code__.co_firstlineno + 3 # 3 lines down from func head
|
| 300 |
+
line2 = foo.__code__.co_firstlineno + 6 # 6 lines down from func head
|
| 301 |
+
self.assertIn("Loop at line {line}".format(line=line1), annotation)
|
| 302 |
+
self.assertIn("Loop at line {line}".format(line=line2), annotation)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class TestLoopLiftingInAction(MemoryLeakMixin, TestCase):
|
| 306 |
+
def assert_has_lifted(self, jitted, loopcount):
|
| 307 |
+
lifted = jitted.overloads[jitted.signatures[0]].lifted
|
| 308 |
+
self.assertEqual(len(lifted), loopcount)
|
| 309 |
+
|
| 310 |
+
def test_issue_734(self):
|
| 311 |
+
from numba import jit, void, int32, double
|
| 312 |
+
|
| 313 |
+
@jit(void(int32, double[:]), forceobj=True)
|
| 314 |
+
def forloop_with_if(u, a):
|
| 315 |
+
if u == 0:
|
| 316 |
+
for i in range(a.shape[0]):
|
| 317 |
+
a[i] = a[i] * 2.0
|
| 318 |
+
else:
|
| 319 |
+
for i in range(a.shape[0]):
|
| 320 |
+
a[i] = a[i] + 1.0
|
| 321 |
+
|
| 322 |
+
for u in (0, 1):
|
| 323 |
+
nb_a = np.arange(10, dtype='int32')
|
| 324 |
+
np_a = np.arange(10, dtype='int32')
|
| 325 |
+
forloop_with_if(u, nb_a)
|
| 326 |
+
forloop_with_if.py_func(u, np_a)
|
| 327 |
+
self.assertPreciseEqual(nb_a, np_a)
|
| 328 |
+
|
| 329 |
+
def test_issue_812(self):
|
| 330 |
+
from numba import jit
|
| 331 |
+
|
| 332 |
+
@jit('f8[:](f8[:])', forceobj=True)
|
| 333 |
+
def test(x):
|
| 334 |
+
res = np.zeros(len(x))
|
| 335 |
+
ind = 0
|
| 336 |
+
for ii in range(len(x)):
|
| 337 |
+
ind += 1
|
| 338 |
+
res[ind] = x[ind]
|
| 339 |
+
if x[ind] >= 10:
|
| 340 |
+
break
|
| 341 |
+
|
| 342 |
+
# Invalid loopjitting will miss the usage of `ind` in the
|
| 343 |
+
# following loop.
|
| 344 |
+
for ii in range(ind + 1, len(x)):
|
| 345 |
+
res[ii] = 0
|
| 346 |
+
return res
|
| 347 |
+
|
| 348 |
+
x = np.array([1., 4, 2, -3, 5, 2, 10, 5, 2, 6])
|
| 349 |
+
np.testing.assert_equal(test.py_func(x), test(x))
|
| 350 |
+
|
| 351 |
+
def test_issue_2368(self):
|
| 352 |
+
from numba import jit
|
| 353 |
+
|
| 354 |
+
def lift_issue2368(a, b):
|
| 355 |
+
s = 0
|
| 356 |
+
for e in a:
|
| 357 |
+
s += e
|
| 358 |
+
h = b.__hash__()
|
| 359 |
+
return s, h
|
| 360 |
+
|
| 361 |
+
a = np.ones(10)
|
| 362 |
+
b = object()
|
| 363 |
+
jitted = jit(forceobj=True)(lift_issue2368)
|
| 364 |
+
|
| 365 |
+
expected = lift_issue2368(a, b)
|
| 366 |
+
got = jitted(a, b)
|
| 367 |
+
|
| 368 |
+
self.assertEqual(expected[0], got[0])
|
| 369 |
+
self.assertEqual(expected[1], got[1])
|
| 370 |
+
|
| 371 |
+
jitloop = jitted.overloads[jitted.signatures[0]].lifted[0]
|
| 372 |
+
[loopcres] = jitloop.overloads.values()
|
| 373 |
+
# assert lifted function is native
|
| 374 |
+
self.assertTrue(loopcres.fndesc.native)
|
| 375 |
+
|
| 376 |
+
def test_no_iteration_w_redef(self):
|
| 377 |
+
# redefinition of res in the loop with no use of res should not
|
| 378 |
+
# prevent lifting
|
| 379 |
+
from numba import jit
|
| 380 |
+
|
| 381 |
+
@jit(forceobj=True)
|
| 382 |
+
def test(n):
|
| 383 |
+
res = 0
|
| 384 |
+
for i in range(n):
|
| 385 |
+
res = i
|
| 386 |
+
return res
|
| 387 |
+
|
| 388 |
+
# loop count = 1, loop lift but loop body not execute
|
| 389 |
+
self.assertEqual(test.py_func(-1), test(-1))
|
| 390 |
+
self.assert_has_lifted(test, loopcount=1)
|
| 391 |
+
# loop count = 1, loop will lift and will execute
|
| 392 |
+
self.assertEqual(test.py_func(1), test(1))
|
| 393 |
+
self.assert_has_lifted(test, loopcount=1)
|
| 394 |
+
|
| 395 |
+
def test_no_iteration(self):
|
| 396 |
+
from numba import jit
|
| 397 |
+
|
| 398 |
+
@jit(forceobj=True)
|
| 399 |
+
def test(n):
|
| 400 |
+
res = 0
|
| 401 |
+
for i in range(n):
|
| 402 |
+
res += i
|
| 403 |
+
return res
|
| 404 |
+
|
| 405 |
+
# loop count = 1
|
| 406 |
+
self.assertEqual(test.py_func(-1), test(-1))
|
| 407 |
+
self.assert_has_lifted(test, loopcount=1)
|
| 408 |
+
# loop count = 1
|
| 409 |
+
self.assertEqual(test.py_func(1), test(1))
|
| 410 |
+
self.assert_has_lifted(test, loopcount=1)
|
| 411 |
+
|
| 412 |
+
def test_define_in_loop_body(self):
|
| 413 |
+
# tests a definition in a loop that leaves the loop is liftable
|
| 414 |
+
from numba import jit
|
| 415 |
+
|
| 416 |
+
@jit(forceobj=True)
|
| 417 |
+
def test(n):
|
| 418 |
+
for i in range(n):
|
| 419 |
+
res = i
|
| 420 |
+
return res
|
| 421 |
+
|
| 422 |
+
# loop count = 1
|
| 423 |
+
self.assertEqual(test.py_func(1), test(1))
|
| 424 |
+
self.assert_has_lifted(test, loopcount=1)
|
| 425 |
+
|
| 426 |
+
def test_invalid_argument(self):
|
| 427 |
+
"""Test a problem caused by invalid discovery of loop argument
|
| 428 |
+
when a variable is used afterwards but not before.
|
| 429 |
+
|
| 430 |
+
Before the fix, this will result in::
|
| 431 |
+
|
| 432 |
+
numba.ir.NotDefinedError: 'i' is not defined
|
| 433 |
+
"""
|
| 434 |
+
from numba import jit
|
| 435 |
+
|
| 436 |
+
@jit(forceobj=True)
|
| 437 |
+
def test(arg):
|
| 438 |
+
if type(arg) == np.ndarray: # force object mode
|
| 439 |
+
if arg.ndim == 1:
|
| 440 |
+
result = 0.0
|
| 441 |
+
j = 0
|
| 442 |
+
for i in range(arg.shape[0]):
|
| 443 |
+
pass
|
| 444 |
+
else:
|
| 445 |
+
raise Exception
|
| 446 |
+
else:
|
| 447 |
+
result = 0.0
|
| 448 |
+
i, j = 0, 0
|
| 449 |
+
return result
|
| 450 |
+
|
| 451 |
+
arg = np.arange(10)
|
| 452 |
+
self.assertEqual(test.py_func(arg), test(arg))
|
| 453 |
+
|
| 454 |
+
def test_conditionally_defined_in_loop(self):
|
| 455 |
+
from numba import jit
|
| 456 |
+
@jit(forceobj=True)
|
| 457 |
+
def test():
|
| 458 |
+
x = 5
|
| 459 |
+
y = 0
|
| 460 |
+
for i in range(2):
|
| 461 |
+
if i > 0:
|
| 462 |
+
x = 6
|
| 463 |
+
y += x
|
| 464 |
+
return y, x
|
| 465 |
+
|
| 466 |
+
self.assertEqual(test.py_func(), test())
|
| 467 |
+
self.assert_has_lifted(test, loopcount=1)
|
| 468 |
+
|
| 469 |
+
def test_stack_offset_error_when_has_no_return(self):
|
| 470 |
+
from numba import jit
|
| 471 |
+
import warnings
|
| 472 |
+
|
| 473 |
+
def pyfunc(a):
|
| 474 |
+
if a:
|
| 475 |
+
for i in range(10):
|
| 476 |
+
pass
|
| 477 |
+
|
| 478 |
+
with warnings.catch_warnings():
|
| 479 |
+
warnings.simplefilter("error")
|
| 480 |
+
|
| 481 |
+
cfunc = jit(forceobj=True)(pyfunc)
|
| 482 |
+
self.assertEqual(pyfunc(True), cfunc(True))
|
| 483 |
+
|
| 484 |
+
def test_variable_scope_bug(self):
|
| 485 |
+
"""
|
| 486 |
+
https://github.com/numba/numba/issues/2179
|
| 487 |
+
|
| 488 |
+
Looplifting transformation is using the wrong version of variable `h`.
|
| 489 |
+
"""
|
| 490 |
+
from numba import jit
|
| 491 |
+
|
| 492 |
+
def bar(x):
|
| 493 |
+
return x
|
| 494 |
+
|
| 495 |
+
def foo(x):
|
| 496 |
+
h = 0.
|
| 497 |
+
for k in range(x):
|
| 498 |
+
h = h + k
|
| 499 |
+
h = h - bar(x)
|
| 500 |
+
return h
|
| 501 |
+
|
| 502 |
+
cfoo = jit(forceobj=True)(foo)
|
| 503 |
+
self.assertEqual(foo(10), cfoo(10))
|
| 504 |
+
|
| 505 |
+
def test_recompilation_loop(self):
|
| 506 |
+
"""
|
| 507 |
+
https://github.com/numba/numba/issues/2481
|
| 508 |
+
"""
|
| 509 |
+
from numba import jit
|
| 510 |
+
|
| 511 |
+
def foo(x, y):
|
| 512 |
+
# slicing to make array `x` into different layout
|
| 513 |
+
# to cause a new compilation of the lifted loop
|
| 514 |
+
A = x[::y]
|
| 515 |
+
c = 1
|
| 516 |
+
for k in range(A.size):
|
| 517 |
+
object() # to force objectmode and looplifting
|
| 518 |
+
c = c * A[::-1][k] # the slice that is failing in static_getitem
|
| 519 |
+
return c
|
| 520 |
+
|
| 521 |
+
cfoo = jit(forceobj=True)(foo)
|
| 522 |
+
# First run just works
|
| 523 |
+
args = np.arange(10), 1
|
| 524 |
+
self.assertEqual(foo(*args), cfoo(*args))
|
| 525 |
+
# Exactly 1 lifted loop so far
|
| 526 |
+
self.assertEqual(len(cfoo.overloads[cfoo.signatures[0]].lifted), 1)
|
| 527 |
+
lifted = cfoo.overloads[cfoo.signatures[0]].lifted[0]
|
| 528 |
+
# The lifted loop has 1 signature
|
| 529 |
+
self.assertEqual(len(lifted.signatures), 1)
|
| 530 |
+
# Use different argument to trigger a new compilation of the lifted loop
|
| 531 |
+
args = np.arange(10), -1
|
| 532 |
+
self.assertEqual(foo(*args), cfoo(*args))
|
| 533 |
+
# Ensure that is really a new overload for the lifted loop
|
| 534 |
+
self.assertEqual(len(lifted.signatures), 2)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def test_lift_objectmode_issue_4223(self):
|
| 538 |
+
from numba import jit
|
| 539 |
+
|
| 540 |
+
@jit(forceobj=True)
|
| 541 |
+
def foo(a, b, c, d, x0, y0, n):
|
| 542 |
+
xs, ys = np.zeros(n), np.zeros(n)
|
| 543 |
+
xs[0], ys[0] = x0, y0
|
| 544 |
+
for i in np.arange(n-1):
|
| 545 |
+
xs[i+1] = np.sin(a * ys[i]) + c * np.cos(a * xs[i])
|
| 546 |
+
ys[i+1] = np.sin(b * xs[i]) + d * np.cos(b * ys[i])
|
| 547 |
+
object() # ensure object mode
|
| 548 |
+
return xs, ys
|
| 549 |
+
|
| 550 |
+
kwargs = dict(a=1.7, b=1.7, c=0.6, d=1.2, x0=0, y0=0, n=200)
|
| 551 |
+
got = foo(**kwargs)
|
| 552 |
+
expected = foo.py_func(**kwargs)
|
| 553 |
+
self.assertPreciseEqual(got[0], expected[0])
|
| 554 |
+
self .assertPreciseEqual(got[1], expected[1])
|
| 555 |
+
[lifted] = foo.overloads[foo.signatures[0]].lifted
|
| 556 |
+
self.assertEqual(len(lifted.nopython_signatures), 1)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
if __name__ == '__main__':
|
| 560 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_mangling.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Test function name mangling.
|
| 4 |
+
The mangling affects the ABI of numba compiled binaries.
|
| 5 |
+
"""
|
| 6 |
+
from numba.core import types
|
| 7 |
+
from numba.core.funcdesc import default_mangler
|
| 8 |
+
from numba.tests.support import unittest, TestCase
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestMangling(TestCase):
|
| 12 |
+
def test_one_args(self):
|
| 13 |
+
fname = 'foo'
|
| 14 |
+
argtypes = types.int32,
|
| 15 |
+
name = default_mangler(fname, argtypes)
|
| 16 |
+
self.assertEqual(name, '_Z3fooi')
|
| 17 |
+
|
| 18 |
+
def test_two_args(self):
|
| 19 |
+
fname = 'foo'
|
| 20 |
+
argtypes = types.int32, types.float32
|
| 21 |
+
name = default_mangler(fname, argtypes)
|
| 22 |
+
self.assertEqual(name, '_Z3fooif')
|
| 23 |
+
|
| 24 |
+
def test_unicode_fname(self):
|
| 25 |
+
fname = u'foಠ'
|
| 26 |
+
argtypes = types.int32, types.float32
|
| 27 |
+
name = default_mangler(fname, argtypes)
|
| 28 |
+
self.assertIsInstance(name, str)
|
| 29 |
+
# manually encode it
|
| 30 |
+
unichar = fname[2]
|
| 31 |
+
enc = ''.join('_{:02x}'.format(c)
|
| 32 |
+
for c in unichar.encode('utf8'))
|
| 33 |
+
text = 'fo' + enc
|
| 34 |
+
expect = '_Z{}{}if'.format(len(text), text)
|
| 35 |
+
self.assertEqual(name, expect)
|
| 36 |
+
# ensure result chars are in the right charset
|
| 37 |
+
self.assertRegex(name, r'^_Z[a-zA-Z0-9_\$]+$')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == '__main__':
|
| 41 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_moved_modules.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for moved modules and their redirection from old path
|
| 2 |
+
"""
|
| 3 |
+
from numba.tests.support import TestCase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestMovedModule(TestCase):
|
| 7 |
+
"""Testing moved modules in Q1 2020 but were decided to kept as public API
|
| 8 |
+
"""
|
| 9 |
+
def tests_numba_types(self):
|
| 10 |
+
import numba.types
|
| 11 |
+
import numba.core.types as types
|
| 12 |
+
# The old module IS NOT the new module
|
| 13 |
+
self.assertIsNot(numba.types, types)
|
| 14 |
+
# Attribute access are there
|
| 15 |
+
self.assertIs(numba.types.intp, types.intp)
|
| 16 |
+
self.assertIs(numba.types.float64, types.float64)
|
| 17 |
+
self.assertIs(numba.types.Array, types.Array)
|
| 18 |
+
# Submodule access through old import path is possible
|
| 19 |
+
import numba.types.misc
|
| 20 |
+
self.assertIs(types.misc, numba.types.misc)
|
| 21 |
+
self.assertIs(types.misc.Optional, numba.types.misc.Optional)
|
| 22 |
+
# Import time code could be executed twice and causes the following to
|
| 23 |
+
# fail.
|
| 24 |
+
self.assertIs(types.StringLiteral, numba.types.misc.StringLiteral)
|
| 25 |
+
# Check numba.types.container
|
| 26 |
+
from numba.types import containers
|
| 27 |
+
self.assertIs(types.containers, containers)
|
| 28 |
+
self.assertIs(types.containers.Sequence, containers.Sequence)
|
| 29 |
+
from numba.types.containers import Sequence
|
| 30 |
+
self.assertIs(Sequence, containers.Sequence)
|
lib/python3.10/site-packages/numba/tests/test_multi3.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from numba import njit
|
| 6 |
+
from numba.core import types
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
class TestMulti3(unittest.TestCase):
|
| 10 |
+
"""
|
| 11 |
+
This test is only relevant for 32-bit architectures.
|
| 12 |
+
|
| 13 |
+
Test __multi3 implementation in _helperlib.c.
|
| 14 |
+
The symbol defines a i128 multiplication.
|
| 15 |
+
It is necessary for working around an issue in LLVM (see issue #969).
|
| 16 |
+
The symbol does not exist in 32-bit platform, and should not be used by
|
| 17 |
+
LLVM. However, optimization passes will create i65 multiplication that
|
| 18 |
+
is then lowered to __multi3.
|
| 19 |
+
"""
|
| 20 |
+
def test_multi3(self):
|
| 21 |
+
@njit("(int64,)")
|
| 22 |
+
def func(x):
|
| 23 |
+
res = 0
|
| 24 |
+
for i in range(x):
|
| 25 |
+
res += i
|
| 26 |
+
return res
|
| 27 |
+
|
| 28 |
+
x_cases = [-1, 0, 1, 3, 4, 8,
|
| 29 |
+
0xffffffff - 1, 0xffffffff, 0xffffffff + 1,
|
| 30 |
+
0x123456789abcdef, -0x123456789abcdef]
|
| 31 |
+
for _ in range(500):
|
| 32 |
+
x_cases.append(random.randint(0, 0xffffffff))
|
| 33 |
+
|
| 34 |
+
def expected(x):
|
| 35 |
+
if x <= 0: return 0
|
| 36 |
+
return ((x * (x - 1)) // 2) & (2**64 - 1)
|
| 37 |
+
|
| 38 |
+
for x in x_cases:
|
| 39 |
+
self.assertEqual(expected(x), func(x))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == '__main__':
|
| 43 |
+
unittest.main()
|
lib/python3.10/site-packages/numba/tests/test_nan.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from numba import jit
|
| 3 |
+
from numba.core import types
|
| 4 |
+
|
| 5 |
+
enable_pyobj_flags = {'forceobj': True}
|
| 6 |
+
no_pyobj_flags = {'nopython': True}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def isnan(x):
|
| 10 |
+
return x != x
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def isequal(x):
|
| 14 |
+
return x == x
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TestNaN(unittest.TestCase):
|
| 18 |
+
|
| 19 |
+
def test_nans(self, flags=enable_pyobj_flags):
|
| 20 |
+
pyfunc = isnan
|
| 21 |
+
cfunc = jit((types.float64,), **flags)(pyfunc)
|
| 22 |
+
|
| 23 |
+
self.assertTrue(cfunc(float('nan')))
|
| 24 |
+
self.assertFalse(cfunc(1.0))
|
| 25 |
+
|
| 26 |
+
pyfunc = isequal
|
| 27 |
+
cfunc = jit((types.float64,), **flags)(pyfunc)
|
| 28 |
+
|
| 29 |
+
self.assertFalse(cfunc(float('nan')))
|
| 30 |
+
self.assertTrue(cfunc(1.0))
|
| 31 |
+
|
| 32 |
+
def test_nans_npm(self):
|
| 33 |
+
self.test_nans(flags=no_pyobj_flags)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if __name__ == '__main__':
|
| 37 |
+
unittest.main()
|