More refactoring and general fixes, including of module types

Signed-off-by: David Shah <davey1576@gmail.com>
diff --git a/tests/adder/pb_type.xml b/tests/adder/pb_type.xml
index e675790..f14d676 100644
--- a/tests/adder/pb_type.xml
+++ b/tests/adder/pb_type.xml
@@ -1,10 +1,9 @@
-<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="adder" num_pb="1">
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" blif_model=".subckt adder" name="adder" num_pb="1">
   <input equivalent="false" name="a" num_pins="1"/>
   <input equivalent="false" name="b" num_pins="1"/>
   <input equivalent="false" name="ci" num_pins="1"/>
   <output equivalent="false" name="y" num_pins="1"/>
   <output equivalent="false" name="co" num_pins="1"/>
-  <interconnect/>
   <delay_constant in_port="adder.a" max="20e-12" out_port="adder.y"/>
   <delay_constant in_port="adder.b" max="20e-12" out_port="adder.y"/>
   <delay_constant in_port="adder.ci" max="10e-12" out_port="adder.y"/>
diff --git a/tests/adder/sim.v b/tests/adder/sim.v
index 2d9be56..3411e3e 100644
--- a/tests/adder/sim.v
+++ b/tests/adder/sim.v
@@ -1,3 +1,4 @@
+(* blackbox *)
 module adder(
 	input a,
 	input b,
diff --git a/tests/dff/model.xml b/tests/dff/model.xml
index f8b4458..07cce64 100644
--- a/tests/dff/model.xml
+++ b/tests/dff/model.xml
@@ -2,7 +2,6 @@
   <model name="dff">
     <input_ports>
       <port is_clock="1" name="clk"/>
-      <port clock="clk" name="rst"/>
       <port clock="clk" name="d"/>
     </input_ports>
     <output_ports>
diff --git a/tests/dff/pb_type.xml b/tests/dff/pb_type.xml
index 7d63821..5d80b66 100644
--- a/tests/dff/pb_type.xml
+++ b/tests/dff/pb_type.xml
@@ -1,11 +1,7 @@
 <pb_type xmlns:xi="http://www.w3.org/2001/XInclude" blif_model=".latch" class="flipflop" name="dff" num_pb="1">
   <clock equivalent="false" name="clk" num_pins="1" port_class="clock"/>
-  <input equivalent="false" name="rst" num_pins="1"/>
   <input equivalent="false" name="d" num_pins="1" port_class="D"/>
   <output equivalent="false" name="q" num_pins="1" port_class="Q"/>
-  <interconnect/>
-  <T_setup clock="clk" port="dff.rst" value="200e-12"/>
-  <T_hold clock="clk" port="dff.rst" value="50e-12"/>
   <T_setup clock="clk" port="dff.d" value="200e-12"/>
   <T_hold clock="clk" port="dff.d" value="50e-12"/>
   <T_clock_to_Q clock="clk" max="400e-12" port="dff.q"/>
diff --git a/tests/dff/sim.v b/tests/dff/sim.v
index bb464c6..e2ae093 100644
--- a/tests/dff/sim.v
+++ b/tests/dff/sim.v
@@ -1,12 +1,9 @@
-(* TYPE="bel" *) (* CLASS="flipflop" *)
-module dff(clk, rst, d, q);
+(* blackbox *) (* CLASS="flipflop" *)
+module dff(clk, d, q);
 
 (* PORT_CLASS = "clock" *)
 input wire clk;
 
-(* SETUP = "clk 200e-12" *) (* HOLD = "clk 50e-12" *)
-input wire rst;
-
 (* PORT_CLASS = "D" *) (* SETUP = "clk 200e-12" *) (* HOLD = "clk 50e-12" *)
 input wire d;
 
@@ -14,9 +11,6 @@
 output wire q;
 
 always @(posedge clk)
-	if (rst == 1'b1)
-		q <= 1'b0;
-	else
 		q <= d;
 
 endmodule
diff --git a/tests/lut2/model.xml b/tests/lut2/model.xml
index f062f9f..6c721c2 100644
--- a/tests/lut2/model.xml
+++ b/tests/lut2/model.xml
@@ -5,7 +5,6 @@
     </input_ports>
     <output_ports>
       <port name="y"/>
-      <port name="co"/>
     </output_ports>
   </model>
 </models>
diff --git a/tests/lut2/pb_type.xml b/tests/lut2/pb_type.xml
index 953d8f3..8c11624 100644
--- a/tests/lut2/pb_type.xml
+++ b/tests/lut2/pb_type.xml
@@ -1,8 +1,6 @@
-<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="lut2" num_pb="1">
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" blif_model=".subckt lut2" name="lut2" num_pb="1">
   <input equivalent="false" name="in" num_pins="2"/>
   <output equivalent="false" name="y" num_pins="1"/>
-  <output equivalent="false" name="co" num_pins="1"/>
-  <interconnect/>
   <delay_matrix in_port="lut2.in" out_port="lut2.y" type="max">
 10e-12
  10e-12
diff --git a/tests/lut2/sim.v b/tests/lut2/sim.v
index 34c235d..e7f9760 100644
--- a/tests/lut2/sim.v
+++ b/tests/lut2/sim.v
@@ -1,9 +1,9 @@
+(* blackbox *)
 module lut2 (
 		input [1:0] in,
+
 		(* DELAY_MATRIX_in = "10e-12; 10e-12" *)
-		output y,
-		output co);
+		output y);
 parameter [3:0] content = 4'b1000;
 assign y = content[in];
-assign co = 1'b0;
 endmodule
diff --git a/tests/model.xml b/tests/model.xml
index a1985e3..5bbe083 100644
--- a/tests/model.xml
+++ b/tests/model.xml
@@ -2,7 +2,6 @@
   <model name="test_pb">
     <input_ports>
       <port name="clk"/>
-      <port name="rst"/>
       <port name="a"/>
       <port name="b"/>
       <port name="ci"/>
diff --git a/tests/pb_type.xml b/tests/pb_type.xml
index 83bcaf3..b733dce 100644
--- a/tests/pb_type.xml
+++ b/tests/pb_type.xml
@@ -1,6 +1,5 @@
 <pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="test_pb" num_pb="1">
   <input equivalent="false" name="clk" num_pins="1"/>
-  <input equivalent="false" name="rst" num_pins="1"/>
   <input equivalent="false" name="a" num_pins="1"/>
   <input equivalent="false" name="b" num_pins="1"/>
   <input equivalent="false" name="ci" num_pins="1"/>
@@ -16,7 +15,6 @@
       <direct input="adder.co" name="test_add_co" output="test_add.co"/>
       <direct input="test_add.clk" name="dff_clk" output="dff.clk"/>
       <direct input="adder.y" name="dff_d" output="dff.d"/>
-      <direct input="test_add.rst" name="dff_rst" output="dff.rst"/>
       <direct input="dff.q" name="test_add_q" output="test_add.q"/>
     </interconnect>
   </mode>
@@ -26,11 +24,9 @@
     <interconnect>
       <direct input="test_lut.clk" name="dff_clk" output="dff.clk"/>
       <direct input="lut2.y" name="dff_d" output="dff.d"/>
-      <direct input="test_lut.rst" name="dff_rst" output="dff.rst"/>
       <direct input="dff.q" name="test_lut_q" output="test_lut.q"/>
-      <direct input="test_lut.a" name="lut2_in[2]" output="lut2.in[2]"/>
-      <direct input="test_lut.b" name="lut2_in[2]" output="lut2.in[2]"/>
-      <direct input="lut2.co" name="test_lut_co" output="test_lut.co"/>
+      <direct input="test_lut.a" name="lut2_in_0" output="lut2.in[0]"/>
+      <direct input="test_lut.b" name="lut2_in_1" output="lut2.in[1]"/>
     </interconnect>
   </mode>
 </pb_type>
diff --git a/tests/sim.v b/tests/sim.v
index ed6ceff..1151952 100644
--- a/tests/sim.v
+++ b/tests/sim.v
@@ -4,23 +4,23 @@
 
 
 (* blackbox *)
-module test_pb(input clk, rst, a, b, ci, output q, co);
+module test_pb(input clk, a, b, ci, output q, co);
 endmodule
 
 (* ALTERNATIVE_TO="test_pb" *)
-module test_add(input clk, rst, a, b, ci, output q, co);
+module test_add(input clk, a, b, ci, output q, co);
 
 wire d;
 adder adder_i(.a(a), .b(b), .ci(ci), .y(d), .co(co));
-dff dff_i(.clk(clk), .rst(rst), .d(d), .q(q));
+dff dff_i(.clk(clk), .d(d), .q(q));
 
 endmodule
 
 (* ALTERNATIVE_TO="test_pb" *)
-module test_lut(input clk, rst, a, b, ci, output q, co);
+module test_lut(input clk, a, b, ci, output q, co);
 
 wire d;
-lut2 lut2_i(.in({b, a}), .y(d), .co(co));
-dff dff_i(.clk(clk), .rst(rst), .d(d), .q(q));
+lut2 lut2_i(.in({b, a}), .y(d));
+dff dff_i(.clk(clk), .d(d), .q(q));
 
 endmodule
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index 11ee815..9298604 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -99,49 +99,54 @@
     def make_direct_conn(ic_xml, source, dest):
         source_pin = get_full_pin_name(source)
         dest_pin = get_full_pin_name(dest)
-        ic_name = dest_pin.replace(".","_")
+        ic_name = dest_pin.replace(".","_").replace("[","_").replace("]","")
         dir_xml = ET.SubElement(ic_xml, 'direct', {
             'name': ic_name,
             'input': source_pin,
             'output': dest_pin
         })
+    # Find out whether or not the module we are generating content for is a blackbox
+    is_blackbox = (mod.attr("blackbox", 0) == 1)
+
     # List of entries in format ((from_cell, from_pin), (to_cell, to_pin))
     interconn = []
 
-    # Process cells. First build the list of cnames.
-    for cname, i_of in mod.cells:
-        pb_name = i_of
-        module_path = os.path.dirname(yj.get_module_file(i_of))
-        pb_type_path = "%s/pb_type.xml" % module_path
-        include_xml(xml_parent, pb_type_path)
-        # In order to avoid overspecifying interconnect, there are two directions we currently
-        # consider. All interconnect going INTO a cell, and interconnect going out of a cell
-        # into a top level output - or all outputs if "mode" is used.
-        inp_cons = mod.cell_conns(cname, "input")
-        for pin, net in inp_cons:
-            drvs = mod.net_drivers(net)
-            if len(drvs) == 0:
-                print("ERROR: pin %s.%s has no driver, interconnect will be missing" % (pb_name, pin))
-                assert False
-            elif len(drvs) > 1:
-                print("ERROR: pin %s.%s has multiple drivers, interconnect will be overspecified" % (pb_name, pin))
-                assert False
-            for drv_cell, drv_pin in drvs:
-                interconn.append(((drv_cell, drv_pin), (cname, pin)))
+    # Blackbox modules don't have inner cells or interconnect (but do still have timing)
+    if not is_blackbox:
+        # Process cells. First build the list of cnames.
+        for cname, i_of in mod.cells:
+            pb_name = i_of
+            module_path = os.path.dirname(yj.get_module_file(i_of))
+            pb_type_path = "%s/pb_type.xml" % module_path
+            include_xml(xml_parent, pb_type_path)
+            # In order to avoid overspecifying interconnect, there are two directions we currently
+            # consider. All interconnect going INTO a cell, and interconnect going out of a cell
+            # into a top level output - or all outputs if "mode" is used.
+            inp_cons = mod.cell_conns(cname, "input")
+            for pin, net in inp_cons:
+                drvs = mod.net_drivers(net)
+                if len(drvs) == 0:
+                    print("ERROR: pin %s.%s has no driver, interconnect will be missing" % (pb_name, pin))
+                    assert False
+                elif len(drvs) > 1:
+                    print("ERROR: pin %s.%s has multiple drivers, interconnect will be overspecified" % (pb_name, pin))
+                    assert False
+                for drv_cell, drv_pin in drvs:
+                    interconn.append(((drv_cell, drv_pin), (cname, pin)))
 
-        out_cons = mod.cell_conns(cname, "output")
-        for pin, net in out_cons:
-            sinks = mod.net_sinks(net)
-            for sink_cell, sink_pin in sinks:
-                if sink_cell == mod.name:
-                     #Only consider outputs from cell to top level IO. Inputs to other cells will be dealt with
-                     #in those cells.
-                    interconn.append(((cname, pin), (sink_cell, sink_pin)))
+            out_cons = mod.cell_conns(cname, "output")
+            for pin, net in out_cons:
+                sinks = mod.net_sinks(net)
+                for sink_cell, sink_pin in sinks:
+                    if sink_cell == mod.name:
+                         #Only consider outputs from cell to top level IO. Inputs to other cells will be dealt with
+                         #in those cells.
+                        interconn.append(((cname, pin), (sink_cell, sink_pin)))
 
-    ic_xml = ET.SubElement(xml_parent, "interconnect")
-    # Process interconnect
-    for source, dest in interconn:
-        make_direct_conn(ic_xml, source, dest)
+        ic_xml = ET.SubElement(xml_parent, "interconnect")
+        # Process interconnect
+        for source, dest in interconn:
+            make_direct_conn(ic_xml, source, dest)
 
     def process_clocked_tmg(tmgspec, port, xmltype, xml_parent):
         """Add a suitable timing spec if necessary to the pb_type"""
@@ -196,15 +201,16 @@
     generate."""
 
     attrs = mod.module_attrs
+    modes = yj.modules_with_attr("ALTERNATIVE_TO", mod.name)
+
     pb_xml_attrs = dict()
-
     pb_xml_attrs["name"] = mod.name
-
+    # If we are a blackbox with no modes, then generate a blif_model
+    is_blackbox = (mod.attr("blackbox", 0) == 1)
+    has_modes = len(modes) > 0
     # Process type and class of module
-    mod_type = mod.attr("TYPE")
-    mod_cls = mod.attr("CLASS")
-    if mod_type == "bel":
-        assert mod_cls is not None
+    mod_cls = mod.CLASS
+    if mod_cls is not None:
         if mod_cls == "lut":
             pb_xml_attrs["blif_model"] = ".names"
             pb_xml_attrs["class"] = "lut"
@@ -216,17 +222,8 @@
             pb_xml_attrs["class"] = "flipflop"
         else:
             assert False
-    elif mod_type == "blackbox":
+    elif is_blackbox and not has_modes:
         pb_xml_attrs["blif_model"] = ".subckt " + mod.name
-        if mod_cls is not None:
-            if mod_cls == "mem":
-                pb_xml_attrs["class"] = "memory"
-            else:
-                assert False
-    elif mod_type is None:
-        pass
-    else:
-        assert False
 
     #TODO: might not always be the case? should be use Verilog `generate`s to detect this?
     pb_xml_attrs["num_pb"] = "1"
@@ -248,8 +245,6 @@
         else:
             assert False
 
-    modes = yj.modules_with_attr("ALTERNATIVE_TO", mod.name)
-
     if len(modes) > 0:
         for mode_mod in modes:
             mode_xml = ET.SubElement(pb_type_xml, "mode", {"name" : mode_mod.name})
diff --git a/yosys/json.py b/yosys/json.py
index 5bdc050..6b625ee 100755
--- a/yosys/json.py
+++ b/yosys/json.py
@@ -67,6 +67,9 @@
         else:
             return defval
 
+    def __getattr__(self, attr):
+        return self.attr(attr)
+
     def has_attr(self, attr):
         """Return true if an attribute exists"""
         return attr in self.module_attrs
@@ -115,7 +118,7 @@
                     conns.append((port, condata[0]))
                 else:
                     for i in range(N):
-                        conns.append(("%s[%d]" % (port, N), condata[i]))
+                        conns.append(("%s[%d]" % (port, i), condata[i]))
         return conns
 
     def conn_io(self, net, iodir):
diff --git a/yosys/run.py b/yosys/run.py
index 7a2d6e3..37e3349 100755
--- a/yosys/run.py
+++ b/yosys/run.py
@@ -5,17 +5,17 @@
 def get_yosys():
     return os.getenv('YOSYS', "yosys")
 
-def yosys_get_output(params):
+def get_output(params):
     cmd = [get_yosys()] + params
     return subprocess.check_output(cmd).decode("utf-8")
 
-def yosys_commands(commands, infiles = []):
+def commands(commands, infiles = []):
     params = ["-q", "-p", commands] + infiles
-    return yosys_get_output(params)
+    return get_output(params)
 
-def yosys_script(script, infiles = []):
+def script(script, infiles = []):
     params = ["-q", "-s", script] + infiles
-    return yosys_get_output(params)
+    return get_output(params)
 
 def vlog_to_json(infiles, flatten = False, aig = False):
     """
@@ -30,7 +30,7 @@
     prep_opts = "-flatten" if flatten else ""
     json_opts = "-aig" if aig else ""
     cmds = "prep %s; write_json %s" % (prep_opts, json_opts)
-    j = yosys.utils.strip_yosys_json(yosys_commands(cmds, infiles))
+    j = yosys.utils.strip_yosys_json(commands(cmds, infiles))
     """with open('dump.json', 'w') as dbg:
         print(j,file=dbg)"""
     return json.loads(j)
@@ -61,7 +61,7 @@
 
     outfile = tempfile.mktemp()
     sel_cmd = "prep -top %s -flatten; cd %s; select -write %s %s" % (module, module, outfile, expr)
-    yosys_commands(sel_cmd, infiles)
+    commands(sel_cmd, infiles)
     pins = []
     with open(outfile, 'r') as f:
         for net in f: