We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Dispatcher bug 
``` python
from numba import jit

@jit
def foo(a, b):
    return 1

# <class 'int'> <class 'float'>
# <class 'float'> <class 'int'>
# <class 'float'> <class 'float'>
# <class 'int'> <class 'int'>

foo(1, 0.1)
foo(0.1, 1)
foo(0.1, 0.1)
foo(1, 1)
```

```
Traceback (most recent call last):
  File "test_disp.py", line 15, in <module>
    foo(1, 1)
  File "/Users/sklam/dev/numba/numba/dispatcher.py", line 161, in _explain_ambiguous
    tuple(self.overloads.keys()), args, kws)
  File "/Users/sklam/dev/numba/numba/typing/templates.py", line 84, in resolve_overload
    if len(args) == len(case.args):
AttributeError: 'tuple' object has no attribute 'args'
```

Dispatcher bug 
``` python
from numba import jit

@jit
def foo(a, b):
    return 1

# <class 'int'> <class 'float'>
# <class 'float'> <class 'int'>
# <class 'float'> <class 'float'>
# <class 'int'> <class 'int'>

foo(1, 0.1)
foo(0.1, 1)
foo(0.1, 0.1)
foo(1, 1)
```

```
Traceback (most recent call last):
  File "test_disp.py", line 15, in <module>
    foo(1, 1)
  File "/Users/sklam/dev/numba/numba/dispatcher.py", line 161, in _explain_ambiguous
    tuple(self.overloads.keys()), args, kws)
  File "/Users/sklam/dev/numba/numba/typing/templates.py", line 84, in resolve_overload
    if len(args) == len(case.args):
AttributeError: 'tuple' object has no attribute 'args'
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `numba/dispatcher.py`
Content:
```
1 from __future__ import print_function, division, absolute_import
2 import contextlib
3 import functools
4 import inspect
5 import sys
6 
7 from numba import _dispatcher, compiler, utils
8 from numba.typeconv.rules import default_type_manager
9 from numba import typing
10 from numba.typing.templates import resolve_overload
11 from numba import types, sigutils
12 from numba.bytecode import get_code_object
13 
14 
15 class _OverloadedBase(_dispatcher.Dispatcher):
16     """
17     Common base class for dispatcher Implementations.
18     """
19 
20     __numba__ = "py_func"
21 
22     def __init__(self, arg_count, py_func):
23         self.tm = default_type_manager
24         _dispatcher.Dispatcher.__init__(self, self.tm.get_pointer(), arg_count)
25 
26         # A mapping of signatures to entry points
27         self.overloads = {}
28         # A mapping of signatures to types.Function objects
29         self._function_types = {}
30         # A mapping of signatures to compile results
31         self._compileinfos = {}
32 
33         self.py_func = py_func
34         # other parts of Numba assume the old Python 2 name for code object
35         self.func_code = get_code_object(py_func)
36         # but newer python uses a different name
37         self.__code__ = self.func_code
38 
39         self.doc = py_func.__doc__
40         self._compiling = False
41 
42         utils.finalize(self, self._make_finalizer())
43 
44     def _make_finalizer(self):
45         """
46         Return a finalizer function that will release references to
47         related compiled functions.
48         """
49         overloads = self.overloads
50         targetctx = self.targetctx
51         # Early-bind utils.shutting_down() into the function's local namespace
52         # (see issue #689)
53         def finalizer(shutting_down=utils.shutting_down):
54             # The finalizer may crash at shutdown, skip it (resources
55             # will be cleared by the process exiting, anyway).
56             if shutting_down():
57                 return
58             # This function must *not* hold any reference to self:
59             # we take care to bind the necessary objects in the closure.
60             for func in overloads.values():
61                 try:
62                     targetctx.remove_user_function(func)
63                     targetctx.remove_native_function(func)
64                 except KeyError:
65                     # Not a native function (object mode presumably)
66                     pass
67 
68         return finalizer
69 
70     @property
71     def signatures(self):
72         """
73         Returns a list of compiled function signatures.
74         """
75         return list(self.overloads)
76 
77     def disable_compile(self, val=True):
78         """Disable the compilation of new signatures at call time.
79         """
80         self._disable_compile(int(val))
81 
82     def add_overload(self, cres):
83         args = tuple(cres.signature.args)
84         sig = [a._code for a in args]
85         self._insert(sig, cres.entry_point, cres.objectmode)
86         self.overloads[args] = cres.entry_point
87         self._compileinfos[args] = cres
88 
89         # Add native function for correct typing the code generation
90         target = cres.target_context
91         cfunc = cres.entry_point
92         if cfunc in target.native_funcs:
93             target.dynamic_map_function(cfunc)
94             # Create function type for typing
95             func_name = cres.fndesc.mangled_name
96             name = "CallTemplate(%s)" % cres.fndesc.mangled_name
97             # The `key` isn't really used except for diagnosis here,
98             # so avoid keeping a reference to `cfunc`.
99             call_template = typing.make_concrete_template(
100                 name, key=func_name, signatures=[cres.signature])
101             self._function_types[args] = call_template
102 
103     def get_call_template(self, args, kws):
104         """
105         Get a typing.ConcreteTemplate for this dispatcher and the given *args*
106         and *kws*.  This allows to resolve the return type.
107         """
108         if kws:
109             raise TypeError("kwargs not supported")
110         # Ensure an overload is available, but avoid compiler re-entrance
111         if not self.is_compiling:
112             self.compile(tuple(args))
113         return self._function_types[args]
114 
115     def get_overload(self, sig):
116         args, return_type = sigutils.normalize_signature(sig)
117         return self.overloads[tuple(args)]
118 
119     @contextlib.contextmanager
120     def _compile_lock(self):
121         if self._compiling:
122             raise RuntimeError("Compiler re-entrant")
123         self._compiling = True
124         try:
125             yield
126         finally:
127             self._compiling = False
128 
129     @property
130     def is_compiling(self):
131         return self._compiling
132 
133     def jit(self, sig, **kws):
134         """Alias of compile(sig, **kws)
135         """
136         return self.compile(sig, **kws)
137 
138     def _compile_for_args(self, *args, **kws):
139         """
140         For internal use.  Compile a specialized version of the function
141         for the given *args* and *kws*, and return the resulting callable.
142         """
143         assert not kws
144         sig = tuple([self.typeof_pyval(a) for a in args])
145         return self.jit(sig)
146 
147     def inspect_types(self, file=None):
148         if file is None:
149             file = sys.stdout
150 
151         for ver, res in utils.iteritems(self._compileinfos):
152             print("%s %s" % (self.py_func.__name__, ver), file=file)
153             print('-' * 80, file=file)
154             print(res.type_annotation, file=file)
155             print('=' * 80, file=file)
156 
157     def _explain_ambiguous(self, *args, **kws):
158         assert not kws, "kwargs not handled"
159         args = tuple([self.typeof_pyval(a) for a in args])
160         resolve_overload(self.typingctx, self.py_func,
161                          tuple(self.overloads.keys()), args, kws)
162 
163     def __repr__(self):
164         return "%s(%s)" % (type(self).__name__, self.py_func)
165 
166     def typeof_pyval(self, val):
167         """
168         Resolve the Numba type of Python value *val*.
169         This is called from numba._dispatcher as a fallback if the native code
170         cannot decide the type.
171         """
172         if isinstance(val, utils.INT_TYPES):
173             # Ensure no autoscaling of integer type, to match the
174             # typecode() function in _dispatcher.c.
175             return types.int64
176 
177         tp = self.typingctx.resolve_data_type(val)
178         if tp is None:
179             tp = types.pyobject
180         return tp
181 
182 
183 class Overloaded(_OverloadedBase):
184     """
185     Implementation of user-facing dispatcher objects (i.e. created using
186     the @jit decorator).
187     This is an abstract base class. Subclasses should define the targetdescr
188     class attribute.
189     """
190 
191     def __init__(self, py_func, locals={}, targetoptions={}):
192         """
193         Parameters
194         ----------
195         py_func: function object to be compiled
196         locals: dict, optional
197             Mapping of local variable names to Numba types.  Used to override
198             the types deduced by the type inference engine.
199         targetoptions: dict, optional
200             Target-specific config options.
201         """
202         self.typingctx = self.targetdescr.typing_context
203         self.targetctx = self.targetdescr.target_context
204 
205         argspec = inspect.getargspec(py_func)
206         argct = len(argspec.args)
207 
208         _OverloadedBase.__init__(self, argct, py_func)
209 
210         functools.update_wrapper(self, py_func)
211 
212         self.targetoptions = targetoptions
213         self.locals = locals
214 
215         self.typingctx.insert_overloaded(self)
216 
217     def compile(self, sig, locals={}, **targetoptions):
218         with self._compile_lock():
219             locs = self.locals.copy()
220             locs.update(locals)
221 
222             topt = self.targetoptions.copy()
223             topt.update(targetoptions)
224 
225             flags = compiler.Flags()
226             self.targetdescr.options.parse_as_flags(flags, topt)
227 
228             args, return_type = sigutils.normalize_signature(sig)
229 
230             # Don't recompile if signature already exist.
231             existing = self.overloads.get(tuple(args))
232             if existing is not None:
233                 return existing
234 
235             cres = compiler.compile_extra(self.typingctx, self.targetctx,
236                                           self.py_func,
237                                           args=args, return_type=return_type,
238                                           flags=flags, locals=locs)
239 
240             # Check typing error if object mode is used
241             if cres.typing_error is not None and not flags.enable_pyobject:
242                 raise cres.typing_error
243 
244             self.add_overload(cres)
245             return cres.entry_point
246 
247 
248 class LiftedLoop(_OverloadedBase):
249     """
250     Implementation of the hidden dispatcher objects used for lifted loop
251     (a lifted loop is really compiled as a separate function).
252     """
253 
254     def __init__(self, bytecode, typingctx, targetctx, locals, flags):
255         self.typingctx = typingctx
256         self.targetctx = targetctx
257 
258         argspec = bytecode.argspec
259         argct = len(argspec.args)
260 
261         _OverloadedBase.__init__(self, argct, bytecode.func)
262 
263         self.locals = locals
264         self.flags = flags
265         self.bytecode = bytecode
266 
267     def compile(self, sig):
268         with self._compile_lock():
269             # FIXME this is mostly duplicated from Overloaded
270             flags = self.flags
271             args, return_type = sigutils.normalize_signature(sig)
272 
273             # Don't recompile if signature already exist.
274             existing = self.overloads.get(tuple(args))
275             if existing is not None:
276                 return existing.entry_point
277 
278             assert not flags.enable_looplift, "Enable looplift flags is on"
279             cres = compiler.compile_bytecode(typingctx=self.typingctx,
280                                              targetctx=self.targetctx,
281                                              bc=self.bytecode,
282                                              args=args,
283                                              return_type=return_type,
284                                              flags=flags,
285                                              locals=self.locals)
286 
287             # Check typing error if object mode is used
288             if cres.typing_error is not None and not flags.enable_pyobject:
289                 raise cres.typing_error
290 
291             self.add_overload(cres)
292             return cres.entry_point
293 
294 
295 # Initialize dispatcher
296 _dispatcher.init_types(dict((str(t), t._code) for t in types.number_domain))
297
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/numba/dispatcher.py b/numba/dispatcher.py
--- a/numba/dispatcher.py
+++ b/numba/dispatcher.py
@@ -157,8 +157,8 @@
     def _explain_ambiguous(self, *args, **kws):
         assert not kws, "kwargs not handled"
         args = tuple([self.typeof_pyval(a) for a in args])
-        resolve_overload(self.typingctx, self.py_func,
-                         tuple(self.overloads.keys()), args, kws)
+        sigs = [cr.signature for cr in self._compileinfos.values()]
+        resolve_overload(self.typingctx, self.py_func, sigs, args, kws)
 
     def __repr__(self):
         return "%s(%s)" % (type(self).__name__, self.py_func)

{"golden_diff": "diff --git a/numba/dispatcher.py b/numba/dispatcher.py\n--- a/numba/dispatcher.py\n+++ b/numba/dispatcher.py\n@@ -157,8 +157,8 @@\n     def _explain_ambiguous(self, *args, **kws):\n         assert not kws, \"kwargs not handled\"\n         args = tuple([self.typeof_pyval(a) for a in args])\n-        resolve_overload(self.typingctx, self.py_func,\n-                         tuple(self.overloads.keys()), args, kws)\n+        sigs = [cr.signature for cr in self._compileinfos.values()]\n+        resolve_overload(self.typingctx, self.py_func, sigs, args, kws)\n \n     def __repr__(self):\n         return \"%s(%s)\" % (type(self).__name__, self.py_func)\n", "issue": "Dispatcher bug \n``` python\nfrom numba import jit\n\n@jit\ndef foo(a, b):\n    return 1\n\n# <class 'int'> <class 'float'>\n# <class 'float'> <class 'int'>\n# <class 'float'> <class 'float'>\n# <class 'int'> <class 'int'>\n\nfoo(1, 0.1)\nfoo(0.1, 1)\nfoo(0.1, 0.1)\nfoo(1, 1)\n```\n\n```\nTraceback (most recent call last):\n  File \"test_disp.py\", line 15, in <module>\n    foo(1, 1)\n  File \"/Users/sklam/dev/numba/numba/dispatcher.py\", line 161, in _explain_ambiguous\n    tuple(self.overloads.keys()), args, kws)\n  File \"/Users/sklam/dev/numba/numba/typing/templates.py\", line 84, in resolve_overload\n    if len(args) == len(case.args):\nAttributeError: 'tuple' object has no attribute 'args'\n```\n\nDispatcher bug \n``` python\nfrom numba import jit\n\n@jit\ndef foo(a, b):\n    return 1\n\n# <class 'int'> <class 'float'>\n# <class 'float'> <class 'int'>\n# <class 'float'> <class 'float'>\n# <class 'int'> <class 'int'>\n\nfoo(1, 0.1)\nfoo(0.1, 1)\nfoo(0.1, 0.1)\nfoo(1, 1)\n```\n\n```\nTraceback (most recent call last):\n  File \"test_disp.py\", line 15, in <module>\n    foo(1, 1)\n  File \"/Users/sklam/dev/numba/numba/dispatcher.py\", line 161, in _explain_ambiguous\n    tuple(self.overloads.keys()), args, kws)\n  File \"/Users/sklam/dev/numba/numba/typing/templates.py\", line 84, in resolve_overload\n    if len(args) == len(case.args):\nAttributeError: 'tuple' object has no attribute 'args'\n```\n\n", "before_files": [{"content": "from __future__ import print_function, division, absolute_import\nimport contextlib\nimport functools\nimport inspect\nimport sys\n\nfrom numba import _dispatcher, compiler, utils\nfrom numba.typeconv.rules import default_type_manager\nfrom numba import typing\nfrom numba.typing.templates import resolve_overload\nfrom numba import types, sigutils\nfrom numba.bytecode import get_code_object\n\n\nclass _OverloadedBase(_dispatcher.Dispatcher):\n    \"\"\"\n    Common base class for dispatcher Implementations.\n    \"\"\"\n\n    __numba__ = \"py_func\"\n\n    def __init__(self, arg_count, py_func):\n        self.tm = default_type_manager\n        _dispatcher.Dispatcher.__init__(self, self.tm.get_pointer(), arg_count)\n\n        # A mapping of signatures to entry points\n        self.overloads = {}\n        # A mapping of signatures to types.Function objects\n        self._function_types = {}\n        # A mapping of signatures to compile results\n        self._compileinfos = {}\n\n        self.py_func = py_func\n        # other parts of Numba assume the old Python 2 name for code object\n        self.func_code = get_code_object(py_func)\n        # but newer python uses a different name\n        self.__code__ = self.func_code\n\n        self.doc = py_func.__doc__\n        self._compiling = False\n\n        utils.finalize(self, self._make_finalizer())\n\n    def _make_finalizer(self):\n        \"\"\"\n        Return a finalizer function that will release references to\n        related compiled functions.\n        \"\"\"\n        overloads = self.overloads\n        targetctx = self.targetctx\n        # Early-bind utils.shutting_down() into the function's local namespace\n        # (see issue #689)\n        def finalizer(shutting_down=utils.shutting_down):\n            # The finalizer may crash at shutdown, skip it (resources\n            # will be cleared by the process exiting, anyway).\n            if shutting_down():\n                return\n            # This function must *not* hold any reference to self:\n            # we take care to bind the necessary objects in the closure.\n            for func in overloads.values():\n                try:\n                    targetctx.remove_user_function(func)\n                    targetctx.remove_native_function(func)\n                except KeyError:\n                    # Not a native function (object mode presumably)\n                    pass\n\n        return finalizer\n\n    @property\n    def signatures(self):\n        \"\"\"\n        Returns a list of compiled function signatures.\n        \"\"\"\n        return list(self.overloads)\n\n    def disable_compile(self, val=True):\n        \"\"\"Disable the compilation of new signatures at call time.\n        \"\"\"\n        self._disable_compile(int(val))\n\n    def add_overload(self, cres):\n        args = tuple(cres.signature.args)\n        sig = [a._code for a in args]\n        self._insert(sig, cres.entry_point, cres.objectmode)\n        self.overloads[args] = cres.entry_point\n        self._compileinfos[args] = cres\n\n        # Add native function for correct typing the code generation\n        target = cres.target_context\n        cfunc = cres.entry_point\n        if cfunc in target.native_funcs:\n            target.dynamic_map_function(cfunc)\n            # Create function type for typing\n            func_name = cres.fndesc.mangled_name\n            name = \"CallTemplate(%s)\" % cres.fndesc.mangled_name\n            # The `key` isn't really used except for diagnosis here,\n            # so avoid keeping a reference to `cfunc`.\n            call_template = typing.make_concrete_template(\n                name, key=func_name, signatures=[cres.signature])\n            self._function_types[args] = call_template\n\n    def get_call_template(self, args, kws):\n        \"\"\"\n        Get a typing.ConcreteTemplate for this dispatcher and the given *args*\n        and *kws*.  This allows to resolve the return type.\n        \"\"\"\n        if kws:\n            raise TypeError(\"kwargs not supported\")\n        # Ensure an overload is available, but avoid compiler re-entrance\n        if not self.is_compiling:\n            self.compile(tuple(args))\n        return self._function_types[args]\n\n    def get_overload(self, sig):\n        args, return_type = sigutils.normalize_signature(sig)\n        return self.overloads[tuple(args)]\n\n    @contextlib.contextmanager\n    def _compile_lock(self):\n        if self._compiling:\n            raise RuntimeError(\"Compiler re-entrant\")\n        self._compiling = True\n        try:\n            yield\n        finally:\n            self._compiling = False\n\n    @property\n    def is_compiling(self):\n        return self._compiling\n\n    def jit(self, sig, **kws):\n        \"\"\"Alias of compile(sig, **kws)\n        \"\"\"\n        return self.compile(sig, **kws)\n\n    def _compile_for_args(self, *args, **kws):\n        \"\"\"\n        For internal use.  Compile a specialized version of the function\n        for the given *args* and *kws*, and return the resulting callable.\n        \"\"\"\n        assert not kws\n        sig = tuple([self.typeof_pyval(a) for a in args])\n        return self.jit(sig)\n\n    def inspect_types(self, file=None):\n        if file is None:\n            file = sys.stdout\n\n        for ver, res in utils.iteritems(self._compileinfos):\n            print(\"%s %s\" % (self.py_func.__name__, ver), file=file)\n            print('-' * 80, file=file)\n            print(res.type_annotation, file=file)\n            print('=' * 80, file=file)\n\n    def _explain_ambiguous(self, *args, **kws):\n        assert not kws, \"kwargs not handled\"\n        args = tuple([self.typeof_pyval(a) for a in args])\n        resolve_overload(self.typingctx, self.py_func,\n                         tuple(self.overloads.keys()), args, kws)\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, self.py_func)\n\n    def typeof_pyval(self, val):\n        \"\"\"\n        Resolve the Numba type of Python value *val*.\n        This is called from numba._dispatcher as a fallback if the native code\n        cannot decide the type.\n        \"\"\"\n        if isinstance(val, utils.INT_TYPES):\n            # Ensure no autoscaling of integer type, to match the\n            # typecode() function in _dispatcher.c.\n            return types.int64\n\n        tp = self.typingctx.resolve_data_type(val)\n        if tp is None:\n            tp = types.pyobject\n        return tp\n\n\nclass Overloaded(_OverloadedBase):\n    \"\"\"\n    Implementation of user-facing dispatcher objects (i.e. created using\n    the @jit decorator).\n    This is an abstract base class. Subclasses should define the targetdescr\n    class attribute.\n    \"\"\"\n\n    def __init__(self, py_func, locals={}, targetoptions={}):\n        \"\"\"\n        Parameters\n        ----------\n        py_func: function object to be compiled\n        locals: dict, optional\n            Mapping of local variable names to Numba types.  Used to override\n            the types deduced by the type inference engine.\n        targetoptions: dict, optional\n            Target-specific config options.\n        \"\"\"\n        self.typingctx = self.targetdescr.typing_context\n        self.targetctx = self.targetdescr.target_context\n\n        argspec = inspect.getargspec(py_func)\n        argct = len(argspec.args)\n\n        _OverloadedBase.__init__(self, argct, py_func)\n\n        functools.update_wrapper(self, py_func)\n\n        self.targetoptions = targetoptions\n        self.locals = locals\n\n        self.typingctx.insert_overloaded(self)\n\n    def compile(self, sig, locals={}, **targetoptions):\n        with self._compile_lock():\n            locs = self.locals.copy()\n            locs.update(locals)\n\n            topt = self.targetoptions.copy()\n            topt.update(targetoptions)\n\n            flags = compiler.Flags()\n            self.targetdescr.options.parse_as_flags(flags, topt)\n\n            args, return_type = sigutils.normalize_signature(sig)\n\n            # Don't recompile if signature already exist.\n            existing = self.overloads.get(tuple(args))\n            if existing is not None:\n                return existing\n\n            cres = compiler.compile_extra(self.typingctx, self.targetctx,\n                                          self.py_func,\n                                          args=args, return_type=return_type,\n                                          flags=flags, locals=locs)\n\n            # Check typing error if object mode is used\n            if cres.typing_error is not None and not flags.enable_pyobject:\n                raise cres.typing_error\n\n            self.add_overload(cres)\n            return cres.entry_point\n\n\nclass LiftedLoop(_OverloadedBase):\n    \"\"\"\n    Implementation of the hidden dispatcher objects used for lifted loop\n    (a lifted loop is really compiled as a separate function).\n    \"\"\"\n\n    def __init__(self, bytecode, typingctx, targetctx, locals, flags):\n        self.typingctx = typingctx\n        self.targetctx = targetctx\n\n        argspec = bytecode.argspec\n        argct = len(argspec.args)\n\n        _OverloadedBase.__init__(self, argct, bytecode.func)\n\n        self.locals = locals\n        self.flags = flags\n        self.bytecode = bytecode\n\n    def compile(self, sig):\n        with self._compile_lock():\n            # FIXME this is mostly duplicated from Overloaded\n            flags = self.flags\n            args, return_type = sigutils.normalize_signature(sig)\n\n            # Don't recompile if signature already exist.\n            existing = self.overloads.get(tuple(args))\n            if existing is not None:\n                return existing.entry_point\n\n            assert not flags.enable_looplift, \"Enable looplift flags is on\"\n            cres = compiler.compile_bytecode(typingctx=self.typingctx,\n                                             targetctx=self.targetctx,\n                                             bc=self.bytecode,\n                                             args=args,\n                                             return_type=return_type,\n                                             flags=flags,\n                                             locals=self.locals)\n\n            # Check typing error if object mode is used\n            if cres.typing_error is not None and not flags.enable_pyobject:\n                raise cres.typing_error\n\n            self.add_overload(cres)\n            return cres.entry_point\n\n\n# Initialize dispatcher\n_dispatcher.init_types(dict((str(t), t._code) for t in types.number_domain))\n", "path": "numba/dispatcher.py"}], "after_files": [{"content": "from __future__ import print_function, division, absolute_import\nimport contextlib\nimport functools\nimport inspect\nimport sys\n\nfrom numba import _dispatcher, compiler, utils\nfrom numba.typeconv.rules import default_type_manager\nfrom numba import typing\nfrom numba.typing.templates import resolve_overload\nfrom numba import types, sigutils\nfrom numba.bytecode import get_code_object\n\n\nclass _OverloadedBase(_dispatcher.Dispatcher):\n    \"\"\"\n    Common base class for dispatcher Implementations.\n    \"\"\"\n\n    __numba__ = \"py_func\"\n\n    def __init__(self, arg_count, py_func):\n        self.tm = default_type_manager\n        _dispatcher.Dispatcher.__init__(self, self.tm.get_pointer(), arg_count)\n\n        # A mapping of signatures to entry points\n        self.overloads = {}\n        # A mapping of signatures to types.Function objects\n        self._function_types = {}\n        # A mapping of signatures to compile results\n        self._compileinfos = {}\n\n        self.py_func = py_func\n        # other parts of Numba assume the old Python 2 name for code object\n        self.func_code = get_code_object(py_func)\n        # but newer python uses a different name\n        self.__code__ = self.func_code\n\n        self.doc = py_func.__doc__\n        self._compiling = False\n\n        utils.finalize(self, self._make_finalizer())\n\n    def _make_finalizer(self):\n        \"\"\"\n        Return a finalizer function that will release references to\n        related compiled functions.\n        \"\"\"\n        overloads = self.overloads\n        targetctx = self.targetctx\n        # Early-bind utils.shutting_down() into the function's local namespace\n        # (see issue #689)\n        def finalizer(shutting_down=utils.shutting_down):\n            # The finalizer may crash at shutdown, skip it (resources\n            # will be cleared by the process exiting, anyway).\n            if shutting_down():\n                return\n            # This function must *not* hold any reference to self:\n            # we take care to bind the necessary objects in the closure.\n            for func in overloads.values():\n                try:\n                    targetctx.remove_user_function(func)\n                    targetctx.remove_native_function(func)\n                except KeyError:\n                    # Not a native function (object mode presumably)\n                    pass\n\n        return finalizer\n\n    @property\n    def signatures(self):\n        \"\"\"\n        Returns a list of compiled function signatures.\n        \"\"\"\n        return list(self.overloads)\n\n    def disable_compile(self, val=True):\n        \"\"\"Disable the compilation of new signatures at call time.\n        \"\"\"\n        self._disable_compile(int(val))\n\n    def add_overload(self, cres):\n        args = tuple(cres.signature.args)\n        sig = [a._code for a in args]\n        self._insert(sig, cres.entry_point, cres.objectmode)\n        self.overloads[args] = cres.entry_point\n        self._compileinfos[args] = cres\n\n        # Add native function for correct typing the code generation\n        target = cres.target_context\n        cfunc = cres.entry_point\n        if cfunc in target.native_funcs:\n            target.dynamic_map_function(cfunc)\n            # Create function type for typing\n            func_name = cres.fndesc.mangled_name\n            name = \"CallTemplate(%s)\" % cres.fndesc.mangled_name\n            # The `key` isn't really used except for diagnosis here,\n            # so avoid keeping a reference to `cfunc`.\n            call_template = typing.make_concrete_template(\n                name, key=func_name, signatures=[cres.signature])\n            self._function_types[args] = call_template\n\n    def get_call_template(self, args, kws):\n        \"\"\"\n        Get a typing.ConcreteTemplate for this dispatcher and the given *args*\n        and *kws*.  This allows to resolve the return type.\n        \"\"\"\n        if kws:\n            raise TypeError(\"kwargs not supported\")\n        # Ensure an overload is available, but avoid compiler re-entrance\n        if not self.is_compiling:\n            self.compile(tuple(args))\n        return self._function_types[args]\n\n    def get_overload(self, sig):\n        args, return_type = sigutils.normalize_signature(sig)\n        return self.overloads[tuple(args)]\n\n    @contextlib.contextmanager\n    def _compile_lock(self):\n        if self._compiling:\n            raise RuntimeError(\"Compiler re-entrant\")\n        self._compiling = True\n        try:\n            yield\n        finally:\n            self._compiling = False\n\n    @property\n    def is_compiling(self):\n        return self._compiling\n\n    def jit(self, sig, **kws):\n        \"\"\"Alias of compile(sig, **kws)\n        \"\"\"\n        return self.compile(sig, **kws)\n\n    def _compile_for_args(self, *args, **kws):\n        \"\"\"\n        For internal use.  Compile a specialized version of the function\n        for the given *args* and *kws*, and return the resulting callable.\n        \"\"\"\n        assert not kws\n        sig = tuple([self.typeof_pyval(a) for a in args])\n        return self.jit(sig)\n\n    def inspect_types(self, file=None):\n        if file is None:\n            file = sys.stdout\n\n        for ver, res in utils.iteritems(self._compileinfos):\n            print(\"%s %s\" % (self.py_func.__name__, ver), file=file)\n            print('-' * 80, file=file)\n            print(res.type_annotation, file=file)\n            print('=' * 80, file=file)\n\n    def _explain_ambiguous(self, *args, **kws):\n        assert not kws, \"kwargs not handled\"\n        args = tuple([self.typeof_pyval(a) for a in args])\n        sigs = [cr.signature for cr in self._compileinfos.values()]\n        resolve_overload(self.typingctx, self.py_func, sigs, args, kws)\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, self.py_func)\n\n    def typeof_pyval(self, val):\n        \"\"\"\n        Resolve the Numba type of Python value *val*.\n        This is called from numba._dispatcher as a fallback if the native code\n        cannot decide the type.\n        \"\"\"\n        if isinstance(val, utils.INT_TYPES):\n            # Ensure no autoscaling of integer type, to match the\n            # typecode() function in _dispatcher.c.\n            return types.int64\n\n        tp = self.typingctx.resolve_data_type(val)\n        if tp is None:\n            tp = types.pyobject\n        return tp\n\n\nclass Overloaded(_OverloadedBase):\n    \"\"\"\n    Implementation of user-facing dispatcher objects (i.e. created using\n    the @jit decorator).\n    This is an abstract base class. Subclasses should define the targetdescr\n    class attribute.\n    \"\"\"\n\n    def __init__(self, py_func, locals={}, targetoptions={}):\n        \"\"\"\n        Parameters\n        ----------\n        py_func: function object to be compiled\n        locals: dict, optional\n            Mapping of local variable names to Numba types.  Used to override\n            the types deduced by the type inference engine.\n        targetoptions: dict, optional\n            Target-specific config options.\n        \"\"\"\n        self.typingctx = self.targetdescr.typing_context\n        self.targetctx = self.targetdescr.target_context\n\n        argspec = inspect.getargspec(py_func)\n        argct = len(argspec.args)\n\n        _OverloadedBase.__init__(self, argct, py_func)\n\n        functools.update_wrapper(self, py_func)\n\n        self.targetoptions = targetoptions\n        self.locals = locals\n\n        self.typingctx.insert_overloaded(self)\n\n    def compile(self, sig, locals={}, **targetoptions):\n        with self._compile_lock():\n            locs = self.locals.copy()\n            locs.update(locals)\n\n            topt = self.targetoptions.copy()\n            topt.update(targetoptions)\n\n            flags = compiler.Flags()\n            self.targetdescr.options.parse_as_flags(flags, topt)\n\n            args, return_type = sigutils.normalize_signature(sig)\n\n            # Don't recompile if signature already exist.\n            existing = self.overloads.get(tuple(args))\n            if existing is not None:\n                return existing\n\n            cres = compiler.compile_extra(self.typingctx, self.targetctx,\n                                          self.py_func,\n                                          args=args, return_type=return_type,\n                                          flags=flags, locals=locs)\n\n            # Check typing error if object mode is used\n            if cres.typing_error is not None and not flags.enable_pyobject:\n                raise cres.typing_error\n\n            self.add_overload(cres)\n            return cres.entry_point\n\n\nclass LiftedLoop(_OverloadedBase):\n    \"\"\"\n    Implementation of the hidden dispatcher objects used for lifted loop\n    (a lifted loop is really compiled as a separate function).\n    \"\"\"\n\n    def __init__(self, bytecode, typingctx, targetctx, locals, flags):\n        self.typingctx = typingctx\n        self.targetctx = targetctx\n\n        argspec = bytecode.argspec\n        argct = len(argspec.args)\n\n        _OverloadedBase.__init__(self, argct, bytecode.func)\n\n        self.locals = locals\n        self.flags = flags\n        self.bytecode = bytecode\n\n    def compile(self, sig):\n        with self._compile_lock():\n            # FIXME this is mostly duplicated from Overloaded\n            flags = self.flags\n            args, return_type = sigutils.normalize_signature(sig)\n\n            # Don't recompile if signature already exist.\n            existing = self.overloads.get(tuple(args))\n            if existing is not None:\n                return existing.entry_point\n\n            assert not flags.enable_looplift, \"Enable looplift flags is on\"\n            cres = compiler.compile_bytecode(typingctx=self.typingctx,\n                                             targetctx=self.targetctx,\n                                             bc=self.bytecode,\n                                             args=args,\n                                             return_type=return_type,\n                                             flags=flags,\n                                             locals=self.locals)\n\n            # Check typing error if object mode is used\n            if cres.typing_error is not None and not flags.enable_pyobject:\n                raise cres.typing_error\n\n            self.add_overload(cres)\n            return cres.entry_point\n\n\n# Initialize dispatcher\n_dispatcher.init_types(dict((str(t), t._code) for t in types.number_domain))\n", "path": "numba/dispatcher.py"}]}