numba-cuda 0.21.1__cp313-cp313-win_amd64.whl → 0.24.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. numba_cuda/VERSION +1 -1
  2. numba_cuda/numba/cuda/__init__.py +4 -1
  3. numba_cuda/numba/cuda/_compat.py +47 -0
  4. numba_cuda/numba/cuda/api.py +4 -1
  5. numba_cuda/numba/cuda/cext/_dispatcher.cp313-win_amd64.pyd +0 -0
  6. numba_cuda/numba/cuda/cext/_dispatcher.cpp +8 -40
  7. numba_cuda/numba/cuda/cext/_hashtable.cpp +5 -0
  8. numba_cuda/numba/cuda/cext/_helperlib.cp313-win_amd64.pyd +0 -0
  9. numba_cuda/numba/cuda/cext/_pymodule.h +1 -1
  10. numba_cuda/numba/cuda/cext/_typeconv.cp313-win_amd64.pyd +0 -0
  11. numba_cuda/numba/cuda/cext/_typeof.cpp +56 -119
  12. numba_cuda/numba/cuda/cext/mviewbuf.c +7 -1
  13. numba_cuda/numba/cuda/cext/mviewbuf.cp313-win_amd64.pyd +0 -0
  14. numba_cuda/numba/cuda/cloudpickle/cloudpickle.py +4 -5
  15. numba_cuda/numba/cuda/codegen.py +46 -12
  16. numba_cuda/numba/cuda/compiler.py +15 -9
  17. numba_cuda/numba/cuda/core/analysis.py +29 -21
  18. numba_cuda/numba/cuda/core/annotations/pretty_annotate.py +1 -1
  19. numba_cuda/numba/cuda/core/annotations/type_annotations.py +4 -4
  20. numba_cuda/numba/cuda/core/base.py +12 -11
  21. numba_cuda/numba/cuda/core/bytecode.py +21 -13
  22. numba_cuda/numba/cuda/core/byteflow.py +336 -90
  23. numba_cuda/numba/cuda/core/compiler.py +3 -4
  24. numba_cuda/numba/cuda/core/compiler_machinery.py +3 -3
  25. numba_cuda/numba/cuda/core/config.py +5 -7
  26. numba_cuda/numba/cuda/core/consts.py +1 -1
  27. numba_cuda/numba/cuda/core/controlflow.py +17 -9
  28. numba_cuda/numba/cuda/core/cuda_errors.py +917 -0
  29. numba_cuda/numba/cuda/core/errors.py +4 -912
  30. numba_cuda/numba/cuda/core/inline_closurecall.py +82 -67
  31. numba_cuda/numba/cuda/core/interpreter.py +334 -160
  32. numba_cuda/numba/cuda/core/ir.py +191 -119
  33. numba_cuda/numba/cuda/core/ir_utils.py +149 -128
  34. numba_cuda/numba/cuda/core/postproc.py +8 -8
  35. numba_cuda/numba/cuda/core/pythonapi.py +3 -0
  36. numba_cuda/numba/cuda/core/rewrites/ir_print.py +6 -3
  37. numba_cuda/numba/cuda/core/rewrites/static_binop.py +1 -1
  38. numba_cuda/numba/cuda/core/rewrites/static_getitem.py +5 -5
  39. numba_cuda/numba/cuda/core/rewrites/static_raise.py +3 -3
  40. numba_cuda/numba/cuda/core/ssa.py +5 -5
  41. numba_cuda/numba/cuda/core/transforms.py +29 -16
  42. numba_cuda/numba/cuda/core/typed_passes.py +10 -10
  43. numba_cuda/numba/cuda/core/typeinfer.py +42 -27
  44. numba_cuda/numba/cuda/core/untyped_passes.py +82 -65
  45. numba_cuda/numba/cuda/cpython/unicode.py +2 -2
  46. numba_cuda/numba/cuda/cpython/unicode_support.py +1 -3
  47. numba_cuda/numba/cuda/cudadecl.py +0 -13
  48. numba_cuda/numba/cuda/cudadrv/devicearray.py +10 -9
  49. numba_cuda/numba/cuda/cudadrv/driver.py +142 -519
  50. numba_cuda/numba/cuda/cudadrv/dummyarray.py +4 -0
  51. numba_cuda/numba/cuda/cudadrv/nvrtc.py +87 -32
  52. numba_cuda/numba/cuda/cudaimpl.py +0 -12
  53. numba_cuda/numba/cuda/debuginfo.py +25 -0
  54. numba_cuda/numba/cuda/descriptor.py +1 -1
  55. numba_cuda/numba/cuda/device_init.py +4 -7
  56. numba_cuda/numba/cuda/deviceufunc.py +3 -6
  57. numba_cuda/numba/cuda/dispatcher.py +39 -49
  58. numba_cuda/numba/cuda/intrinsics.py +150 -1
  59. numba_cuda/numba/cuda/libdeviceimpl.py +1 -2
  60. numba_cuda/numba/cuda/lowering.py +36 -29
  61. numba_cuda/numba/cuda/memory_management/nrt.py +10 -14
  62. numba_cuda/numba/cuda/np/arrayobj.py +61 -9
  63. numba_cuda/numba/cuda/np/numpy_support.py +32 -9
  64. numba_cuda/numba/cuda/np/polynomial/polynomial_functions.py +4 -3
  65. numba_cuda/numba/cuda/printimpl.py +20 -0
  66. numba_cuda/numba/cuda/serialize.py +10 -0
  67. numba_cuda/numba/cuda/stubs.py +0 -11
  68. numba_cuda/numba/cuda/testing.py +4 -8
  69. numba_cuda/numba/cuda/tests/benchmarks/test_kernel_launch.py +21 -4
  70. numba_cuda/numba/cuda/tests/cudadrv/test_context_stack.py +1 -2
  71. numba_cuda/numba/cuda/tests/cudadrv/test_cuda_driver.py +195 -51
  72. numba_cuda/numba/cuda/tests/cudadrv/test_cuda_memory.py +6 -2
  73. numba_cuda/numba/cuda/tests/cudadrv/test_emm_plugins.py +3 -1
  74. numba_cuda/numba/cuda/tests/cudadrv/test_events.py +1 -1
  75. numba_cuda/numba/cuda/tests/cudadrv/test_linker.py +6 -7
  76. numba_cuda/numba/cuda/tests/cudadrv/test_module_callbacks.py +11 -12
  77. numba_cuda/numba/cuda/tests/cudadrv/test_nvjitlink.py +53 -23
  78. numba_cuda/numba/cuda/tests/cudapy/test_analysis.py +61 -9
  79. numba_cuda/numba/cuda/tests/cudapy/test_atomics.py +6 -0
  80. numba_cuda/numba/cuda/tests/cudapy/test_caching.py +47 -0
  81. numba_cuda/numba/cuda/tests/cudapy/test_compiler.py +22 -1
  82. numba_cuda/numba/cuda/tests/cudapy/test_complex.py +13 -0
  83. numba_cuda/numba/cuda/tests/cudapy/test_copy_propagate.py +1 -1
  84. numba_cuda/numba/cuda/tests/cudapy/test_debug.py +1 -1
  85. numba_cuda/numba/cuda/tests/cudapy/test_debuginfo.py +94 -0
  86. numba_cuda/numba/cuda/tests/cudapy/test_device_array_capture.py +243 -0
  87. numba_cuda/numba/cuda/tests/cudapy/test_dispatcher.py +3 -3
  88. numba_cuda/numba/cuda/tests/cudapy/test_extending.py +1 -1
  89. numba_cuda/numba/cuda/tests/cudapy/test_numba_interop.py +35 -0
  90. numba_cuda/numba/cuda/tests/cudapy/test_print.py +51 -0
  91. numba_cuda/numba/cuda/tests/cudapy/test_vector_type.py +37 -35
  92. numba_cuda/numba/cuda/tests/cudapy/test_warp_ops.py +117 -1
  93. numba_cuda/numba/cuda/tests/doc_examples/test_globals.py +111 -0
  94. numba_cuda/numba/cuda/tests/nocuda/test_dummyarray.py +61 -0
  95. numba_cuda/numba/cuda/tests/nrt/test_nrt.py +31 -0
  96. numba_cuda/numba/cuda/tests/support.py +11 -0
  97. numba_cuda/numba/cuda/types/cuda_functions.py +1 -1
  98. numba_cuda/numba/cuda/typing/asnumbatype.py +37 -2
  99. numba_cuda/numba/cuda/typing/context.py +3 -1
  100. numba_cuda/numba/cuda/typing/typeof.py +51 -2
  101. {numba_cuda-0.21.1.dist-info → numba_cuda-0.24.0.dist-info}/METADATA +4 -13
  102. {numba_cuda-0.21.1.dist-info → numba_cuda-0.24.0.dist-info}/RECORD +106 -105
  103. numba_cuda/numba/cuda/cext/_devicearray.cp313-win_amd64.pyd +0 -0
  104. numba_cuda/numba/cuda/cext/_devicearray.cpp +0 -159
  105. numba_cuda/numba/cuda/cext/_devicearray.h +0 -29
  106. numba_cuda/numba/cuda/intrinsic_wrapper.py +0 -41
  107. {numba_cuda-0.21.1.dist-info → numba_cuda-0.24.0.dist-info}/WHEEL +0 -0
  108. {numba_cuda-0.21.1.dist-info → numba_cuda-0.24.0.dist-info}/licenses/LICENSE +0 -0
  109. {numba_cuda-0.21.1.dist-info → numba_cuda-0.24.0.dist-info}/licenses/LICENSE.numba +0 -0
  110. {numba_cuda-0.21.1.dist-info → numba_cuda-0.24.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,917 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: BSD-2-Clause
3
+
4
+ """
5
+ Numba-specific errors and warnings.
6
+ """
7
+
8
+ import abc
9
+ import contextlib
10
+ import os
11
+ import warnings
12
+ import numba.cuda.core.config
13
+ import numpy as np
14
+ from collections import defaultdict
15
+ from functools import wraps
16
+ from abc import abstractmethod
17
+
18
+ import numba_cuda
19
+
20
+ # Filled at the end
21
+ __all__ = []
22
+
23
+
24
+ def _is_numba_core_config_loaded():
25
+ """
26
+ To detect if numba.core.config has been initialized due to circular imports.
27
+ """
28
+ try:
29
+ numba.cuda.core.config
30
+ except AttributeError:
31
+ return False
32
+ else:
33
+ return True
34
+
35
+
36
+ class NumbaWarning(Warning):
37
+ """
38
+ Base category for all Numba compiler warnings.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ msg,
44
+ loc=None,
45
+ highlighting=True,
46
+ ):
47
+ self.msg = msg
48
+ self.loc = loc
49
+
50
+ # If a warning is emitted inside validation of env-vars in
51
+ # numba.core.config. Highlighting will not be available.
52
+ if highlighting and _is_numba_core_config_loaded():
53
+ highlight = termcolor().errmsg
54
+ else:
55
+
56
+ def highlight(x):
57
+ return x
58
+
59
+ if loc:
60
+ super(NumbaWarning, self).__init__(
61
+ highlight("%s\n%s\n" % (msg, loc.strformat()))
62
+ )
63
+ else:
64
+ super(NumbaWarning, self).__init__(highlight("%s" % (msg,)))
65
+
66
+
67
+ class NumbaPerformanceWarning(NumbaWarning):
68
+ """
69
+ Warning category for when an operation might not be
70
+ as fast as expected.
71
+ """
72
+
73
+
74
+ class NumbaDeprecationWarning(NumbaWarning, DeprecationWarning):
75
+ """
76
+ Warning category for use of a deprecated feature.
77
+ """
78
+
79
+
80
+ class NumbaPendingDeprecationWarning(NumbaWarning, PendingDeprecationWarning):
81
+ """
82
+ Warning category for use of a feature that is pending deprecation.
83
+ """
84
+
85
+
86
+ class NumbaParallelSafetyWarning(NumbaWarning):
87
+ """
88
+ Warning category for when an operation in a prange
89
+ might not have parallel semantics.
90
+ """
91
+
92
+
93
+ class NumbaTypeSafetyWarning(NumbaWarning):
94
+ """
95
+ Warning category for unsafe casting operations.
96
+ """
97
+
98
+
99
+ class NumbaExperimentalFeatureWarning(NumbaWarning):
100
+ """
101
+ Warning category for using an experimental feature.
102
+ """
103
+
104
+
105
+ class NumbaInvalidConfigWarning(NumbaWarning):
106
+ """
107
+ Warning category for using an invalid configuration.
108
+ """
109
+
110
+
111
+ class NumbaPedanticWarning(NumbaWarning):
112
+ """
113
+ Warning category for reporting pedantic messages.
114
+ """
115
+
116
+ def __init__(self, msg, **kwargs):
117
+ super().__init__(f"{msg}\n{pedantic_warning_info}")
118
+
119
+
120
+ class NumbaIRAssumptionWarning(NumbaPedanticWarning):
121
+ """
122
+ Warning category for reporting an IR assumption violation.
123
+ """
124
+
125
+
126
+ class NumbaDebugInfoWarning(NumbaWarning):
127
+ """
128
+ Warning category for an issue with the emission of debug information.
129
+ """
130
+
131
+
132
+ class NumbaSystemWarning(NumbaWarning):
133
+ """
134
+ Warning category for an issue with the system configuration.
135
+ """
136
+
137
+
138
+ # These are needed in the color formatting of errors setup
139
+
140
+
141
+ class _ColorScheme(metaclass=abc.ABCMeta):
142
+ @abstractmethod
143
+ def code(self, msg):
144
+ pass
145
+
146
+ @abstractmethod
147
+ def errmsg(self, msg):
148
+ pass
149
+
150
+ @abstractmethod
151
+ def filename(self, msg):
152
+ pass
153
+
154
+ @abstractmethod
155
+ def indicate(self, msg):
156
+ pass
157
+
158
+ @abstractmethod
159
+ def highlight(self, msg):
160
+ pass
161
+
162
+ @abstractmethod
163
+ def reset(self, msg):
164
+ pass
165
+
166
+
167
+ class _DummyColorScheme(_ColorScheme):
168
+ def __init__(self, theme=None):
169
+ pass
170
+
171
+ def code(self, msg):
172
+ pass
173
+
174
+ def errmsg(self, msg):
175
+ pass
176
+
177
+ def filename(self, msg):
178
+ pass
179
+
180
+ def indicate(self, msg):
181
+ pass
182
+
183
+ def highlight(self, msg):
184
+ pass
185
+
186
+ def reset(self, msg):
187
+ pass
188
+
189
+
190
+ # holds reference to the instance of the terminal color scheme in use
191
+ _termcolor_inst = None
192
+
193
+ try:
194
+ import colorama
195
+
196
+ # If the colorama version is < 0.3.9 it can break stdout/stderr in some
197
+ # situations, as a result if this condition is met colorama is disabled and
198
+ # the user is warned. Note that early versions did not have a __version__.
199
+ colorama_version = getattr(colorama, "__version__", "0.0.0")
200
+
201
+ if tuple([int(x) for x in colorama_version.split(".")]) < (0, 3, 9):
202
+ msg = (
203
+ "Insufficiently recent colorama version found. "
204
+ "Numba requires colorama >= 0.3.9"
205
+ )
206
+ # warn the user
207
+ warnings.warn(msg)
208
+ # trip the exception to disable color errors
209
+ raise ImportError
210
+
211
+ # If Numba is running in testsuite mode then do not use error message
212
+ # coloring so CI system output is consistently readable without having
213
+ # to read between shell escape characters.
214
+ if os.environ.get("NUMBA_DISABLE_ERROR_MESSAGE_HIGHLIGHTING", None):
215
+ raise ImportError # just to trigger the exception handler below
216
+
217
+ except ImportError:
218
+
219
+ class NOPColorScheme(_DummyColorScheme):
220
+ def __init__(self, theme=None):
221
+ if theme is not None:
222
+ raise ValueError("specifying a theme has no effect")
223
+ _DummyColorScheme.__init__(self, theme=theme)
224
+
225
+ def code(self, msg):
226
+ return msg
227
+
228
+ def errmsg(self, msg):
229
+ return msg
230
+
231
+ def filename(self, msg):
232
+ return msg
233
+
234
+ def indicate(self, msg):
235
+ return msg
236
+
237
+ def highlight(self, msg):
238
+ return msg
239
+
240
+ def reset(self, msg):
241
+ return msg
242
+
243
+ def termcolor():
244
+ global _termcolor_inst
245
+ if _termcolor_inst is None:
246
+ _termcolor_inst = NOPColorScheme()
247
+ return _termcolor_inst
248
+
249
+ else:
250
+ from colorama import init, reinit, deinit, Fore, Style
251
+
252
+ class ColorShell(object):
253
+ _has_initialized = False
254
+
255
+ def __init__(self):
256
+ init()
257
+ self._has_initialized = True
258
+
259
+ def __enter__(self):
260
+ if self._has_initialized:
261
+ reinit()
262
+
263
+ def __exit__(self, *exc_detail):
264
+ Style.RESET_ALL
265
+ deinit()
266
+
267
+ class reset_terminal(object):
268
+ def __init__(self):
269
+ self._buf = bytearray(b"")
270
+
271
+ def __enter__(self):
272
+ return self._buf
273
+
274
+ def __exit__(self, *exc_detail):
275
+ self._buf += bytearray(Style.RESET_ALL.encode("utf-8"))
276
+
277
+ # define some default themes, if more are added, update the envvars docs!
278
+ themes = {}
279
+
280
+ # No color added, just bold weighting
281
+ themes["no_color"] = {
282
+ "code": None,
283
+ "errmsg": None,
284
+ "filename": None,
285
+ "indicate": None,
286
+ "highlight": None,
287
+ "reset": None,
288
+ }
289
+
290
+ # suitable for terminals with a dark background
291
+ themes["dark_bg"] = {
292
+ "code": Fore.BLUE,
293
+ "errmsg": Fore.YELLOW,
294
+ "filename": Fore.WHITE,
295
+ "indicate": Fore.GREEN,
296
+ "highlight": Fore.RED,
297
+ "reset": Style.RESET_ALL,
298
+ }
299
+
300
+ # suitable for terminals with a light background
301
+ themes["light_bg"] = {
302
+ "code": Fore.BLUE,
303
+ "errmsg": Fore.BLACK,
304
+ "filename": Fore.MAGENTA,
305
+ "indicate": Fore.BLACK,
306
+ "highlight": Fore.RED,
307
+ "reset": Style.RESET_ALL,
308
+ }
309
+
310
+ # suitable for terminals with a blue background
311
+ themes["blue_bg"] = {
312
+ "code": Fore.WHITE,
313
+ "errmsg": Fore.YELLOW,
314
+ "filename": Fore.MAGENTA,
315
+ "indicate": Fore.CYAN,
316
+ "highlight": Fore.RED,
317
+ "reset": Style.RESET_ALL,
318
+ }
319
+
320
+ # suitable for use in jupyter notebooks
321
+ themes["jupyter_nb"] = {
322
+ "code": Fore.BLACK,
323
+ "errmsg": Fore.BLACK,
324
+ "filename": Fore.GREEN,
325
+ "indicate": Fore.CYAN,
326
+ "highlight": Fore.RED,
327
+ "reset": Style.RESET_ALL,
328
+ }
329
+
330
+ default_theme = themes["no_color"]
331
+
332
+ class HighlightColorScheme(_DummyColorScheme):
333
+ def __init__(self, theme=default_theme):
334
+ self._code = theme["code"]
335
+ self._errmsg = theme["errmsg"]
336
+ self._filename = theme["filename"]
337
+ self._indicate = theme["indicate"]
338
+ self._highlight = theme["highlight"]
339
+ self._reset = theme["reset"]
340
+ _DummyColorScheme.__init__(self, theme=theme)
341
+
342
+ def _markup(self, msg, color=None, style=Style.BRIGHT):
343
+ features = ""
344
+ if color:
345
+ features += color
346
+ if style:
347
+ features += style
348
+ with ColorShell():
349
+ with reset_terminal() as mu:
350
+ mu += features.encode("utf-8")
351
+ mu += (msg).encode("utf-8")
352
+ return mu.decode("utf-8")
353
+
354
+ def code(self, msg):
355
+ return self._markup(msg, self._code)
356
+
357
+ def errmsg(self, msg):
358
+ return self._markup(msg, self._errmsg)
359
+
360
+ def filename(self, msg):
361
+ return self._markup(msg, self._filename)
362
+
363
+ def indicate(self, msg):
364
+ return self._markup(msg, self._indicate)
365
+
366
+ def highlight(self, msg):
367
+ return self._markup(msg, self._highlight)
368
+
369
+ def reset(self, msg):
370
+ return self._markup(msg, self._reset)
371
+
372
+ def termcolor():
373
+ global _termcolor_inst
374
+ if _termcolor_inst is None:
375
+ scheme = themes[numba.cuda.core.config.COLOR_SCHEME]
376
+ _termcolor_inst = HighlightColorScheme(scheme)
377
+ return _termcolor_inst
378
+
379
+
380
+ pedantic_warning_info = """
381
+ This warning came from an internal pedantic check. Please report the warning
382
+ message and traceback, along with a minimal reproducer at:
383
+ https://github.com/numba/numba/issues/new?template=bug_report.md
384
+ """
385
+
386
+ feedback_details = """
387
+ Please report the error message and traceback, along with a minimal reproducer
388
+ at: https://github.com/numba/numba/issues/new?template=bug_report.md
389
+
390
+ If more help is needed please feel free to speak to the Numba core developers
391
+ directly at: https://gitter.im/numba/numba
392
+
393
+ Thanks in advance for your help in improving Numba!
394
+ """
395
+
396
+ unsupported_error_info = """
397
+ Unsupported functionality was found in the code Numba was trying to compile.
398
+
399
+ If this functionality is important to you please file a feature request at:
400
+ https://github.com/numba/numba/issues/new?template=feature_request.md
401
+ """
402
+
403
+ interpreter_error_info = """
404
+ Unsupported Python functionality was found in the code Numba was trying to
405
+ compile. This error could be due to invalid code, does the code work
406
+ without Numba? (To temporarily disable Numba JIT, set the `NUMBA_DISABLE_JIT`
407
+ environment variable to non-zero, and then rerun the code).
408
+
409
+ If the code is valid and the unsupported functionality is important to you
410
+ please file a feature request at:
411
+ https://github.com/numba/numba/issues/new?template=feature_request.md
412
+
413
+ To see Python/NumPy features supported by the latest release of Numba visit:
414
+ https://numba.readthedocs.io/en/stable/reference/pysupported.html
415
+ and
416
+ https://numba.readthedocs.io/en/stable/reference/numpysupported.html
417
+ """
418
+
419
+ constant_inference_info = (
420
+ """
421
+ Numba could not make a constant out of something that it decided should be
422
+ a constant. This could well be a current limitation in Numba's internals,
423
+ however please first check that your code is valid for compilation,
424
+ particularly with respect to string interpolation (not supported!) and
425
+ the requirement of compile time constants as arguments to exceptions:
426
+ https://numba.readthedocs.io/en/stable/reference/pysupported.html?highlight=exceptions#constructs
427
+
428
+ If the code is valid and the unsupported functionality is important to you
429
+ please file a feature request at:
430
+ https://github.com/numba/numba/issues/new?template=feature_request.md
431
+
432
+ If you think your code should work with Numba. %s
433
+ """
434
+ % feedback_details
435
+ )
436
+
437
+ typing_error_info = """
438
+ This is not usually a problem with Numba itself but instead often caused by
439
+ the use of unsupported features or an issue in resolving types.
440
+
441
+ To see Python/NumPy features supported by the latest release of Numba visit:
442
+ https://numba.readthedocs.io/en/stable/reference/pysupported.html
443
+ and
444
+ https://numba.readthedocs.io/en/stable/reference/numpysupported.html
445
+
446
+ For more information about typing errors and how to debug them visit:
447
+ https://numba.readthedocs.io/en/stable/user/troubleshoot.html#my-code-doesn-t-compile
448
+
449
+ If you think your code should work with Numba, please report the error message
450
+ and traceback, along with a minimal reproducer at:
451
+ https://github.com/numba/numba/issues/new?template=bug_report.md
452
+ """
453
+
454
+ reportable_issue_info = """
455
+ -------------------------------------------------------------------------------
456
+ This should not have happened, a problem has occurred in Numba's internals.
457
+ You are currently using Numba version %s.
458
+ %s
459
+ """ % (numba_cuda.__version__, feedback_details)
460
+
461
+ error_extras = dict()
462
+ error_extras["unsupported_error"] = unsupported_error_info
463
+ error_extras["typing"] = typing_error_info
464
+ error_extras["reportable"] = reportable_issue_info
465
+ error_extras["interpreter"] = interpreter_error_info
466
+ error_extras["constant_inference"] = constant_inference_info
467
+
468
+
469
+ def deprecated(arg):
470
+ """Define a deprecation decorator.
471
+ An optional string should refer to the new API to be used instead.
472
+
473
+ Example:
474
+ @deprecated
475
+ def old_func(): ...
476
+
477
+ @deprecated('new_func')
478
+ def old_func(): ..."""
479
+
480
+ subst = arg if isinstance(arg, str) else None
481
+
482
+ def decorator(func):
483
+ def wrapper(*args, **kwargs):
484
+ msg = 'Call to deprecated function "{}".'
485
+ if subst:
486
+ msg += '\n Use "{}" instead.'
487
+ warnings.warn(
488
+ msg.format(func.__name__, subst),
489
+ category=DeprecationWarning,
490
+ stacklevel=2,
491
+ )
492
+ return func(*args, **kwargs)
493
+
494
+ return wraps(func)(wrapper)
495
+
496
+ if not subst:
497
+ return decorator(arg)
498
+ else:
499
+ return decorator
500
+
501
+
502
+ class WarningsFixer(object):
503
+ """
504
+ An object "fixing" warnings of a given category caught during
505
+ certain phases. The warnings can have their filename and lineno fixed,
506
+ and they are deduplicated as well.
507
+
508
+ When used as a context manager, any warnings caught by `.catch_warnings()`
509
+ will be flushed at the exit of the context manager.
510
+ """
511
+
512
+ def __init__(self, category):
513
+ self._category = category
514
+ # {(filename, lineno, category) -> messages}
515
+ self._warnings = defaultdict(set)
516
+
517
+ @contextlib.contextmanager
518
+ def catch_warnings(self, filename=None, lineno=None):
519
+ """
520
+ Store warnings and optionally fix their filename and lineno.
521
+ """
522
+ with warnings.catch_warnings(record=True) as wlist:
523
+ warnings.simplefilter("always", self._category)
524
+ yield
525
+
526
+ for w in wlist:
527
+ msg = str(w.message)
528
+ if issubclass(w.category, self._category):
529
+ # Store warnings of this category for deduplication
530
+ filename = filename or w.filename
531
+ lineno = lineno or w.lineno
532
+ self._warnings[filename, lineno, w.category].add(msg)
533
+ else:
534
+ # Simply emit other warnings again
535
+ warnings.warn_explicit(msg, w.category, w.filename, w.lineno)
536
+
537
+ def flush(self):
538
+ """
539
+ Emit all stored warnings.
540
+ """
541
+
542
+ def key(arg):
543
+ # It is possible through codegen to create entirely identical
544
+ # warnings, this leads to comparing types when sorting which breaks
545
+ # on Python 3. Key as str() and if the worse happens then `id`
546
+ # creates some uniqueness
547
+ return str(arg) + str(id(arg))
548
+
549
+ for (filename, lineno, category), messages in sorted(
550
+ self._warnings.items(), key=key
551
+ ):
552
+ for msg in sorted(messages):
553
+ warnings.warn_explicit(msg, category, filename, lineno)
554
+ self._warnings.clear()
555
+
556
+ def __enter__(self):
557
+ return
558
+
559
+ def __exit__(self, exc_type, exc_value, traceback):
560
+ self.flush()
561
+
562
+
563
+ class NumbaError(Exception):
564
+ def __init__(self, msg, loc=None, highlighting=True):
565
+ self.msg = msg
566
+ self.loc = loc
567
+ if highlighting:
568
+ highlight = termcolor().errmsg
569
+ else:
570
+
571
+ def highlight(x):
572
+ return x
573
+
574
+ if loc:
575
+ new_msg = "%s\n%s\n" % (msg, loc.strformat())
576
+ else:
577
+ new_msg = "%s" % (msg,)
578
+ super(NumbaError, self).__init__(highlight(new_msg))
579
+
580
+ @property
581
+ def contexts(self):
582
+ try:
583
+ return self._contexts
584
+ except AttributeError:
585
+ self._contexts = lst = []
586
+ return lst
587
+
588
+ def add_context(self, msg):
589
+ """
590
+ Add contextual info. The exception message is expanded with the new
591
+ contextual information.
592
+ """
593
+ self.contexts.append(msg)
594
+ f = termcolor().errmsg("{0}\n") + termcolor().filename("During: {1}")
595
+ newmsg = f.format(self, msg)
596
+ self.args = (newmsg,)
597
+ return self
598
+
599
+ def patch_message(self, new_message):
600
+ """
601
+ Change the error message to the given new message.
602
+ """
603
+ self.args = (new_message,) + self.args[1:]
604
+
605
+
606
+ class UnsupportedError(NumbaError):
607
+ """
608
+ Numba does not have an implementation for this functionality.
609
+ """
610
+
611
+
612
+ class UnsupportedBytecodeError(Exception):
613
+ """Unsupported bytecode is non-recoverable"""
614
+
615
+ def __init__(self, msg, loc=None):
616
+ super().__init__(f"{msg}. Raised from {loc}")
617
+
618
+
619
+ class UnsupportedRewriteError(UnsupportedError):
620
+ """UnsupportedError from rewrite passes"""
621
+
622
+ pass
623
+
624
+
625
+ class IRError(NumbaError):
626
+ """
627
+ An error occurred during Numba IR generation.
628
+ """
629
+
630
+ pass
631
+
632
+
633
+ class RedefinedError(IRError):
634
+ """
635
+ An error occurred during interpretation of IR due to variable redefinition.
636
+ """
637
+
638
+ pass
639
+
640
+
641
+ class NotDefinedError(IRError):
642
+ """
643
+ An undefined variable is encountered during interpretation of IR.
644
+ """
645
+
646
+ def __init__(self, name, loc=None):
647
+ self.name = name
648
+ msg = (
649
+ "The compiler failed to analyze the bytecode. "
650
+ "Variable '%s' is not defined." % name
651
+ )
652
+ super(NotDefinedError, self).__init__(msg, loc=loc)
653
+
654
+
655
+ class VerificationError(IRError):
656
+ """
657
+ An error occurred during IR verification. Once Numba's internal
658
+ representation (IR) is constructed it is then verified to ensure that
659
+ terminators are both present and in the correct places within the IR. If
660
+ it is the case that this condition is not met, a VerificationError is
661
+ raised.
662
+ """
663
+
664
+ pass
665
+
666
+
667
+ class DeprecationError(NumbaError):
668
+ """
669
+ Functionality is deprecated.
670
+ """
671
+
672
+ pass
673
+
674
+
675
+ class LoweringError(NumbaError):
676
+ """
677
+ An error occurred during lowering.
678
+ """
679
+
680
+ def __init__(self, msg, loc=None):
681
+ super(LoweringError, self).__init__(msg, loc=loc)
682
+
683
+
684
+ class UnsupportedParforsError(NumbaError):
685
+ """
686
+ An error occurred because parfors is not supported on the platform.
687
+ """
688
+
689
+ pass
690
+
691
+
692
+ class ForbiddenConstruct(LoweringError):
693
+ """
694
+ A forbidden Python construct was encountered (e.g. use of locals()).
695
+ """
696
+
697
+ pass
698
+
699
+
700
+ class TypingError(NumbaError):
701
+ """
702
+ A type inference failure.
703
+ """
704
+
705
+ pass
706
+
707
+
708
+ class UntypedAttributeError(TypingError):
709
+ def __init__(self, value, attr, loc=None):
710
+ module = getattr(value, "pymod", None)
711
+ if module is not None and module == np:
712
+ # unsupported numpy feature.
713
+ msg = (
714
+ "Use of unsupported NumPy function 'numpy.%s' "
715
+ "or unsupported use of the function."
716
+ ) % attr
717
+ else:
718
+ msg = "Unknown attribute '{attr}' of type {type}"
719
+ msg = msg.format(type=value, attr=attr)
720
+ super(UntypedAttributeError, self).__init__(msg, loc=loc)
721
+
722
+
723
+ class ByteCodeSupportError(NumbaError):
724
+ """
725
+ Failure to extract the bytecode of the user's function.
726
+ """
727
+
728
+ def __init__(self, msg, loc=None):
729
+ super(ByteCodeSupportError, self).__init__(msg, loc=loc)
730
+
731
+
732
+ class CompilerError(NumbaError):
733
+ """
734
+ Some high-level error in the compiler.
735
+ """
736
+
737
+ pass
738
+
739
+
740
+ class ConstantInferenceError(NumbaError):
741
+ """
742
+ Failure during constant inference.
743
+ """
744
+
745
+ def __init__(self, value, loc=None):
746
+ super(ConstantInferenceError, self).__init__(value, loc=loc)
747
+
748
+
749
+ class InternalError(NumbaError):
750
+ """
751
+ For wrapping internal error occurred within the compiler
752
+ """
753
+
754
+ def __init__(self, exception):
755
+ super(InternalError, self).__init__(str(exception))
756
+ self.old_exception = exception
757
+
758
+
759
+ class InternalTargetMismatchError(InternalError):
760
+ """For signalling a target mismatch error occurred internally within the
761
+ compiler.
762
+ """
763
+
764
+ def __init__(self, kind, target_hw, hw_clazz):
765
+ msg = (
766
+ f"{kind.title()} being resolved on a target from which it does "
767
+ f"not inherit. Local target is {target_hw}, declared "
768
+ f"target class is {hw_clazz}."
769
+ )
770
+ super().__init__(msg)
771
+
772
+
773
+ class NonexistentTargetError(InternalError):
774
+ """For signalling that a target that does not exist was requested."""
775
+
776
+ pass
777
+
778
+
779
+ class RequireLiteralValue(TypingError):
780
+ """
781
+ For signalling that a function's typing requires a constant value for
782
+ some of its arguments.
783
+ """
784
+
785
+ pass
786
+
787
+
788
+ class ForceLiteralArg(NumbaError):
789
+ """A Pseudo-exception to signal the dispatcher to type an argument literally
790
+
791
+ Attributes
792
+ ----------
793
+ requested_args : frozenset[int]
794
+ requested positions of the arguments.
795
+ """
796
+
797
+ def __init__(self, arg_indices, fold_arguments=None, loc=None):
798
+ """
799
+ Parameters
800
+ ----------
801
+ arg_indices : Sequence[int]
802
+ requested positions of the arguments.
803
+ fold_arguments: callable
804
+ A function ``(tuple, dict) -> tuple`` that binds and flattens
805
+ the ``args`` and ``kwargs``.
806
+ loc : numba.ir.Loc or None
807
+ """
808
+ super(ForceLiteralArg, self).__init__(
809
+ "Pseudo-exception to force literal arguments in the dispatcher",
810
+ loc=loc,
811
+ )
812
+ self.requested_args = frozenset(arg_indices)
813
+ self.fold_arguments = fold_arguments
814
+
815
+ def bind_fold_arguments(self, fold_arguments):
816
+ """Bind the fold_arguments function"""
817
+ # to avoid circular import
818
+ from numba.cuda.core.utils import chain_exception
819
+
820
+ e = ForceLiteralArg(self.requested_args, fold_arguments, loc=self.loc)
821
+ return chain_exception(e, self)
822
+
823
+ def combine(self, other):
824
+ """Returns a new instance by or'ing the requested_args."""
825
+ if not isinstance(other, ForceLiteralArg):
826
+ m = "*other* must be a {} but got a {} instead"
827
+ raise TypeError(m.format(ForceLiteralArg, type(other)))
828
+ return ForceLiteralArg(self.requested_args | other.requested_args)
829
+
830
+ def __or__(self, other):
831
+ """Same as self.combine(other)"""
832
+ return self.combine(other)
833
+
834
+
835
+ class LiteralTypingError(TypingError):
836
+ """
837
+ Failure in typing a Literal type
838
+ """
839
+
840
+ pass
841
+
842
+
843
+ # These Exception classes are just Numba copies of their Python equivalents for
844
+ # use internally in cases where we want e.g. type inference to keep on trying.
845
+ # Exceptions extending from NumbaError are considered "special" by Numba's
846
+ # internals and are treated differently to standard Python exceptions which are
847
+ # permitted to just propagate up the stack.
848
+
849
+
850
+ class NumbaValueError(TypingError):
851
+ pass
852
+
853
+
854
+ class NumbaTypeError(TypingError):
855
+ pass
856
+
857
+
858
+ class NumbaAttributeError(TypingError):
859
+ pass
860
+
861
+
862
+ class NumbaAssertionError(TypingError):
863
+ pass
864
+
865
+
866
+ class NumbaNotImplementedError(TypingError):
867
+ pass
868
+
869
+
870
+ class NumbaKeyError(TypingError):
871
+ pass
872
+
873
+
874
+ class NumbaIndexError(TypingError):
875
+ pass
876
+
877
+
878
+ class NumbaRuntimeError(NumbaError):
879
+ pass
880
+
881
+
882
+ def _format_msg(fmt, args, kwargs):
883
+ return fmt.format(*args, **kwargs)
884
+
885
+
886
+ _numba_path = os.path.dirname(__file__)
887
+ loc_info = {}
888
+
889
+
890
+ @contextlib.contextmanager
891
+ def new_error_context(fmt_, *args, **kwargs):
892
+ """
893
+ A contextmanager that prepend contextual information to any exception
894
+ raised within.
895
+
896
+ The first argument is a message that describes the context. It can be a
897
+ format string. If there are additional arguments, it will be used as
898
+ ``fmt_.format(*args, **kwargs)`` to produce the final message string.
899
+ """
900
+ loc = kwargs.get("loc", None)
901
+ if loc is not None and not loc.filename.startswith(_numba_path):
902
+ loc_info.update(kwargs)
903
+
904
+ try:
905
+ yield
906
+ except NumbaError as e:
907
+ e.add_context(_format_msg(fmt_, args, kwargs))
908
+ raise
909
+
910
+
911
+ __all__ += [
912
+ name
913
+ for (name, value) in globals().items()
914
+ if not name.startswith("_")
915
+ and isinstance(value, type)
916
+ and issubclass(value, (Exception, Warning))
917
+ ]