utils: Running autoformatter over code.

Not doing rr_graph lib because of #94.

Signed-off-by: Tim 'mithro' Ansell <me@mith.ro>
diff --git a/v2x/lib/argparse_extra.py b/v2x/lib/argparse_extra.py
index b8a98ae..76657f5 100644
--- a/v2x/lib/argparse_extra.py
+++ b/v2x/lib/argparse_extra.py
@@ -1,5 +1,6 @@
 import argparse
 
+
 class ActionStoreBool(argparse.Action):
     """Convert a string argument into a boolean.
 
@@ -51,17 +52,32 @@
         * f
         * 0
     """
-    def __init__(self, option_strings, dest, default=None, required=False, help=None, metavar=None):
+
+    def __init__(self,
+                 option_strings,
+                 dest,
+                 default=None,
+                 required=False,
+                 help=None,
+                 metavar=None):
         self.orig_option_strings = option_strings
         new_option_strings = []
         for s in option_strings:
             assert s.startswith("--"), s
             new_option_strings.append(s)
-            new_option_strings.append("--no-"+s[2:])
+            new_option_strings.append("--no-" + s[2:])
         argparse.Action.__init__(
-            self, new_option_strings, dest=dest, nargs='?', const=[True],
-            default=default, type=self.value, choices=None, required=required,
-            help=help, metavar=metavar)
+            self,
+            new_option_strings,
+            dest=dest,
+            nargs='?',
+            const=[True],
+            default=default,
+            type=self.value,
+            choices=None,
+            required=required,
+            help=help,
+            metavar=metavar)
 
     def value(self, s):
         if not s:
@@ -82,7 +98,8 @@
         setattr(namespace, self.dest, values[0])
 
     def __repr__(self):
-        return "ActionStoreBool({}, {})".format(self.orig_option_strings, self.default)
+        return "ActionStoreBool({}, {})".format(self.orig_option_strings,
+                                                self.default)
 
 
 if __name__ == "__main__":
diff --git a/v2x/lib/asserts.py b/v2x/lib/asserts.py
index 008fbf3..644fadb 100644
--- a/v2x/lib/asserts.py
+++ b/v2x/lib/asserts.py
@@ -5,36 +5,48 @@
     except Exception as e:
         return "{}@{}({})".format(a.__class__.__name__, id(a), e)
 
+
 def __safe_error(msg, a, b):
     """Generate the error message for assert_XX without causing an error."""
     return "{} ({}) {} {} ({})".format(
-        __safe_call(str, a), __safe_call(repr, a),
+        __safe_call(str, a),
+        __safe_call(repr, a),
         msg,
-        __safe_call(str, b), __safe_call(repr, b),
+        __safe_call(str, b),
+        __safe_call(repr, b),
     )
 
+
 def assert_eq(a, b):
     """Assert equal with better error message."""
     assert a == b, __safe_error("!=", a, b)
 
+
 def assert_is(a, b):
     """Assert is with better error message."""
     assert a is b, __safe_error("is not", a, b)
 
-def assert_type(obj, cls, msg="{obj} ({obj!r}) should be a {cls}, not {objcls}"):
+
+def assert_type(obj,
+                cls,
+                msg="{obj} ({obj!r}) should be a {cls}, not {objcls}"):
     """Raise a type error if obj is not an instance of cls."""
     if not isinstance(obj, cls):
         raise TypeError(msg.format(obj=obj, objcls=type(obj), cls=cls))
 
+
 def assert_type_or_none(obj, classes):
     """Raise a type error if obj is not an instance of cls or None."""
     if obj is not None:
         assert_type(obj, classes)
 
+
 def assert_len_eq(l):
     """Check all lists in a list are equal length"""
     # Sanity check
     max_len = max(len(p) for p in l)
     for i, p in enumerate(l):
-        assert len(p) == max_len, "Length check failed!\nl[{}] has {} elements != {} ({!r})\n{!r}".format(
+        assert len(
+            p
+        ) == max_len, "Length check failed!\nl[{}] has {} elements != {} ({!r})\n{!r}".format(
             i, len(p), max_len, p, l)
diff --git a/v2x/lib/mux.py b/v2x/lib/mux.py
index 9dc339b..4328313 100644
--- a/v2x/lib/mux.py
+++ b/v2x/lib/mux.py
@@ -27,7 +27,7 @@
 
 
 class MuxType(Enum):
-    LOGIC   = 'BEL_MX'
+    LOGIC = 'BEL_MX'
     ROUTING = 'BEL_RX'
 
 
@@ -42,7 +42,8 @@
         elif self == self.OUTPUT:
             return "output wire"
         else:
-            raise TypeError("Can't convert {} into verilog definition.".format(self))
+            raise TypeError(
+                "Can't convert {} into verilog definition.".format(self))
 
     def direction(self):
         if self in (self.INPUT, self.SELECT):
@@ -50,7 +51,8 @@
         elif self == self.OUTPUT:
             return "output"
         else:
-            raise TypeError("Can't convert {} into verilog definition.".format(self))
+            raise TypeError(
+                "Can't convert {} into verilog definition.".format(self))
 
     def __str__(self):
         return self.value
@@ -85,31 +87,36 @@
     xml.etree.ElementTree
         pb_type.xml for requested mux
     """
-    assert isinstance(comment, str), "{} {}".format(type(comment), repr(comment))
+    assert isinstance(comment, str), "{} {}".format(
+        type(comment), repr(comment))
 
     if mux_type == MuxType.LOGIC:
         if '-' not in mux_name:
-            mux_name = 'BEL_MX-'+mux_name
+            mux_name = 'BEL_MX-' + mux_name
         else:
-            assert mux_name.startswith('BEL_MX-'), "Provided mux name has type {} but not BEL_MX!".format(mux_name)
+            assert mux_name.startswith(
+                'BEL_MX-'
+            ), "Provided mux name has type {} but not BEL_MX!".format(mux_name)
     elif mux_type == MuxType.ROUTING:
         if '-' not in mux_name:
-            mux_name = 'BEL_RX-'+mux_name
+            mux_name = 'BEL_RX-' + mux_name
         else:
-            assert mux_name.startswith('BEL_RX-'), "Provided mux name has type {} but not BEL_MX!".format(mux_name)
+            assert mux_name.startswith(
+                'BEL_RX-'
+            ), "Provided mux name has type {} but not BEL_MX!".format(mux_name)
     else:
         assert False, "Unknown type {}".format(mux_type)
 
-    pb_type_xml = ET.Element(
-        'pb_type', {
-            'name': mux_name,
-            'num_pb': str(num_pb),
-        })
+    pb_type_xml = ET.Element('pb_type', {
+        'name': mux_name,
+        'num_pb': str(num_pb),
+    })
 
     if mux_type == MuxType.LOGIC:
         pb_type_xml.attrib['blif_model'] = '.subckt %s' % subckt
     else:
-        assert not subckt, "Provided subckt={} for non-logic mux!".format(subckt)
+        assert not subckt, "Provided subckt={} for non-logic mux!".format(
+            subckt)
 
     if comment is not None:
         pb_type_xml.append(ET.Comment(comment))
@@ -122,7 +129,10 @@
         ET.SubElement(
             pb_type_xml,
             pin_type.direction(),
-            {'name': pin_name, 'num_pins': str(pin_width)},
+            {
+                'name': pin_name,
+                'num_pins': str(pin_width)
+            },
         )
 
     if mux_type == MuxType.LOGIC:
@@ -131,12 +141,13 @@
                 continue
 
             for opin_type, opin_name, opin_width, opin_index in pins:
-                if opin_type not in (MuxPinType.OUTPUT,):
+                if opin_type not in (MuxPinType.OUTPUT, ):
                     continue
 
                 ET.SubElement(
                     pb_type_xml,
-                    'delay_constant', {
+                    'delay_constant',
+                    {
                         'max': "10e-12",
                         'in_port': "%s.%s" % (mux_name, ipin_name),
                         'out_port': "%s.%s" % (mux_name, opin_name),
@@ -145,14 +156,21 @@
     elif mux_type == MuxType.ROUTING:
         interconnect = ET.SubElement(pb_type_xml, 'interconnect')
 
-        inputs  = ["{}.{}".format(mux_name, n) for t, n, _, _ in pins if t in (MuxPinType.INPUT,)]
-        outputs = ["{}.{}".format(mux_name, n) for t, n, _, _ in pins if t in (MuxPinType.OUTPUT,)]
+        inputs = [
+            "{}.{}".format(mux_name, n) for t, n, _, _ in pins
+            if t in (MuxPinType.INPUT, )
+        ]
+        outputs = [
+            "{}.{}".format(mux_name, n) for t, n, _, _ in pins
+            if t in (MuxPinType.OUTPUT, )
+        ]
         assert len(outputs) == 1
 
         ET.SubElement(
             interconnect,
-            'mux', {
-                'name': '%s' % (mux_name,),
+            'mux',
+            {
+                'name': '%s' % (mux_name, ),
                 'input': " ".join(inputs),
                 'output': outputs[0],
             },
diff --git a/v2x/mux_gen.py b/v2x/mux_gen.py
index 905caf0..4eddbc8 100755
--- a/v2x/mux_gen.py
+++ b/v2x/mux_gen.py
@@ -22,81 +22,99 @@
 parser = argparse.ArgumentParser(
     description='Generate a MUX wrapper.',
     fromfile_prefix_chars='@',
-    prefix_chars='-~'
-)
+    prefix_chars='-~')
 
 parser.add_argument(
-    '--verbose', '--no-verbose',
-    action=ActionStoreBool, default=os.environ.get('V', '')=='1',
+    '--verbose',
+    '--no-verbose',
+    action=ActionStoreBool,
+    default=os.environ.get('V', '') == '1',
     help="Print lots of information about the generation.")
 
-parser.add_argument(
-    '--width', type=int, default=8,
-    help="Width of the MUX.")
+parser.add_argument('--width', type=int, default=8, help="Width of the MUX.")
 
 parser.add_argument(
-    '--type', choices=['logic', 'routing'],
+    '--type',
+    choices=['logic', 'routing'],
     default='logic',
     help="Type of MUX.")
 
 parser.add_argument(
     '--split-inputs',
-    action=ActionStoreBool, default=False,
+    action=ActionStoreBool,
+    default=False,
     help="Split the inputs into separate signals")
 
 parser.add_argument(
     '--split-selects',
-    action=ActionStoreBool, default=False,
+    action=ActionStoreBool,
+    default=False,
     help="Split the selects into separate signals")
 
 parser.add_argument(
-    '--name-mux', type=str, default='MUX',
-    help="Name of the mux.")
+    '--name-mux', type=str, default='MUX', help="Name of the mux.")
 
 parser.add_argument(
-    '--name-input', type=str, default='I',
+    '--name-input',
+    type=str,
+    default='I',
     help="Name of the input values for the mux.")
 
 parser.name_inputs = parser.add_argument(
-    '--name-inputs', type=str, default=None,
-    help="Comma deliminator list for the name of each input to the mux (implies --split-inputs).")
+    '--name-inputs',
+    type=str,
+    default=None,
+    help=
+    "Comma deliminator list for the name of each input to the mux (implies --split-inputs)."
+)
 
 parser.add_argument(
-    '--name-output', type=str, default='O',
+    '--name-output',
+    type=str,
+    default='O',
     help="Name of the output value for the mux.")
 
 parser.add_argument(
-    '--name-select', type=str, default='S',
+    '--name-select',
+    type=str,
+    default='S',
     help="Name of the select parameter for the mux.")
 
 parser.name_selects = parser.add_argument(
-    '--name-selects', type=str, default=None,
-    help="Comma deliminator list for the name of each select to the mux (implies --split-selects).")
+    '--name-selects',
+    type=str,
+    default=None,
+    help=
+    "Comma deliminator list for the name of each select to the mux (implies --split-selects)."
+)
 
 parser.add_argument(
-    '--order', choices=[''.join(x) for x in itertools.permutations('ios')]+[''.join(x) for x in itertools.permutations('io')],
+    '--order',
+    choices=[''.join(x) for x in itertools.permutations('ios')] +
+    [''.join(x) for x in itertools.permutations('io')],
     default='iso',
-    help="""Order of the arguments for the MUX. (i - Inputs, o - Output, s - Select)""")
+    help=
+    """Order of the arguments for the MUX. (i - Inputs, o - Output, s - Select)"""
+)
 
 parser.add_argument(
-    '--outdir', default=None,
+    '--outdir',
+    default=None,
     help="""Directory to output generated content too.""")
 
 parser.add_argument(
-    '--outfilename', default=None,
+    '--outfilename',
+    default=None,
     help="""Filename to output generated content too.""")
 
 parser.add_argument(
-    '--comment', default=None,
-    help="""Add some type of comment to the mux.""")
+    '--comment', default=None, help="""Add some type of comment to the mux.""")
 
 parser.add_argument(
-    '--num_pb', default=1,
-    help="""Set the num_pb for the mux.""")
+    '--num_pb', default=1, help="""Set the num_pb for the mux.""")
 
 parser.add_argument(
-    '--subckt', default=None,
-    help="""Override the subcircuit name.""")
+    '--subckt', default=None, help="""Override the subcircuit name.""")
 
 
 def main(argv):
@@ -107,11 +125,11 @@
     def output_block(name, s):
         if args.verbose:
             print()
-            print(name, '-'*(75-(len(name)+1)))
+            print(name, '-' * (75 - (len(name) + 1)))
             print(s, end="")
             if s[-1] != '\n':
                 print()
-            print('-'*75)
+            print('-' * 75)
 
     args.width_bits = mux_lib.clog2(args.width)
 
@@ -134,7 +152,8 @@
     mypath = normpath(mypath, to=outdir)
     mux_dir = normpath(os.path.join(mydir, '..', 'vpr', 'muxes'), to=outdir)
     buf_dir = normpath(os.path.join(mydir, '..', 'vpr', 'buf'), to=outdir)
-    mux_mk = normpath(os.path.join(mydir, '..', 'common', 'make', 'mux.mk'), to=outdir)
+    mux_mk = normpath(
+        os.path.join(mydir, '..', 'common', 'make', 'mux.mk'), to=outdir)
 
     if args.name_inputs:
         assert_eq(args.name_input, parser.get_default("name_input"))
@@ -142,10 +161,13 @@
         args.split_inputs = True
 
         names = args.name_inputs.split(',')
-        assert len(names) == args.width, "%s input names, but %s needed." % (names, args.width)
+        assert len(names) == args.width, "%s input names, but %s needed." % (
+            names, args.width)
         args.name_inputs = names
     elif args.split_inputs:
-        args.name_inputs = [args.name_input+str(i) for i in range(args.width)]
+        args.name_inputs = [
+            args.name_input + str(i) for i in range(args.width)
+        ]
         parser.name_inputs.default = args.name_inputs
         assert_eq(parser.get_default("name_inputs"), args.name_inputs)
 
@@ -155,10 +177,14 @@
         args.split_selects = True
 
         names = args.name_selects.split(',')
-        assert len(names) == args.width_bits, "%s select names, but %s needed." % (names, args.width_bits)
+        assert len(
+            names) == args.width_bits, "%s select names, but %s needed." % (
+                names, args.width_bits)
         args.name_selects = names
     elif args.split_selects:
-        args.name_selects = [args.name_select+str(i) for i in range(args.width_bits)]
+        args.name_selects = [
+            args.name_select + str(i) for i in range(args.width_bits)
+        ]
         parser.name_selects.default = args.name_selects
         assert_eq(parser.get_default("name_selects"), args.name_selects)
 
@@ -186,7 +212,9 @@
     pbtype_xml_filename = '%s.pb_type.xml' % args.outfilename
     sim_filename = '%s.sim.v' % args.outfilename
 
-    output_files = [model_xml_filename, pbtype_xml_filename, sim_filename, 'Makefile.mux']
+    output_files = [
+        model_xml_filename, pbtype_xml_filename, sim_filename, 'Makefile.mux'
+    ]
     commit_files = ["Makefile.mux"]
     remove_files = [f for f in output_files if f not in commit_files]
 
@@ -207,7 +235,9 @@
         if args.split_inputs:
             print("MUX_SPLIT_INPUTS = 1", file=f)
             if args.name_inputs != parser.get_default('name_inputs'):
-                print("MUX_INPUTS = {}".format(",".join(args.name_inputs)), file=f)
+                print(
+                    "MUX_INPUTS = {}".format(",".join(args.name_inputs)),
+                    file=f)
         else:
             if args.name_input != parser.get_default('name_input'):
                 print("MUX_INPUT = {}".format(args.name_input), file=f)
@@ -215,7 +245,9 @@
         if args.split_selects:
             print("MUX_SPLIT_SELECTS = 1", file=f)
             if args.name_selects != parser.get_default('name_selects'):
-                print("MUX_SELECTS = {}".format(",".join(args.name_selects)), file=f)
+                print(
+                    "MUX_SELECTS = {}".format(",".join(args.name_selects)),
+                    file=f)
         else:
             if args.name_select != parser.get_default('name_select'):
                 print("MUX_SELECT = {}".format(args.name_select), file=f)
@@ -248,19 +280,27 @@
     for i in args.order:
         if i == 'i':
             if args.split_inputs:
-                port_names.extend((mux_lib.MuxPinType.INPUT, args.name_inputs[j], 1, '[%i]' % j) for j in range(args.width))
+                port_names.extend((mux_lib.MuxPinType.INPUT,
+                                   args.name_inputs[j], 1, '[%i]' % j)
+                                  for j in range(args.width))
             else:
                 # verilog range bounds are inclusive and convention is [<width-1>:0]
-                port_names.append((mux_lib.MuxPinType.INPUT, args.name_input, args.width, '[%i:0]' % (args.width - 1)))
+                port_names.append((mux_lib.MuxPinType.INPUT, args.name_input,
+                                   args.width, '[%i:0]' % (args.width - 1)))
         elif i == 's':
             if args.split_selects:
-                port_names.extend((mux_lib.MuxPinType.SELECT, args.name_selects[j], 1, '[%i]' % j) for j in range(args.width_bits))
+                port_names.extend((mux_lib.MuxPinType.SELECT,
+                                   args.name_selects[j], 1, '[%i]' % j)
+                                  for j in range(args.width_bits))
             else:
                 assert args.name_select is not None
                 # verilog array range bounds are inclusive and convention is [<width-1>:0]
-                port_names.append((mux_lib.MuxPinType.SELECT, args.name_select, args.width_bits, '[%i:0]' % (args.width_bits - 1)))
+                port_names.append(
+                    (mux_lib.MuxPinType.SELECT, args.name_select,
+                     args.width_bits, '[%i:0]' % (args.width_bits - 1)))
         elif i == 'o':
-            port_names.append((mux_lib.MuxPinType.OUTPUT, args.name_output, 1, ''))
+            port_names.append((mux_lib.MuxPinType.OUTPUT, args.name_output, 1,
+                               ''))
 
     # ------------------------------------------------------------------------
     # Generate the sim.v Verilog module
@@ -283,9 +323,12 @@
         f.write("\n * ".join(generated_with.splitlines()))
         f.write("\n */\n\n")
         f.write('`include "%s/%s/%smux%i/%smux%i.sim.v"\n' % (
-            mux_dir, 'logic',
-            '', args.width,
-            '', args.width,
+            mux_dir,
+            'logic',
+            '',
+            args.width,
+            '',
+            args.width,
         ))
         f.write("\n")
         f.write('(* blackbox *) (* CLASS="%s" *)\n' % mux_class)
@@ -314,7 +357,7 @@
             for type, name, width, index in port_names:
                 if type != mux_lib.MuxPinType.INPUT:
                     continue
-                if j+width <= i:
+                if j + width <= i:
                     j += width
                     continue
                 break
@@ -322,14 +365,14 @@
             if width == 1:
                 f.write('\t\t.I%i(%s),\n' % (i, name))
             else:
-                f.write('\t\t.I%i(%s[%i]),\n' % (i, name, i-j))
+                f.write('\t\t.I%i(%s[%i]),\n' % (i, name, i - j))
 
         for i in range(0, args.width_bits):
             j = 0
             for type, name, width, index in port_names:
                 if type != mux_lib.MuxPinType.SELECT:
                     continue
-                if j+width < i:
+                if j + width < i:
                     j += width
                     continue
                 break
@@ -337,13 +380,13 @@
             if width == 1:
                 f.write('\t\t.S%i(%s),\n' % (i, name))
             else:
-                f.write('\t\t.S%i(%s[%i]),\n' % (i, name, i-j))
+                f.write('\t\t.S%i(%s[%i]),\n' % (i, name, i - j))
 
         for type, name, width, index in port_names:
             if type != mux_lib.MuxPinType.OUTPUT:
                 continue
             break
-        assert_eq(width ,  1)
+        assert_eq(width, 1)
         f.write('\t\t.O(%s)\n\t);\n' % name)
 
         f.write('endmodule\n')
@@ -361,8 +404,7 @@
     # Generate the Model XML form.
     # ------------------------------------------------------------------------
     def xml_comment_indent(n, s):
-        return ("\n"+" "*n).join(s.splitlines()+[""])
-
+        return ("\n" + " " * n).join(s.splitlines() + [""])
 
     if args.type == 'logic':
         models_xml = ET.Element('models')
@@ -376,10 +418,13 @@
             if type in (mux_lib.MuxPinType.INPUT, mux_lib.MuxPinType.SELECT):
                 ET.SubElement(
                     input_ports, 'port', {
-                        'name': name,
-                        'combinational_sink_ports': ','.join(n for t, n, w, i in port_names if t in (mux_lib.MuxPinType.OUTPUT,)),
+                        'name':
+                        name,
+                        'combinational_sink_ports':
+                        ','.join(n for t, n, w, i in port_names
+                                 if t in (mux_lib.MuxPinType.OUTPUT, )),
                     })
-            elif type in (mux_lib.MuxPinType.OUTPUT,):
+            elif type in (mux_lib.MuxPinType.OUTPUT, ):
                 ET.SubElement(output_ports, 'port', {'name': args.name_output})
 
         models_str = ET.tostring(models_xml, pretty_print=True).decode('utf-8')