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

Issue:
Redhat 6.5 can no longer raise a TestError
Regressions report pass but number of tests has gone done on some simulators. Icarus for instance shows this.

```
0.00ns [34mINFO    [39m cocotb.gpi                                  gpi_embed.c:213  in embed_sim_init                  [34mRunning on Icarus Verilog version 0.10.0 (devel)[39m
     0.00ns [34mINFO    [39m cocotb.gpi                                  gpi_embed.c:214  in embed_sim_init                  [34mPython interpreter initialised and cocotb loaded![39m
     0.00ns [34mINFO    [39m cocotb.gpi                                  __init__.py:96   in _initialise_testbench           [34mSeeding Python random module with 1421853826[39m
     0.00ns [34mINFO    [39m cocotb.gpi                                  __init__.py:110  in _initialise_testbench           [34mRunning tests with Cocotb v0.5a from /var/lib/jenkins/workspace/cocotb_icarus_x86_64[39m
     0.00ns [31mERROR   [39m cocotb.coroutine.fail                     decorators.py:99   in __init__                        [31mtest_duplicate_yield isn't a value coroutine! Did you use the yield keyword?[39m
Traceback (most recent call last):
  File "/var/lib/jenkins/workspace/cocotb_icarus_x86_64/cocotb/__init__.py", line 128, in _initialise_testbench
    regression.initialise()
  File "/var/lib/jenkins/workspace/cocotb_icarus_x86_64/cocotb/regression.py", line 123, in initialise
    test = thing(self._dut)
  File "/var/lib/jenkins/workspace/cocotb_icarus_x86_64/cocotb/decorators.py", line 356, in _wrapped_test
    raise_error(self, str(e))
  File "/var/lib/jenkins/workspace/cocotb_icarus_x86_64/cocotb/result.py", line 42, in raise_error
    if sys.version_info.major >= 3:
AttributeError: 'tuple' object has no attribute 'major'
```



Discussion:
Unfortunately there's no way to control the exit code of the simulator so we can mask failures (the same thing was occurring with the Modelsim SIGSEGV).

There's a fairly strong argument for just `exit(1)` on any unhandled exceptions.  At least then Make would report the error, although it's possible the simulator would mask that too.


Resolving patch:
diff --git a/cocotb/result.py b/cocotb/result.py
--- a/cocotb/result.py
+++ b/cocotb/result.py
@@ -39,7 +39,8 @@ def raise_error(obj, msg):
         msg is a string
     """
     exc_type, exc_value, exc_traceback = sys.exc_info()
-    if sys.version_info.major >= 3:
+    # 2.6 cannot use named access
+    if sys.version_info[0] >= 3:
         buff = StringIO()
         traceback.print_tb(exc_traceback, file=buff)
     else:


Test patch:
Repository: cocotb/cocotb

Issue:
Typo in BusMonitor Causes python Exception
In the bus monitor function in_reset(), there is a typo causing a problem.

The code at lines 168-169, tests if self._reset is valid, but then it accesses self._reset_n when it should be accessing self._reset.



Discussion:

Resolving patch:
diff --git a/cocotb/monitors/__init__.py b/cocotb/monitors/__init__.py
--- a/cocotb/monitors/__init__.py
+++ b/cocotb/monitors/__init__.py
@@ -166,7 +166,7 @@ def in_reset(self):
         if self._reset_n is not None:
             return not bool(self._reset_n.value.integer)
         if self._reset is not None:
-            return bool(self._reset_n.value.integer)
+            return bool(self._reset.value.integer)
         return False
 
     def __str__(self):


Test patch:
Repository: cocotb/cocotb

Issue:
Add protection to RunningCoroutine.join()
In a large test, one might fork off several coroutines, then go off and do some things and finally want to invoke the join() function on the forked off coroutines to make sure everything has completed before finishing the test.

With the current implementation, after the coroutine is finished running, the underlying trigger that is returned when join() is called, is already deleted.  This means if I forked off a coroutine "coroutineA" and then later in the simulation call coroutineA.join(), this will throw an expception "Send raised exception: 'RunningCoroutine' object has to attribute '_join'".

Currently the only way to protect from this, is to test if the coroutine is still running and if it is then invoke the join().  Not bad if you only have one, but when you have several forked coroutines, this is a lot of typing.

My proposal would be to add protection into the RunningCoroutine::join() function and return a NullTrigger or some variant that will just trigger immediately if the coroutine is no longer running.

Something like:

``` python
def join(self):
    """Return a trigger that will fire when the wrapped coroutine exits"""
    if self._finished:
        return NullTrigger()
    else:
        return self._join
```



Discussion:

Resolving patch:
diff --git a/cocotb/decorators.py b/cocotb/decorators.py
--- a/cocotb/decorators.py
+++ b/cocotb/decorators.py
@@ -147,7 +147,10 @@ def _finished_cb(self):
 
     def join(self):
         """Return a trigger that will fire when the wrapped coroutine exits"""
-        return self._join
+        if self._finished:
+            return NullTrigger()
+        else:
+            return self._join
 
     def __nonzero__(self):
         """Provide boolean testing


Test patch:
Repository: cocotb/cocotb

Issue:
getvalue() in handle.py should configure the returned Binary value
When getting a value from a handle a "BinaryValue()" object is created.  In my case, I tried to slice that value to get the upper bits, but the call failed because the returned value is not configured.

I believe at a minimum, the Handle should set the number of bits, but ideally it would just configure everything the BinaryValue() object needs before returning it.



Discussion:
see also #134 which has a number of pending improvements for BinaryValue / Handle


Resolving patch:
diff --git a/cocotb/handle.py b/cocotb/handle.py
--- a/cocotb/handle.py
+++ b/cocotb/handle.py
@@ -82,7 +82,7 @@ def __getattr__(self, name):
         """ Query the simulator for a object with the specified name
             and cache the result to build a tree
         """
-        # python's builtin dir and IPython's dir2 search for these, 
+        # python's builtin dir and IPython's dir2 search for these,
         # raise an AttributeError to avoid incorrect calls to _raise_testerror
         if name in ["__methods__","__members__","trait_names","_getAttributeNames"]:
             raise AttributeError(name)
@@ -150,7 +150,7 @@ def __setitem__(self, index, value):
         self.__getitem__(index).setcachedvalue(value)
 
     def getvalue(self):
-        result = BinaryValue()
+        result = BinaryValue(bits=len(self))
         result.binstr = self._get_value_str()
         return result
 


Test patch:
Repository: cocotb/cocotb

Issue:
AvalonMM only supports readLatency == 1
We ignore the readdatavalid signal even if it's present.



Discussion:

Resolving patch:
diff --git a/cocotb/drivers/avalon.py b/cocotb/drivers/avalon.py
--- a/cocotb/drivers/avalon.py
+++ b/cocotb/drivers/avalon.py
@@ -81,7 +81,9 @@ def __init__(self, entity, name, clock):
         if hasattr(self.bus, "cs"):
             self.bus.cs.setimmediatevalue(0)
 
-        self.bus.address.setimmediatevalue(0)
+        v = self.bus.address.value
+        v.binstr = "x" * len(self.bus.address)
+        self.bus.address.setimmediatevalue(v)
 
     def read(self, address):
         pass
@@ -140,16 +142,6 @@ def read(self, address, sync=True):
         # Wait for waitrequest to be low
         if hasattr(self.bus, "waitrequest"):
             yield self._wait_for_nsignal(self.bus.waitrequest)
-
-        # Assume readLatency = 1
-        # FIXME need to configure this,
-        # should take a dictionary of Avalon properties.
-        yield RisingEdge(self.clock)
-
-        # Get the data
-        yield ReadOnly()
-        data = self.bus.readdata.value
-
         yield RisingEdge(self.clock)
 
         # Deassert read
@@ -158,6 +150,24 @@ def read(self, address, sync=True):
             self.bus.byteenable <= 0
         if hasattr(self.bus, "cs"):
             self.bus.cs <= 0
+        v = self.bus.address.value
+        v.binstr = "x" * len(self.bus.address)
+        self.bus.address <= v
+
+        if hasattr(self.bus, "readdatavalid"):
+            while True:
+                yield ReadOnly()
+                if int(self.bus.readdatavalid):
+                    break
+                yield RisingEdge(self.clock)
+        else:
+            # Assume readLatency = 1 if no readdatavalid
+            # FIXME need to configure this,
+            # should take a dictionary of Avalon properties.
+            yield ReadOnly()
+
+        # Get the data
+        data = self.bus.readdata.value
 
         self._release_lock()
         raise ReturnValue(data)
@@ -196,6 +206,9 @@ def write(self, address, value):
             self.bus.byteenable <= 0
         if hasattr(self.bus, "cs"):
             self.bus.cs <= 0
+        v = self.bus.address.value
+        v.binstr = "x" * len(self.bus.address)
+        self.bus.address <= v
 
         v = self.bus.writedata.value
         v.binstr = "x" * len(self.bus.writedata)


Test patch:
Repository: cocotb/cocotb

Issue:
Memory leak
For simulations with large number of packets streaming in, the memory usage of the simulator seems to continuously grow.
This can be reproduced even in the endian_swapper testbench by increasing the packets to a very large number (300K).
I have a simulation which reads in a pcap which has 5Million messages and icarus seems to consume the whole memory by about 3 million packets.
Any workarounds for this memory leak?

-Ajesh


Discussion:
This does seem to be a problem. Just so you know you can run a test with the MEMCHECK=<port> set, then open a browser to localhost:<port>. This uses the dowser and cherrypy modules installable from pip. On the web page it shows the number of objects that are currently in use. If I increase the number of packets to 300000 as you suggest then I see ```__builtin__.dict``` increasing linearly as well as the ```builtin__.generator``` objects as well. I've not looked into if this is the test at fault, the scoreboard or the  coroutine scheduling engine. 
Hi Stuart. Thanks for the pointers. I will play around and see if I can find anything. Regards!

Resolving patch:
diff --git a/cocotb/scheduler.py b/cocotb/scheduler.py
--- a/cocotb/scheduler.py
+++ b/cocotb/scheduler.py
@@ -366,6 +366,7 @@ def unschedule(self, coro):
                 self._trigger2coros[trigger].remove(coro)
             if not self._trigger2coros[trigger]:
                 trigger.unprime()
+                del self._trigger2coros[trigger]
         del self._coro2triggers[coro]
 
         if coro._join in self._trigger2coros:


Test patch:
Repository: cocotb/cocotb

Issue:
Add documentation for the `utils` module.
The utils module includes some useful functions but is not mentioned in the documentation.  Would be nice  if it was included and if the reference documentation was more complete.


Discussion:

Resolving patch:
diff --git a/cocotb/monitors/__init__.py b/cocotb/monitors/__init__.py
--- a/cocotb/monitors/__init__.py
+++ b/cocotb/monitors/__init__.py
@@ -54,16 +54,28 @@ def __init__(self):
 
 
 class Monitor(object):
+    """Base class for Monitor objects. Monitors are passive 'listening' objects
+    that monitor pins in or out of a DUT. This class should not be used
+    directly, but should be subclassed and the internal `_monitor_recv` method
+    should be overridden and decorated as a @coroutine.  This `_monitor_recv`
+    method should capture some behavior of the pins, form a transaction, and
+    pass this transaction to the internal `_recv` method.  The `_monitor_recv`
+    method is added to the cocotb scheduler during the `__init__` phase, so it
+    should not be yielded anywhere.
+
+    The primary use of a Monitor is as an interface for a :Scoreboard:.
+
+    :type callback: callable
+    :param callback: Will be called with each recovered transaction as the
+    argument. If the callback isn't used, received transactions will be placed
+    on a queue and the event used to notify any consumers.
+
+    :type event: event
+    :param event: Object that supports a `set` method that will be called when
+    a transaction is received through the internal `_recv` method.
+    """
 
     def __init__(self, callback=None, event=None):
-        """
-        Constructor for a monitor instance
-
-        callback will be called with each recovered transaction as the argument
-
-        If the callback isn't used, received transactions will be placed on a
-        queue and the event used to notify any consumers.
-        """
         self._event = event
         self._wait_event = None
         self._recvQ = deque()
diff --git a/cocotb/scoreboard.py b/cocotb/scoreboard.py
--- a/cocotb/scoreboard.py
+++ b/cocotb/scoreboard.py
@@ -95,12 +95,12 @@ def compare(self, got, exp, log, strict_type=True):
         # Compare the types
         if strict_type and type(got) != type(exp):
             self.errors += 1
-            log.error("Received transaction is a different type to expected "
-                      "transaction")
-            log.info("Got: %s but expected %s" %
+            log.error("Received transaction type is different than expected")
+            log.info("Received: %s but expected %s" %
                      (str(type(got)), str(type(exp))))
             if self._imm:
-                raise TestFailure("Received transaction of wrong type")
+                raise TestFailure("Received transaction of wrong type. "
+                                  "Set strict_type=False to avoid this.")
             return
         # Or convert to a string before comparison
         elif not strict_type:


Test patch:
Repository: cocotb/cocotb

Issue:
Images missing from PDF version of docs
The PDF documentation (https://media.readthedocs.org/pdf/cocotb/latest/cocotb.pdf) does not include any images. This is because of the following error in the build process (e.g. https://readthedocs.org/api/v2/build/8287909.txt):
```
LaTeX Warning: File `{diagrams/svg/cocotb_overview}.*' not found on input line 
168.


! LaTeX Error: Unknown graphics extension: .*.
```
Adding the ``.svg`` extension is the first step toward making this work. In addition, it looks like we also need to enable the ``sphinx.ext.imgconverter`` extension (http://www.sphinx-doc.org/en/master/usage/extensions/imgconverter.html).

PR upcoming.


Discussion:

Resolving patch:
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -18,6 +18,10 @@
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
 sys.path.insert(0, os.path.abspath('../..'))
+
+# Add in-tree extensions to path
+sys.path.insert(0, os.path.abspath('../sphinxext'))
+
 os.environ["SPHINX_BUILD"] = "1"
 
 # -- General configuration -----------------------------------------------------
@@ -32,9 +36,10 @@
     'sphinx.ext.doctest', 
     'sphinx.ext.todo', 
     'sphinx.ext.coverage', 
-    'sphinx.ext.pngmath', 
+    'sphinx.ext.imgmath', 
     'sphinx.ext.viewcode',
     'sphinx.ext.napoleon',
+    'cairosvgconverter',
     ]
 
 # Add any paths that contain templates here, relative to this directory.
diff --git a/documentation/sphinxext/cairosvgconverter.py b/documentation/sphinxext/cairosvgconverter.py
new file mode 100644
--- /dev/null
+++ b/documentation/sphinxext/cairosvgconverter.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+"""
+"""
+from sphinx.errors import ExtensionError
+from sphinx.locale import _
+from sphinx.transforms.post_transforms.images import ImageConverter
+from sphinx.util import logging
+from sphinx.util.osutil import ENOENT, EPIPE, EINVAL
+from cairosvg import svg2pdf
+
+logger = logging.getLogger(__name__)
+
+class CairoSvgConverter(ImageConverter):
+    conversion_rules = [
+        ('image/svg+xml', 'application/pdf'),
+    ]
+
+    def is_available(self):
+        # type: () -> bool
+        return True
+
+    def convert(self, _from, _to):
+        # type: (unicode, unicode) -> bool
+        """Converts the image to expected one."""
+        svg2pdf(url=_from, write_to=_to)
+
+        return True
+
+
+def setup(app):
+    # type: (Sphinx) -> Dict[unicode, Any]
+    app.add_post_transform(CairoSvgConverter)
+
+    return {
+        'version': 'builtin',
+        'parallel_read_safe': True,
+        'parallel_write_safe': True,
+    }


Test patch:
Repository: cocotb/cocotb

Issue:
Waiting on an event that has already fired will hang forever
We just need to check that if we have already fired then return a NullTrigger()

[Need to modify this function](https://github.com/potentialventures/cocotb/blob/0bb751d5bb80f75e7a03284284f0d46caa209ee4/cocotb/triggers.py#L402)

```python
     def wait(self):
         """This can be yielded to block this coroutine
         until another wakes it"""
+        if self.fired:
+            return NullTrigger()
+
         return _Event(self)
```

Originally reported by @stuarthodgson 


Discussion:

Resolving patch:
diff --git a/cocotb/triggers.py b/cocotb/triggers.py
--- a/cocotb/triggers.py
+++ b/cocotb/triggers.py
@@ -401,7 +401,13 @@ def set(self, data=None):
 
     def wait(self):
         """This can be yielded to block this coroutine
-        until another wakes it"""
+        until another wakes it
+
+        If the Event has already been fired, this returns NullTrigger()
+        To reset the event (and enable the use of wait() again), clear() should be called
+        """
+        if self.fired:
+            return NullTrigger()
         return _Event(self)
 
     def clear(self):


Test patch:
Repository: cocotb/cocotb

Issue:
Use sphinxcontrib-trio to document coroutines
It looks like https://sphinxcontrib-trio.readthedocs.io/ could help autodoc'ing our coroutines nicer. 


Discussion:

Resolving patch:
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -41,6 +41,7 @@
     'sphinx.ext.napoleon',
     'sphinx.ext.intersphinx',
     'cairosvgconverter',
+    'sphinxcontrib_trio',
     ]
 
 intersphinx_mapping = {'https://docs.python.org/3': None}


Test patch:
Repository: cocotb/cocotb

Issue:
Tab completion broken in newer IPython versions
In recent IPython versions, tab completion has changed. cocotb uses ``_getAttributeNames`` to allow completing DUT object names but this has been removed in https://github.com/ipython/ipython/pull/8081/files.

These days, providing ``__dir__(self)`` is the way to go (https://ipython.readthedocs.io/en/stable/config/integrating.html). I'll prepare a PR.


Discussion:

Resolving patch:
diff --git a/cocotb/handle.py b/cocotb/handle.py
--- a/cocotb/handle.py
+++ b/cocotb/handle.py
@@ -215,10 +215,10 @@ def _sub_handle_key(self, name):
         """Translates the handle name to a key to use in ``_sub_handles`` dictionary."""
         return name.split(".")[-1]
 
-    def _getAttributeNames(self):
+    def __dir__(self):
         """Permits IPython tab completion to work."""
         self._discover_all()
-        return dir(self)
+        return super(RegionObject, self).__dir__() + [str(k) for k in self._sub_handles]
 
 
 class HierarchyObject(RegionObject):


Test patch:
diff --git a/tests/test_cases/test_discovery/test_discovery.py b/tests/test_cases/test_discovery/test_discovery.py
--- a/tests/test_cases/test_discovery/test_discovery.py
+++ b/tests/test_cases/test_discovery/test_discovery.py
@@ -27,6 +27,8 @@
 
 import cocotb
 import logging
+import os
+import textwrap
 from cocotb.triggers import Timer
 from cocotb.result import TestError, TestFailure
 from cocotb.handle import IntegerObject, ConstantObject, HierarchyObject
@@ -60,7 +62,25 @@ def ipython_embed(dut):
     IPython.embed()
 
 
+@cocotb.test(skip=True)
+def ipython_embed_kernel(dut):
+    """Start an interactive Python shell."""
+    yield Timer(0)
+    import IPython
+    print(textwrap.dedent("""
+    ###############################################################################
+    Running IPython embed_kernel()
+
+    You can now send this process into the background with "Ctrl-Z bg" and run
+        jupyter console --existing
+    or
+        jupyter qtconsole --existing
+    or
+        jupyter console --existing kernel-{}.json
+    ###############################################################################""".format(os.getpid())))
+    IPython.embed_kernel()
 
+    
 @cocotb.test(expect_error=True)
 def discover_value_not_in_dut(dut):
     """Try and get a value from the DUT that is not there"""
Repository: cocotb/cocotb

Issue:
Fix docs for async/await in coroutines doc
The new documentation for async has a couple issues:

- a non-inline link in rst isn't displayed: https://cocotb.readthedocs.io/en/latest/coroutines.html (at the bottom of the page, "More details on this type of generator can be found in `PEP 525`_.")
- `python3` should be used instead of `python` in the code examples to make sure that keywords like `await` get highlighted properly.
- the note block is broken.


Discussion:

Resolving patch:
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -113,7 +113,24 @@
 
 # The theme to use for HTML and HTML Help pages.  See the documentation for
 # a list of builtin themes.
-html_theme = 'default'
+
+# The Read the Docs theme is available from
+# https://github.com/snide/sphinx_rtd_theme
+#
+# Install with
+# - pip install sphinx_rtd_theme
+# or
+# - apt-get install python-sphinx-rtd-theme
+
+try:
+    import sphinx_rtd_theme
+    html_theme = 'sphinx_rtd_theme'
+except ImportError:
+    sys.stderr.write('Warning: The Sphinx \'sphinx_rtd_theme\' HTML theme was '+
+        'not found. Make sure you have the theme installed to produce pretty '+
+        'HTML output. Falling back to the default theme.\n')
+
+    html_theme = 'default'
 
 # Theme options are theme-specific and customize the look and feel of a theme
 # further.  For a list of options available for each theme, see the


Test patch: