internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: numba/numba

Issue:
Bad truth value for NaNs
```
>>> def b(x): return bool(x)
... 
>>> b = jit(nopython=True)(b)
>>> 
>>> b(float('nan'))
False
>>> bool(float('nan'))
True
```



Discussion:

Resolving patch:
diff --git a/numba/targets/base.py b/numba/targets/base.py
--- a/numba/targets/base.py
+++ b/numba/targets/base.py
@@ -846,12 +846,11 @@ def is_true(self, builder, typ, val):
         if typ in types.integer_domain:
             return builder.icmp(lc.ICMP_NE, val, Constant.null(val.type))
         elif typ in types.real_domain:
-            return builder.fcmp(lc.FCMP_ONE, val, Constant.real(val.type, 0))
+            return builder.fcmp(lc.FCMP_UNE, val, Constant.real(val.type, 0))
         elif typ in types.complex_domain:
             cmplx = self.make_complex(typ)(self, builder, val)
-            fty = types.float32 if typ == types.complex64 else types.float64
-            real_istrue = self.is_true(builder, fty, cmplx.real)
-            imag_istrue = self.is_true(builder, fty, cmplx.imag)
+            real_istrue = self.is_true(builder, typ.underlying_float, cmplx.real)
+            imag_istrue = self.is_true(builder, typ.underlying_float, cmplx.imag)
             return builder.or_(real_istrue, imag_istrue)
         raise NotImplementedError("is_true", val, typ)
 


Test patch:
diff --git a/numba/tests/test_builtins.py b/numba/tests/test_builtins.py
--- a/numba/tests/test_builtins.py
+++ b/numba/tests/test_builtins.py
@@ -233,6 +233,14 @@ def test_bool(self, flags=enable_pyobj_flags):
         cfunc = cr.entry_point
         for x in [-1, 0, 1]:
             self.assertPreciseEqual(cfunc(x), pyfunc(x))
+        cr = compile_isolated(pyfunc, (types.float64,), flags=flags)
+        cfunc = cr.entry_point
+        for x in [0.0, -0.0, 1.5, float('inf'), float('nan')]:
+            self.assertPreciseEqual(cfunc(x), pyfunc(x))
+        cr = compile_isolated(pyfunc, (types.complex128,), flags=flags)
+        cfunc = cr.entry_point
+        for x in [complex(0, float('inf')), complex(0, float('nan'))]:
+            self.assertPreciseEqual(cfunc(x), pyfunc(x))
 
     def test_bool_npm(self):
         self.test_bool(flags=no_pyobj_flags)
Repository: numba/numba

Issue:
Clarify nopython vs object mode in supported features documentation
The supported Python and NumPy features pages should make it clear whether something is supported in nopython mode.  This is probably easiest by listing things that are not supported in all modes, and then listing things that are supported in nopython mode.



Discussion:

Resolving patch:
diff --git a/numba/cuda/api.py b/numba/cuda/api.py
--- a/numba/cuda/api.py
+++ b/numba/cuda/api.py
@@ -212,8 +212,8 @@ def event(timing=True):
 
 def select_device(device_id):
     """Creates a new CUDA context with the selected device.
-    The context is associated with the current thread. Numba
-    currently allows only one context per thread.
+    The context is associated with the current thread.
+    Numba currently allows only one context per thread.
 
     Returns a device instance
 


Test patch:
Repository: numba/numba

Issue:
Incorrect code on some tuple unpacking
```
>>> from numba import jit
>>> def f(x, y):
...     if x:
...        x, y = y, x
...     return x, y
... 
>>> ff = jit(nopython=True)(f)
>>> ff(1, 2)
(2, 2)
```



Discussion:

Resolving patch:
diff --git a/numba/interpreter.py b/numba/interpreter.py
--- a/numba/interpreter.py
+++ b/numba/interpreter.py
@@ -24,6 +24,8 @@ class Assigner(object):
     def __init__(self):
         # { destination variable name -> source Var object }
         self.dest_to_src = {}
+        # Basically a reverse mapping of dest_to_src:
+        # { source variable name -> all destination names in dest_to_src }
         self.src_invalidate = collections.defaultdict(list)
         self.unused_dests = set()
 
@@ -34,9 +36,9 @@ def assign(self, srcvar, destvar):
         """
         srcname = srcvar.name
         destname = destvar.name
-        if srcname in self.src_invalidate:
-            # Invalidate all previously known simplifications
-            for d in self.src_invalidate.pop(srcname):
+        if destname in self.src_invalidate:
+            # destvar will change, invalidate all previously known simplifications
+            for d in self.src_invalidate.pop(destname):
                 self.dest_to_src.pop(d)
         if srcname in self.dest_to_src:
             srcvar = self.dest_to_src[srcname]


Test patch:
diff --git a/numba/tests/test_unpack_sequence.py b/numba/tests/test_unpack_sequence.py
--- a/numba/tests/test_unpack_sequence.py
+++ b/numba/tests/test_unpack_sequence.py
@@ -73,6 +73,13 @@ def chained_unpack_assign1(x, y):
     return d + e + b + c
 
 
+def conditional_swap(x, y):
+    # Used to produce invalid code (issue #977)
+    if x > 0:
+        x, y = y, x
+    return x, y
+
+
 class TestUnpack(TestCase):
 
     def test_unpack_list(self):
@@ -160,7 +167,20 @@ def test_unpack_range_too_large(self):
     def test_unpack_range_too_large_npm(self):
         self.check_unpack_error(unpack_range_too_large, no_pyobj_flags)
 
+    def check_conditional_swap(self, flags=force_pyobj_flags):
+        cr = compile_isolated(conditional_swap, (types.int32, types.int32),
+                              flags=flags)
+        cfunc = cr.entry_point
+        self.assertPreciseEqual(cfunc(4, 5), (5, 4))
+        self.assertPreciseEqual(cfunc(0, 5), (0, 5))
+
+    def test_conditional_swap(self):
+        self.check_conditional_swap()
+
+    def test_conditional_swap_npm(self):
+        self.check_conditional_swap(no_pyobj_flags)
+
 
 if __name__ == '__main__':
-    unittest.main(buffer=True)
+    unittest.main()
Repository: numba/numba

Issue:
TypeError: No matching definition doesn't give enough useful information
When a matching definition can't be found by the dispatcher, the message received is:

```
TypeError: No matching definition
```

It would probably be helpful if the definition required were printed, and a list of existing defininitions as well.



Discussion:
A big +1 to this.  I was just about to open an issue for this too.

Do you have a small bit of code that replicates the issue handy? It looks like when I opened this issue I was in a bit of a hurry and failed to include a reproducer.

``` python
from numba import *
@jit(boolean(float32[:]))
def demo(x):
    return False
demo(np.arange(100, dtype=float))
```

It would also be nice, if there would be some useful stack trace.

Thanks for the reproducer. 

Just as a note (based on a quick glance at the relevant code), I think the message is coming from `Dispatcher_call` in `numba/_dispatcher.c`. At this point the typecodes of args have been used to find (or fail to find) a matching implementation, so there would be a bit of work necessary to allow a human-readable list of available overloads and the arguments of the inputs to be presented as part of the message.


Resolving patch:
diff --git a/numba/dispatcher.py b/numba/dispatcher.py
--- a/numba/dispatcher.py
+++ b/numba/dispatcher.py
@@ -186,6 +186,13 @@ def _explain_ambiguous(self, *args, **kws):
         sigs = [cr.signature for cr in self._compileinfos.values()]
         resolve_overload(self.typingctx, self.py_func, sigs, args, kws)
 
+    def _explain_matching_error(self, *args, **kws):
+        assert not kws, "kwargs not handled"
+        args = [self.typeof_pyval(a) for a in args]
+        msg = ("No matching definition for argument type(s) %s"
+               % ', '.join(map(str, args)))
+        raise TypeError(msg)
+
     def __repr__(self):
         return "%s(%s)" % (type(self).__name__, self.py_func)
 


Test patch:
diff --git a/numba/tests/test_dispatcher.py b/numba/tests/test_dispatcher.py
--- a/numba/tests/test_dispatcher.py
+++ b/numba/tests/test_dispatcher.py
@@ -147,6 +147,14 @@ def test_signature_mismatch(self):
             jit("(intc,)", forceobj=True)(add)
         self.assertIn(tmpl % 1, str(cm.exception))
 
+    def test_matching_error_message(self):
+        f = jit("(intc,intc)")(add)
+        with self.assertRaises(TypeError) as cm:
+            f(1j, 1j)
+        self.assertEqual(str(cm.exception),
+                         "No matching definition for argument type(s) "
+                         "complex128, complex128")
+
     def test_recompile(self):
         closure = 1
Repository: numba/numba

Issue:
len(tuple) causes failure to compile
len() is listed on the supported features page on builtin, but is causing code to fail to compile.

code: 'shape_size = len(shape)'

from inspect_vars:
            # --- LINE 225 --- 
            #   $0.3 = global(len: <built-in function len>)  :: pyobject
            #   $0.5 = call $0.3(shape, )  :: pyobject
            #   del shape
            #   del $0.3
            #   shape_size = $0.5  :: pyobject
            #   del shape_size
            #   del $0.5

Error output when using nopython=True:

TypingError: Failed at nopython (nopython frontend)
Undeclared len((int64 x 1),)
File "....\quick\quick\funcs.py", line 225



Discussion:
Taking the length of a tuple appears not to be supported. However, it looks like you're trying to find the number of dimensions of an array, for which you can use the `ndim` property.


Resolving patch:
diff --git a/numba/targets/builtins.py b/numba/targets/builtins.py
--- a/numba/targets/builtins.py
+++ b/numba/targets/builtins.py
@@ -1422,3 +1422,19 @@ def array_ravel_impl(context, builder, sig, args):
 
     return flatarr._getvalue()
 
+
+# -----------------------------------------------------------------------------
+
+@builtin
+@implement(types.len_type, types.Kind(types.Tuple))
+def array_len(context, builder, sig, args):
+    tupty, = sig.args
+    retty = sig.return_type
+    return context.get_constant(retty, len(tupty.types))
+
+@builtin
+@implement(types.len_type, types.Kind(types.UniTuple))
+def array_len(context, builder, sig, args):
+    tupty, = sig.args
+    retty = sig.return_type
+    return context.get_constant(retty, tupty.count)
diff --git a/numba/typing/builtins.py b/numba/typing/builtins.py
--- a/numba/typing/builtins.py
+++ b/numba/typing/builtins.py
@@ -450,9 +450,10 @@ class Len(AbstractTemplate):
     def generic(self, args, kws):
         assert not kws
         (val,) = args
-        if isinstance(val, types.Buffer):
+        if isinstance(val, (types.Buffer, types.Tuple, types.UniTuple)):
             return signature(types.intp, val)
 
+
 #-------------------------------------------------------------------------------
 
 @builtin_attr


Test patch:
diff --git a/numba/tests/test_tuples.py b/numba/tests/test_tuples.py
--- a/numba/tests/test_tuples.py
+++ b/numba/tests/test_tuples.py
@@ -19,6 +19,9 @@ def tuple_second(tup):
     a, b = tup
     return b
 
+def len_usecase(tup):
+    return len(tup)
+
 
 class TestTupleReturn(TestCase):
 
@@ -76,5 +79,17 @@ def test_hetero_tuple(self):
         self.assertPreciseEqual(cr_second.entry_point((2**61, 1.5)), 1.5)
 
 
+class TestOperations(TestCase):
+
+    def test_len(self):
+        pyfunc = len_usecase
+        cr = compile_isolated(pyfunc,
+                              [types.Tuple((types.int64, types.float32))])
+        self.assertPreciseEqual(cr.entry_point((4, 5)), 2)
+        cr = compile_isolated(pyfunc,
+                              [types.UniTuple(types.int64, 3)])
+        self.assertPreciseEqual(cr.entry_point((4, 5, 6)), 3)
+
+
 if __name__ == '__main__':
     unittest.main()
Repository: numba/numba

Issue:
Array expr rewrite mishandling Dispatcher type
Minimal test case

``` python
from numba import jit
import numpy as np

@jit(nopython=True)
def foo(arr):
    return arr

@jit(nopython=True)
def bar(arr):
    c = foo(arr)
    d = foo(arr)   # rewrite pass requires at least 2 calls 
    return c, d

arr = np.arange(10)
bar(arr)
```

Traceback:

``` bash
File "/Users/sklam/dev/numba/numba/npyufunc/array_exprs.py", line 65, in match
    func_key = getattr(func_type.template, 'key', None)
```

This is the slow down reason for #1180



Discussion:

Resolving patch:
diff --git a/numba/npyufunc/array_exprs.py b/numba/npyufunc/array_exprs.py
--- a/numba/npyufunc/array_exprs.py
+++ b/numba/npyufunc/array_exprs.py
@@ -59,10 +59,13 @@ def match(self, block, typemap, calltypes):
                     elif ((expr_op == 'call') and (expr.func.name in typemap)):
                         # Could be a match for a ufunc or DUFunc call.
                         func_type = typemap[expr.func.name]
-                        func_key = getattr(func_type.template, 'key', None)
-                        if isinstance(func_key, (ufunc, DUFunc)):
-                            # If so, match it as a potential subexpression.
-                            array_assigns[target_name] = instr
+                        # Note: func_type can be a types.Dispatcher, which
+                        #       doesn't have the `.template` attribute.
+                        if hasattr(func_type, 'template'):
+                            func_key = getattr(func_type.template, 'key', None)
+                            if isinstance(func_key, (ufunc, DUFunc)):
+                                # If so, match it as a potential subexpression.
+                                array_assigns[target_name] = instr
                     # Now check to see if we matched anything of
                     # interest; if so, check to see if one of the
                     # expression's dependencies isn't also a matching


Test patch:
diff --git a/numba/tests/test_array_exprs.py b/numba/tests/test_array_exprs.py
--- a/numba/tests/test_array_exprs.py
+++ b/numba/tests/test_array_exprs.py
@@ -248,5 +248,27 @@ def test_cmp_op(self):
                                    ns.test_pipeline.interp.blocks)
 
 
+class TestRewriteIssues(unittest.TestCase):
+    def test_issue_1184(self):
+        from numba import jit
+        import numpy as np
+
+        @jit(nopython=True)
+        def foo(arr):
+            return arr
+
+        @jit(nopython=True)
+        def bar(arr):
+            c = foo(arr)
+            d = foo(arr)   # two calls to trigger rewrite
+            return c, d
+
+        arr = np.arange(10)
+        out_c, out_d = bar(arr)
+        self.assertIs(out_c, out_d)
+        self.assertIs(out_c, arr)
+
+
+
 if __name__ == "__main__":
     unittest.main()
Repository: numba/numba

Issue:
Warning at shutdown
I get the following warning at shutdown when running the test suite:

```
Exception ignored in: <bound method Context.__del__ of <CUDA context c_void_p(36426160) of device 0>>
Traceback (most recent call last):
  File "/home/antoine/numba/numba/cuda/cudadrv/driver.py", line 467, in __del__
AttributeError: 'NoneType' object has no attribute 'print_exc'
```



Discussion:

Resolving patch:
diff --git a/numba/cuda/cudadrv/driver.py b/numba/cuda/cudadrv/driver.py
--- a/numba/cuda/cudadrv/driver.py
+++ b/numba/cuda/cudadrv/driver.py
@@ -25,6 +25,7 @@
 import contextlib
 import numpy as np
 from collections import namedtuple
+
 from numba import utils, servicelib, mviewbuf
 from .error import CudaSupportError, CudaDriverError
 from .drvapi import API_PROTOTYPES
@@ -448,23 +449,30 @@ class Context(object):
     def __init__(self, device, handle, finalizer=None):
         self.device = device
         self.handle = handle
-        self.finalizer = finalizer
+        self.external_finalizer = finalizer
         self.trashing = TrashService("cuda.device%d.context%x.trash" %
                                      (self.device.id, self.handle.value))
-        self.is_managed = finalizer is not None
         self.allocations = utils.UniqueDict()
         self.modules = utils.UniqueDict()
+        self.finalizer = utils.finalize(self, self._make_finalizer())
         # For storing context specific data
         self.extras = {}
 
-    def __del__(self):
-        try:
-            self.reset()
-            # Free itself
-            if self.is_managed:
-                self.finalizer()
-        except:
-            traceback.print_exc()
+    def _make_finalizer(self):
+        """
+        Make a finalizer function that doesn't keep a reference to this object.
+        """
+        allocations = self.allocations
+        modules = self.modules
+        trashing = self.trashing
+        external_finalizer = self.external_finalizer
+        def finalize():
+            allocations.clear()
+            modules.clear()
+            trashing.clear()
+            if external_finalizer is not None:
+                external_finalizer()
+        return finalize
 
     def reset(self):
         """


Test patch:
Repository: numba/numba

Issue:
Memory leak in small example script.
Hi all,

@sklam another example script with a memory leak (I have updated to the latest numba version, so I have patch https://github.com/numba/numba/pull/1295). Are you able to reproduce? 

https://gist.github.com/bmer/753cac8ebde04b3472f0



Discussion:
I can reproduce this.  This is not related to #1295.  

Here's a minimal example to reproduce the problem:

``` python


@nb.jit(nopython=True)
def g(n):

    x = f(n)
    # y = None  # Uncomment this will "fix" the problem

    for i in range(n):
        y = x[i]

    for i in range(n):
        y = x[i]

    return 0


num_tsteps = 10000
for i in range(num_tsteps):
    g(10)
```


Resolving patch:
diff --git a/numba/lowering.py b/numba/lowering.py
--- a/numba/lowering.py
+++ b/numba/lowering.py
@@ -704,17 +704,8 @@ def loadvar(self, name):
 
     def storevar(self, value, name):
         fetype = self.typeof(name)
-        # Clean up existing value stored in the variable
-        try:
-            # Load original value in variable
-            old = self.loadvar(name)
-        except KeyError:
-            # If it has not been defined, don't do anything
-            pass
-        else:
-            # Else, dereference the old value
-            self.decref(fetype, old)
-        # Store variable
+
+        # Define if not already
         if name not in self.varmap:
             # If not already defined, allocate it
             llty = self.context.get_value_type(fetype)
@@ -722,6 +713,11 @@ def storevar(self, value, name):
             # Remember the pointer
             self.varmap[name] = ptr
 
+        # Clean up existing value stored in the variable
+        old = self.loadvar(name)
+        self.decref(fetype, old)
+
+        # Store variable
         ptr = self.getvar(name)
         if value.type != ptr.type.pointee:
             msg = ("Storing {value.type} to ptr of {ptr.type.pointee}. "


Test patch:
Repository: numba/numba

Issue:
NotImplementedError: augmented slice assignment
An augment-assign (`+=`) on an array slice causes Numba to raise a `NotImplementedError`.
This can be reproduced with the following code:

``` python
import numpy as np
import numba

@numba.jit
def func(buf):
    buf[2:8] += 10

buffer = np.arange(10)
func(buffer)
```

Executing this code produces the following error:
`NotImplementedError: offset=17 opcode=0x5 opname=ROT_FOUR`

I'm running on Python 2.7, Numba 0.20.0 on OSX



Discussion:
I see. This happens only on Python 2.


Resolving patch:
diff --git a/numba/bytecode.py b/numba/bytecode.py
--- a/numba/bytecode.py
+++ b/numba/bytecode.py
@@ -55,6 +55,7 @@ def _make_bytecode_table():
             ('INPLACE_DIVIDE', 0),
             ('PRINT_ITEM', 0),
             ('PRINT_NEWLINE', 0),
+            ('ROT_FOUR', 0),
             ('SLICE+0', 0),
             ('SLICE+1', 0),
             ('SLICE+2', 0),


Test patch:
diff --git a/numba/tests/test_indexing.py b/numba/tests/test_indexing.py
--- a/numba/tests/test_indexing.py
+++ b/numba/tests/test_indexing.py
@@ -127,6 +127,12 @@ def slicing_1d_usecase_set(a, b, start, stop, step):
     a[start:stop:step] = b
     return a
 
+def slicing_1d_usecase_add(a, b, start, stop):
+    # NOTE: uses the ROT_FOUR opcode on Python 2, only on the [start:stop]
+    # with inplace operator form.
+    a[start:stop] += b
+    return a
+
 def slicing_2d_usecase_set(a, b, start, stop, step, start2, stop2, step2):
     a[start:stop:step,start2:stop2:step2] = b
     return a
@@ -699,6 +705,19 @@ def test_1d_slicing_set(self, flags=enable_pyobj_flags):
             cleft = cfunc(np.zeros_like(arg), arg[slice(*test)], *test)
             self.assertTrue((pyleft == cleft).all())
 
+    def test_1d_slicing_add(self, flags=enable_pyobj_flags):
+        pyfunc = slicing_1d_usecase_add
+        arraytype = types.Array(types.int32, 1, 'C')
+        argtys = (arraytype, arraytype, types.int32, types.int32)
+        cr = compile_isolated(pyfunc, argtys, flags=flags)
+        cfunc = cr.entry_point
+
+        arg = np.arange(10, dtype='i4')
+        for test in ((0, 10), (2, 5)):
+            pyleft = pyfunc(np.zeros_like(arg), arg[slice(*test)], *test)
+            cleft = cfunc(np.zeros_like(arg), arg[slice(*test)], *test)
+            self.assertTrue((pyleft == cleft).all())
+
     def test_1d_slicing_set_npm(self):
         """
         TypingError: Cannot resolve setitem: array(int32, 1d, C)[slice3_type] = ...
@@ -707,6 +726,10 @@ def test_1d_slicing_set_npm(self):
         with self.assertTypingError():
             self.test_1d_slicing_set(flags=Noflags)
 
+    def test_1d_slicing_add_npm(self):
+        with self.assertTypingError():
+            self.test_1d_slicing_add(flags=Noflags)
+
     def test_2d_slicing_set(self, flags=enable_pyobj_flags):
         pyfunc = slicing_2d_usecase_set
         arraytype = types.Array(types.int32, 2, 'C')
Repository: numba/numba

Issue:
Cannot pass list to inner function
If you try the following code:

```
@jit(nopython=True)
def inner(l):
    return len(l)

@jit(nopython=True)
def outer(n):
    l = list(range(n))
    return inner(l)

print(outer(5))
```

You get this error:

```
NotImplementedError: Failed at nopython (nopython mode backend)
cannot convert list(int64) to native value
```

This is because, even though inner() is called from another nopython function, the Python-facing wrapper is always generated, and this fails when trying to unbox a hypothetical Python list.



Discussion:

Resolving patch:
diff --git a/numba/targets/boxing.py b/numba/targets/boxing.py
--- a/numba/targets/boxing.py
+++ b/numba/targets/boxing.py
@@ -422,6 +422,20 @@ def box_list(c, typ, val):
     return obj
 
 
+@unbox(types.List)
+def unbox_list(c, typ, obj):
+    # Since a wrapper is always compiled even for an inner function,
+    # we have to define this to be able to pass lists from one Numba
+    # function to another.
+    # This code should nevertheless never be executed at runtime.
+    c.pyapi.err_set_string("PyExc_RuntimeError",
+                           "cannot unbox list objects")
+
+    # Just return a zero-initialized list value for successful codegen.
+    value = ir.Constant(c.context.get_value_type(typ), None)
+    return NativeValue(value, is_error=cgutils.true_bit)
+
+
 #
 # Other types
 #


Test patch:
diff --git a/numba/tests/test_lists.py b/numba/tests/test_lists.py
--- a/numba/tests/test_lists.py
+++ b/numba/tests/test_lists.py
@@ -541,6 +541,22 @@ def test_bool(self):
             expected = pyfunc(n)
             self.assertPreciseEqual(cfunc(n), expected)
 
+    def test_list_passing(self):
+        # Check one can pass a list from a Numba function to another
+        @jit(nopython=True)
+        def inner(lst):
+            return len(lst), lst[-1]
+
+        @jit(nopython=True)
+        def outer(n):
+            l = list(range(n))
+            return inner(l)
+
+        self.assertPreciseEqual(outer(5), (5, 4))
+        # Cannot call the inner function directly
+        with self.assertRaises(TypeError):
+            inner([42])
+
 
 if __name__ == '__main__':
     unittest.main()