topstitch/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
// SPDX-License-Identifier: Apache-2.0

use indexmap::map::Entry;
use indexmap::IndexMap;
use itertools::Itertools;
use num_bigint::{BigInt, BigUint};
use regex::Regex;
use slang_rs::{self, extract_ports, str2tmpfile, SlangConfig};
use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::Hash;
use std::path::Path;
use std::rc::{Rc, Weak};
use xlsynth::vast::{Expr, LogicRef, VastFile, VastFileType};

mod enum_type;
mod inout;
mod pipeline;

use pipeline::add_pipeline;
use pipeline::PipelineDetails;

/// Represents the direction (`Input` or `Output`) and bit width of a port.
#[derive(Clone, Debug)]
pub enum IO {
    Input(usize),
    Output(usize),
    InOut(usize),
}

impl IO {
    /// Returns the width of the port in bits.
    pub fn width(&self) -> usize {
        match self {
            IO::Input(width) => *width,
            IO::Output(width) => *width,
            IO::InOut(width) => *width,
        }
    }

    /// Returns a new IO enum with the same width but the opposite direction.
    pub fn flip(&self) -> IO {
        match self {
            IO::Input(width) => IO::Output(*width),
            IO::Output(width) => IO::Input(*width),
            IO::InOut(width) => IO::InOut(*width),
        }
    }

    /// Returns a new IO enum with the same direction but a different width.
    pub fn with_width(&self, width: usize) -> IO {
        match self {
            IO::Input(_) => IO::Input(width),
            IO::Output(_) => IO::Output(width),
            IO::InOut(_) => IO::InOut(width),
        }
    }

    fn variant_name(&self) -> &str {
        match self {
            IO::Input(_) => "Input",
            IO::Output(_) => "Output",
            IO::InOut(_) => "InOut",
        }
    }
}

/// Represents a port on a module definition or a module instance.
#[derive(Clone, Debug)]
pub enum Port {
    ModDef {
        mod_def_core: Weak<RefCell<ModDefCore>>,
        name: String,
    },
    ModInst {
        mod_def_core: Weak<RefCell<ModDefCore>>,
        inst_name: String,
        port_name: String,
    },
}

impl Port {
    /// Returns the name this port has in its (parent) module definition.
    pub fn name(&self) -> &str {
        match self {
            Port::ModDef { name, .. } => name,
            Port::ModInst { port_name, .. } => port_name,
        }
    }

    fn variant_name(&self) -> &str {
        match self {
            Port::ModDef { .. } => "ModDef",
            Port::ModInst { .. } => "ModInst",
        }
    }

    /// Returns the IO enum associated with this Port.
    pub fn io(&self) -> IO {
        match self {
            Port::ModDef { mod_def_core, name } => {
                mod_def_core.upgrade().unwrap().borrow().ports[name].clone()
            }
            Port::ModInst {
                mod_def_core,
                inst_name,
                port_name,
            } => mod_def_core.upgrade().unwrap().borrow().instances[inst_name]
                .borrow()
                .ports[port_name]
                .clone(),
        }
    }

    fn assign_to_inst(&self, inst: &ModInst) -> Port {
        match self {
            Port::ModDef { name, .. } => Port::ModInst {
                mod_def_core: inst.mod_def_core.clone(),
                inst_name: inst.name.clone(),
                port_name: name.clone(),
            },
            _ => panic!("Already assigned to an instance."),
        }
    }

    fn to_port_key(&self) -> PortKey {
        match self {
            Port::ModDef { name, .. } => PortKey::ModDefPort {
                mod_def_name: self.get_mod_def_core().borrow().name.clone(),
                port_name: name.clone(),
            },
            Port::ModInst {
                inst_name,
                port_name,
                ..
            } => PortKey::ModInstPort {
                mod_def_name: self.get_mod_def_core().borrow().name.clone(),
                inst_name: inst_name.clone(),
                port_name: port_name.clone(),
            },
        }
    }

    fn is_driver(&self) -> bool {
        match self {
            Port::ModDef { .. } => matches!(self.io(), IO::Input(_)),
            Port::ModInst { .. } => matches!(self.io(), IO::Output(_)),
        }
    }
}

/// Represents a slice of a port, which may be on a module definition or on a
/// module instance.
///
/// A slice is a defined as a contiguous range of bits from `msb` down to `lsb`,
/// inclusive. A slice can be a single bit on the port (`msb` equal to `lsb`),
/// the entire port, or any range in between.
#[derive(Clone, Debug)]
pub struct PortSlice {
    port: Port,
    msb: usize,
    lsb: usize,
}

impl PortSlice {
    /// Divides a port slice into `n` parts of equal bit width, return a vector
    /// of `n` port slices. For example, if a port is 8 bits wide and `n` is 2,
    /// the port will be divided into 2 slices of 4 bits each: `port[3:0]` and
    /// `port[7:4]`. This method panics if the port width is not divisible by
    /// `n`.
    pub fn subdivide(&self, n: usize) -> Vec<Self> {
        let width = self.msb - self.lsb + 1;
        if width % n != 0 {
            panic!(
                "Cannot subdivide {} into {} equal parts.",
                self.debug_string(),
                n
            );
        }
        (0..n)
            .map(move |i| {
                let sub_width = width / n;
                PortSlice {
                    port: self.port.clone(),
                    msb: ((i + 1) * sub_width) - 1 + self.lsb,
                    lsb: (i * sub_width) + self.lsb,
                }
            })
            .collect()
    }

    fn width(&self) -> usize {
        self.msb - self.lsb + 1
    }

    /// Create a new port called `name` on the parent module and connects it to
    /// this port slice.
    ///
    /// The exact behavior depends on whether this is a port slice on a module
    /// definition or a module instance. If this is a port slice on a module
    /// definition, a new port is created on the same module definition, with
    /// the same width, but opposite direction. For example, suppose that this
    /// is a port slice `a` on a module definition that is an 8-bit input;
    /// calling `export_as("y")` will create an 8-bit output on the same
    /// module definition called `y`.
    ///
    /// If, on the other hand, this is a port slice on a module instance, a new
    /// port will be created on the module definition containing the
    /// instance, with the same width and direction. For example, if this is
    /// an 8-bit input port `x` on a module instance, calling
    /// `export_as("y")` will create a new 8-bit input port `y` on the
    /// module definition that contains the instance.
    pub fn export_as(&self, name: impl AsRef<str>) -> Port {
        let io = match self.port {
            Port::ModDef { .. } => self.port.io().with_width(self.width()).flip(),
            Port::ModInst { .. } => self.port.io().with_width(self.width()),
        };

        let core = self.get_mod_def_core();
        let moddef = ModDef { core };

        let new_port = moddef.add_port(name, io);
        self.connect(&new_port);

        new_port
    }

    /// Same as export_as(), but the new port is created with the same name as
    /// the port being exported. As a result, this method can only be used with
    /// ports on module instances. The method will panic if called on a port
    /// slice on a module definition.
    pub fn export(&self) -> Port {
        let name = match &self.port {
            Port::ModDef { .. } => panic!(
                "Use export_as() to export {}, specifying the new name of the exported port.",
                self.debug_string()
            ),
            Port::ModInst { port_name, .. } => port_name.clone(),
        };
        self.export_as(&name)
    }

    fn slice_relative(&self, offset: usize, width: usize) -> Self {
        assert!(offset + width <= self.width());

        PortSlice {
            port: self.port.clone(),
            msb: self.lsb + offset + width - 1,
            lsb: self.lsb + offset,
        }
    }
}

/// Indicates that a type can be converted to a `PortSlice`. `Port` and
/// `PortSlice` both implement this trait, which makes it easier to perform the
/// same operations on both.
pub trait ConvertibleToPortSlice {
    fn to_port_slice(&self) -> PortSlice;
}

impl ConvertibleToPortSlice for Port {
    fn to_port_slice(&self) -> PortSlice {
        PortSlice {
            port: self.clone(),
            msb: self.io().width() - 1,
            lsb: 0,
        }
    }
}

impl ConvertibleToPortSlice for PortSlice {
    fn to_port_slice(&self) -> PortSlice {
        self.clone()
    }
}

/// Represents a module definition, like `module <mod_def_name> ... endmodule`
/// in Verilog.
#[derive(Clone)]
pub struct ModDef {
    core: Rc<RefCell<ModDefCore>>,
}

/// Represents an instance of a module definition, like `<mod_def_name>
/// <mod_inst_name> ( ... );` in Verilog.
#[derive(Clone)]
pub struct ModInst {
    name: String,
    mod_def_core: Weak<RefCell<ModDefCore>>,
}

struct VerilogImport {
    sources: Vec<String>,
    incdirs: Vec<String>,
    skip_unsupported: bool,
    ignore_unknown_modules: bool,
}

#[derive(Debug, Clone)]
pub struct PipelineConfig {
    pub clk: String,
    pub depth: usize,
}

#[derive(Debug, Clone)]
struct Assignment {
    pub lhs: PortSlice,
    pub rhs: PortSlice,
    pub pipeline: Option<PipelineConfig>,
}

/// Data structure representing a module definition.
///
/// Contains the module's name, ports, interfaces, instances, etc. Not intended
/// to be used directly; use `ModDef` instead, which contains a smart pointer to
/// this struct.
pub struct ModDefCore {
    name: String,
    ports: IndexMap<String, IO>,
    interfaces: IndexMap<String, IndexMap<String, (String, usize, usize)>>,
    instances: IndexMap<String, Rc<RefCell<ModDefCore>>>,
    usage: Usage,
    generated_verilog: Option<String>,
    verilog_import: Option<VerilogImport>,
    assignments: Vec<Assignment>,
    unused: Vec<PortSlice>,
    tieoffs: Vec<(PortSlice, BigInt)>,
    whole_port_tieoffs: IndexMap<String, IndexMap<String, BigInt>>,
    inst_connections: IndexMap<String, IndexMap<String, Vec<InstConnection>>>,
    specified_wire_names: IndexMap<String, IndexMap<String, String>>,
    reserved_net_definitions: IndexMap<String, Wire>,
    enum_ports: IndexMap<String, String>,
}

#[derive(Clone)]
struct InstConnection {
    inst_port_slice: PortSlice,
    connected_to: PortSliceOrWire,
}

#[derive(Clone)]
struct Wire {
    name: String,
    width: usize,
}

#[derive(Clone)]
enum PortSliceOrWire {
    PortSlice(PortSlice),
    Wire(Wire),
}

/// Represents how a module definition should be used when validating and/or
/// emitting Verilog.
#[derive(PartialEq, Default, Clone)]
pub enum Usage {
    /// When validating, validate the module definition and descend into its
    /// instances. When emitting Verilog, emit its definition and descend into
    /// its instances.
    #[default]
    EmitDefinitionAndDescend,

    /// When validating, do not validate the module definition and do not
    /// descend into its instances. When emitting Verilog, do not emit its
    /// definition and do not descend into its instances.
    EmitNothingAndStop,

    /// When validating, do not validate the module definition and do not
    /// descend into its instances. When emitting Verilog, emit a stub
    /// (interface only) and do not descend into its instances.
    EmitStubAndStop,

    /// When validating, do not validate the module definition and do not
    /// descend into its instances. When emitting Verilog, emit its definition
    /// but do not descend into its instances.
    EmitDefinitionAndStop,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum PortKey {
    ModDefPort {
        mod_def_name: String,
        port_name: String,
    },
    ModInstPort {
        mod_def_name: String,
        inst_name: String,
        port_name: String,
    },
}

impl PortKey {
    fn debug_string(&self) -> String {
        match &self {
            PortKey::ModDefPort {
                mod_def_name,
                port_name,
            } => format!("{}.{}", mod_def_name, port_name),
            PortKey::ModInstPort {
                mod_def_name,
                inst_name,
                port_name,
            } => format!("{}.{}.{}", mod_def_name, inst_name, port_name),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct DrivenPortBits {
    driven: BigUint,
    width: usize,
}

impl DrivenPortBits {
    fn new(width: usize) -> Self {
        DrivenPortBits {
            driven: BigUint::from(0u32),
            width,
        }
    }

    fn driven(&mut self, msb: usize, lsb: usize) -> Result<(), DrivenError> {
        let mut mask = (BigUint::from(1u32) << (msb - lsb + 1)) - BigUint::from(1u32);

        // make sure this is not already driven
        if (self.driven.clone() >> lsb) & mask.clone() != BigUint::from(0u32) {
            return Err(DrivenError::AlreadyDriven);
        };

        // mark the bits as driven
        mask <<= lsb;
        self.driven |= mask;

        Ok(())
    }

    fn all_driven(&self) -> bool {
        self.driven == (BigUint::from(1u32) << self.width) - BigUint::from(1u32)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct DrivingPortBits {
    driving: BigUint,
    unused: BigUint,
    width: usize,
}

enum DrivenError {
    AlreadyDriven,
}

enum DrivingError {
    AlreadyMarkedUnused,
}

enum UnusedError {
    AlreadyMarkedUnused,
    AlreadyUsed,
}

impl DrivingPortBits {
    fn new(width: usize) -> Self {
        DrivingPortBits {
            driving: BigUint::from(0u32),
            unused: BigUint::from(0u32),
            width,
        }
    }

    fn driving(&mut self, msb: usize, lsb: usize) -> Result<(), DrivingError> {
        let mut mask = (BigUint::from(1u32) << (msb - lsb + 1)) - BigUint::from(1u32);

        // make sure nothing in this range is marked as unused
        if (self.unused.clone() >> lsb) & mask.clone() != BigUint::from(0u32) {
            return Err(DrivingError::AlreadyMarkedUnused);
        };

        // mark the bits as driving
        mask <<= lsb;
        self.driving |= mask;

        Ok(())
    }

    fn unused(&mut self, msb: usize, lsb: usize) -> Result<(), UnusedError> {
        let mut mask = (BigUint::from(1u32) << (msb - lsb + 1)) - BigUint::from(1u32);

        // make sure nothing in this range is marked as unused
        if (self.unused.clone() >> lsb) & mask.clone() != BigUint::from(0u32) {
            return Err(UnusedError::AlreadyMarkedUnused);
        };

        // make sure nothing in this range is marked as driving
        if (self.driving.clone() >> lsb) & mask.clone() != BigUint::from(0u32) {
            return Err(UnusedError::AlreadyUsed);
        };

        // mark the bits as unused
        mask <<= lsb;
        self.unused |= mask;

        Ok(())
    }

    fn all_driving_or_unused(&self) -> bool {
        (self.driving.clone() | self.unused.clone())
            == (BigUint::from(1u32) << self.width) - BigUint::from(1u32)
    }
}

impl ModDef {
    /// Creates a new module definition with the given name.
    pub fn new(name: impl AsRef<str>) -> ModDef {
        ModDef {
            core: Rc::new(RefCell::new(ModDefCore {
                name: name.as_ref().to_string(),
                ports: IndexMap::new(),
                enum_ports: IndexMap::new(),
                interfaces: IndexMap::new(),
                instances: IndexMap::new(),
                usage: Default::default(),
                generated_verilog: None,
                assignments: Vec::new(),
                unused: Vec::new(),
                tieoffs: Vec::new(),
                whole_port_tieoffs: IndexMap::new(),
                verilog_import: None,
                inst_connections: IndexMap::new(),
                reserved_net_definitions: IndexMap::new(),
                specified_wire_names: IndexMap::new(),
            })),
        }
    }

    /// Returns a new module definition with the given name, using the same
    /// ports and interfaces as the original module. The new module has no
    /// instantiations or internal connections.
    pub fn stub(&self, name: impl AsRef<str>) -> ModDef {
        let core = self.core.borrow();
        ModDef {
            core: Rc::new(RefCell::new(ModDefCore {
                name: name.as_ref().to_string(),
                ports: core.ports.clone(),
                // TODO(sherbst): 12/08/2024 should enum_ports be copied when stubbing?
                // The implication is that modules that instantiate this stub will
                // use casting to connect to enum input ports, even though they appear
                // as flat buses in the stub.
                enum_ports: core.enum_ports.clone(),
                interfaces: core.interfaces.clone(),
                instances: IndexMap::new(),
                usage: Default::default(),
                generated_verilog: None,
                assignments: Vec::new(),
                unused: Vec::new(),
                tieoffs: Vec::new(),
                whole_port_tieoffs: IndexMap::new(),
                verilog_import: None,
                inst_connections: IndexMap::new(),
                reserved_net_definitions: IndexMap::new(),
                specified_wire_names: IndexMap::new(),
            })),
        }
    }

    fn frozen(&self) -> bool {
        self.core.borrow().generated_verilog.is_some()
            || self.core.borrow().verilog_import.is_some()
    }

    /// Creates a new module definition from a Verilog file. The `name`
    /// parameter is the name of the module to extract from the Verilog file,
    /// and `verilog` is the path to the Verilog file. If
    /// `ignore_unknown_modules` is `true`, do not panic if the Verilog file
    /// instantiates modules whose definitions cannot be found. This is often
    /// useful because only the interface of module `name` needs to be
    /// extracted; its contents do not need to be interpreted. If
    /// `skip_unsupported` is `true`, do not panic if the interface of module
    /// `name` contains unsupported features; simply skip these ports. This is
    /// occasionally useful when prototyping.
    pub fn from_verilog_file(
        name: impl AsRef<str>,
        verilog: &Path,
        ignore_unknown_modules: bool,
        skip_unsupported: bool,
    ) -> Self {
        Self::from_verilog_files(name, &[verilog], ignore_unknown_modules, skip_unsupported)
    }

    /// Creates a new module definition from a list of Verilog files. The `name`
    /// parameter is the name of the module to extract from the Verilog sources,
    /// and `verilog` is an array of paths of Verilog sources. If
    /// `ignore_unknown_modules` is `true`, do not panic if the Verilog file
    /// instantiates modules whose definitions cannot be found. This is often
    /// useful because only the interface of module `name` needs to be
    /// extracted; its contents do not need to be interpreted. If
    /// `skip_unsupported` is `true`, do not panic if the interface of module
    /// `name` contains unsupported features; simply skip these ports. This is
    /// occasionally useful when prototyping.
    pub fn from_verilog_files(
        name: impl AsRef<str>,
        verilog: &[&Path],
        ignore_unknown_modules: bool,
        skip_unsupported: bool,
    ) -> Self {
        let cfg = SlangConfig {
            sources: &verilog
                .iter()
                .map(|path| path.to_str().unwrap())
                .collect::<Vec<_>>(),
            ignore_unknown_modules,
            ..Default::default()
        };

        Self::from_verilog_using_slang(name, &cfg, skip_unsupported)
    }

    /// Creates a new module definition from Verilog source code. The `name`
    /// parameter is the name of the module to extract from the Verilog code,
    /// and `verilog` is a string containing Verilog code. If
    /// `ignore_unknown_modules` is `true`, do not panic if the Verilog file
    /// instantiates modules whose definitions cannot be found. This is often
    /// useful because only the interface of module `name` needs to be
    /// extracted; its contents do not need to be interpreted. If
    /// `skip_unsupported` is `true`, do not panic if the interface of module
    /// `name` contains unsupported features; simply skip these ports. This is
    /// occasionally useful when prototyping.
    pub fn from_verilog(
        name: impl AsRef<str>,
        verilog: impl AsRef<str>,
        ignore_unknown_modules: bool,
        skip_unsupported: bool,
    ) -> Self {
        let verilog = str2tmpfile(verilog.as_ref()).unwrap();

        let cfg = SlangConfig {
            sources: &[verilog.path().to_str().unwrap()],
            ignore_unknown_modules,
            ..Default::default()
        };

        Self::from_verilog_using_slang(name, &cfg, skip_unsupported)
    }

    /// Creates a new module definition from Verilog sources. The `name`
    /// parameter is the name of the module to extract from Verilog code, and
    /// `cfg` is a `SlangConfig` struct specifying source files, include
    /// directories, etc. If `skip_unsupported` is `true`, do not panic if the
    /// interface of module `name` contains unsupported features; simply skip
    /// these ports. This is occasionally useful when prototyping.
    pub fn from_verilog_using_slang(
        name: impl AsRef<str>,
        cfg: &SlangConfig,
        skip_unsupported: bool,
    ) -> Self {
        let parser_ports = extract_ports(cfg, skip_unsupported);

        let selected = parser_ports.get(name.as_ref()).unwrap_or_else(|| {
            panic!(
                "Module definition '{}' not found in Verilog sources.",
                name.as_ref()
            )
        });

        Self::mod_def_from_parser_ports(name.as_ref(), selected, cfg, skip_unsupported)
    }

    pub fn all_from_verilog_using_slang(cfg: &SlangConfig, skip_unsupported: bool) -> Vec<Self> {
        let parser_ports = extract_ports(cfg, skip_unsupported);
        parser_ports
            .keys()
            .map(|name| {
                Self::mod_def_from_parser_ports(name, &parser_ports[name], cfg, skip_unsupported)
            })
            .collect()
    }

    fn mod_def_from_parser_ports(
        mod_def_name: &str,
        parser_ports: &[slang_rs::Port],
        cfg: &SlangConfig,
        skip_unsupported: bool,
    ) -> ModDef {
        let mut ports = IndexMap::new();
        let mut enum_ports = IndexMap::new();
        for parser_port in parser_ports {
            match parser_port_to_port(parser_port) {
                Ok((name, io)) => {
                    ports.insert(name.clone(), io.clone());
                    // Enum input ports that are not a packed array require special handling
                    // They need to have casting to be valid Verilog.
                    if let slang_rs::Type::Enum {
                        name: enum_name,
                        packed_dimensions,
                        unpacked_dimensions,
                        ..
                    } = &parser_port.ty
                    {
                        if packed_dimensions.is_empty() && unpacked_dimensions.is_empty() {
                            if let IO::Input(_) = io {
                                enum_ports.insert(name.clone(), enum_name.clone());
                            }
                        }
                    }
                }
                Err(e) => {
                    if !skip_unsupported {
                        panic!("{e}");
                    } else {
                        continue;
                    }
                }
            }
        }

        ModDef {
            core: Rc::new(RefCell::new(ModDefCore {
                name: mod_def_name.to_string(),
                ports,
                enum_ports,
                interfaces: IndexMap::new(),
                instances: IndexMap::new(),
                usage: Usage::EmitNothingAndStop,
                generated_verilog: None,
                assignments: Vec::new(),
                unused: Vec::new(),
                tieoffs: Vec::new(),
                whole_port_tieoffs: IndexMap::new(),
                verilog_import: Some(VerilogImport {
                    sources: cfg.sources.iter().map(|s| s.to_string()).collect(),
                    incdirs: cfg.incdirs.iter().map(|s| s.to_string()).collect(),
                    skip_unsupported,
                    ignore_unknown_modules: cfg.ignore_unknown_modules,
                }),
                inst_connections: IndexMap::new(),
                reserved_net_definitions: IndexMap::new(),
                specified_wire_names: IndexMap::new(),
            })),
        }
    }

    /// Adds a port to the module definition with the given name. The direction
    /// and width are specfied via the `io` parameter.
    pub fn add_port(&self, name: impl AsRef<str>, io: IO) -> Port {
        if self.frozen() {
            panic!(
                "Module {} is frozen. wrap() first if modifications are needed.",
                self.core.borrow().name
            );
        }

        let mut core = self.core.borrow_mut();
        match core.ports.entry(name.as_ref().to_string()) {
            Entry::Occupied(_) => {
                panic!("Port {}.{} already exists.", core.name, name.as_ref(),)
            }
            Entry::Vacant(entry) => {
                entry.insert(io);
                Port::ModDef {
                    name: name.as_ref().to_string(),
                    mod_def_core: Rc::downgrade(&self.core),
                }
            }
        }
    }

    /// Returns the port on this module definition with the given name; panics
    /// if a port with that name does not exist.
    pub fn get_port(&self, name: impl AsRef<str>) -> Port {
        let inner = self.core.borrow();
        if inner.ports.contains_key(name.as_ref()) {
            Port::ModDef {
                name: name.as_ref().to_string(),
                mod_def_core: Rc::downgrade(&self.core),
            }
        } else {
            panic!("Port {}.{} does not exist", inner.name, name.as_ref())
        }
    }

    /// Returns a slice of the port on this module definition with the given
    /// name, from `msb` down to `lsb`, inclusive; panics if a port with that
    /// name does not exist.
    pub fn get_port_slice(&self, name: impl AsRef<str>, msb: usize, lsb: usize) -> PortSlice {
        self.get_port(name).slice(msb, lsb)
    }

    /// Returns a vector of all ports on this module definition with the given
    /// prefix. If `prefix` is `None`, returns all ports.
    pub fn get_ports(&self, prefix: Option<&str>) -> Vec<Port> {
        let inner = self.core.borrow();
        let mut result = Vec::new();
        for name in inner.ports.keys() {
            if prefix.map_or(true, |pfx| name.starts_with(pfx)) {
                result.push(Port::ModDef {
                    name: name.clone(),
                    mod_def_core: Rc::downgrade(&self.core),
                });
            }
        }
        result
    }

    /// Walk through all instances within this module definition, marking those
    /// whose names match the given regex with the usage
    /// `Usage::EmitStubAndStop`. Repeat recursively for all instances whose
    /// names do not match this regex.
    pub fn stub_recursive(&self, regex: impl AsRef<str>) {
        let regex_compiled = Regex::new(regex.as_ref()).unwrap();
        let mut visited = HashSet::new();
        self.stub_recursive_helper(&regex_compiled, &mut visited);
    }

    fn stub_recursive_helper(&self, regex: &Regex, visited: &mut HashSet<String>) {
        for inst in self.get_instances() {
            let mod_def = inst.get_mod_def();
            let mod_def_name = mod_def.get_name();
            if regex.is_match(mod_def_name.as_str()) {
                mod_def.set_usage(Usage::EmitStubAndStop);
            } else if !visited.contains(&mod_def_name) {
                visited.insert(mod_def_name);
                mod_def.stub_recursive_helper(regex, visited);
            }
        }
    }

    /// Returns the name of this module definition.
    pub fn get_name(&self) -> String {
        self.core.borrow().name.clone()
    }

    /// Returns a vector of all module instances within this module definition.
    pub fn get_instances(&self) -> Vec<ModInst> {
        self.core
            .borrow()
            .instances
            .keys()
            .map(|name| ModInst {
                name: name.clone(),
                mod_def_core: Rc::downgrade(&self.core),
            })
            .collect()
    }

    /// Returns the module instance within this module definition with the given
    /// name; panics if an instance with that name does not exist.
    pub fn get_instance(&self, name: impl AsRef<str>) -> ModInst {
        let inner = self.core.borrow();
        if inner.instances.contains_key(name.as_ref()) {
            ModInst {
                name: name.as_ref().to_string(),
                mod_def_core: Rc::downgrade(&self.core),
            }
        } else {
            panic!("Instance {}.{} does not exist", inner.name, name.as_ref())
        }
    }

    /// Configures how this module definition should be used when validating
    /// and/or emitting Verilog.
    pub fn set_usage(&self, usage: Usage) {
        if self.core.borrow().generated_verilog.is_some() {
            assert!(
                usage != Usage::EmitDefinitionAndDescend,
                "Cannot descend into a module defined from Verilog sources."
            );
        }
        self.core.borrow_mut().usage = usage;
    }

    /// Instantiate a module, using the provided instance name. `autoconnect` is
    /// an optional list of port names to automatically connect between the
    /// parent module and the instantiated module. This feature does not make
    /// any connections between module instances.
    ///
    /// As an example, suppose that the parent module has a port named `clk` and
    /// the instantiated module has a port named `clk`. Passing
    /// `autoconnect=Some(&["clk"])` will automatically connect the two ports.
    /// It will not automatically connect the `clk` port on this module
    /// instance to the `clk` port on any other module instances.
    ///
    /// It's OK if some or all of the `autoconnect` names do not exist in
    /// the parent module and/or instantiated module; TopStitch will not panic
    /// in this case.
    pub fn instantiate(
        &self,
        moddef: &ModDef,
        name: Option<&str>,
        autoconnect: Option<&[&str]>,
    ) -> ModInst {
        let name_default;
        let name = if let Some(name) = name {
            name
        } else {
            name_default = format!("{}_i", moddef.core.borrow().name);
            name_default.as_str()
        };

        if self.frozen() {
            panic!(
                "Module {} is frozen. wrap() first if modifications are needed.",
                self.core.borrow().name
            );
        }

        {
            let mut inner = self.core.borrow_mut();
            if inner.instances.contains_key(name) {
                panic!("Instance {}.{} already exists", inner.name, name);
            }
            inner
                .instances
                .insert(name.to_string(), moddef.core.clone());
        }

        // Create the ModInst
        let inst = ModInst {
            name: name.to_string(),
            mod_def_core: Rc::downgrade(&self.core),
        };

        // autoconnect logic
        if let Some(port_names) = autoconnect {
            for &port_name in port_names {
                // Check if the instantiated module has this port
                if let Some(io) = moddef.core.borrow().ports.get(port_name) {
                    {
                        let mut inner = self.core.borrow_mut();
                        if !inner.ports.contains_key(port_name) {
                            inner.ports.insert(port_name.to_string(), io.clone());
                        }
                    }

                    // Connect the instance port to the parent module port
                    let parent_port = self.get_port(port_name);
                    let instance_port = inst.get_port(port_name);
                    parent_port.connect(&instance_port)
                }
            }
        }

        inst
    }

    /// Create one or more instances of a module, using the provided dimensions.
    /// For example, if `dimensions` is `&[3]`, TopStitch will create a 1D array
    /// of 3 instances, called `<mod_def_name>_i_0`, `<mod_def_name>_i_1`,
    /// `<mod_def_name>_i_2`. If `dimensions` is `&[2, 3]`, TopStitch will
    /// create a `2x3` array of instances, called `<mod_def_name>_i_0_0`,
    /// `<mod_def_name>_i_0_1`, `<mod_def_name>_i_0_2`, `<mod_def_name>_i_1_0`,
    /// etc. If provided, the optional `prefix` argument sets the prefix used in
    /// naming instances to something other than `<mod_def_name>_i_`.
    /// `autoconnect` has the same meaning as in `instantiate()`: if provided,
    /// it is a list of port names to automatically connect between the parent
    /// module and the instantiated module. For example, if the parent module
    /// has a port named `clk` and the instantiated module has a port named
    /// `clk`, passing `Some(&["clk"])` will automatically connect the two
    /// ports.
    pub fn instantiate_array(
        &self,
        moddef: &ModDef,
        dimensions: &[usize],
        prefix: Option<&str>,
        autoconnect: Option<&[&str]>,
    ) -> Vec<ModInst> {
        if dimensions.is_empty() {
            panic!(
                "Array instantiation of {} in {}: dimensions array cannot be empty.",
                moddef.get_name(),
                self.get_name()
            );
        }
        if dimensions.iter().any(|&d| d == 0) {
            panic!(
                "Array instantiation of {} in {}: dimension sizes must be greater than zero.",
                moddef.get_name(),
                self.get_name()
            );
        }

        // Create a vector of ranges based on dimensions
        let ranges: Vec<std::ops::Range<usize>> = dimensions.iter().map(|&d| 0..d).collect();

        // Generate all combinations of indices
        let index_combinations = ranges.into_iter().multi_cartesian_product();

        let mut instances = Vec::new();

        for indices in index_combinations {
            // Build instance name
            let indices_str = indices
                .iter()
                .map(|&i| i.to_string())
                .collect::<Vec<String>>()
                .join("_");

            let instance_name = match prefix {
                Some(pfx) => {
                    if indices_str.is_empty() {
                        pfx.to_string()
                    } else {
                        format!("{}_{}", pfx, indices_str)
                    }
                }
                None => {
                    let moddef_name = &moddef.core.borrow().name;
                    if indices_str.is_empty() {
                        format!("{}_i", moddef_name)
                    } else {
                        format!("{}_i_{}", moddef_name, indices_str)
                    }
                }
            };

            // Instantiate the moddef
            let inst = self.instantiate(moddef, Some(&instance_name), autoconnect);
            instances.push(inst);
        }

        instances
    }

    /// Writes Verilog code for this module definition to the given file path.
    /// If `validate` is `true`, validate the module definition before emitting
    /// Verilog.
    pub fn emit_to_file(&self, path: &Path, validate: bool) {
        let err_msg = format!("emitting ModDef to file at path: {:?}", path);
        std::fs::write(path, self.emit(validate)).expect(&err_msg);
    }

    /// Returns Verilog code for this module definition as a string. If
    /// `validate` is `true`, validate the module definition before emitting
    /// Verilog.
    pub fn emit(&self, validate: bool) -> String {
        if validate {
            self.validate();
        }
        let mut emitted_module_names = IndexMap::new();
        let mut file = VastFile::new(VastFileType::SystemVerilog);
        let mut leaf_text = Vec::new();
        let mut enum_remapping = IndexMap::new();
        self.emit_recursive(
            &mut emitted_module_names,
            &mut file,
            &mut leaf_text,
            &mut enum_remapping,
        );
        leaf_text.push(file.emit());
        let result = leaf_text.join("\n");
        let result = inout::rename_inout(result);
        enum_type::remap_enum_types(result, &enum_remapping)
    }

    fn retrieve_net_name(&self, inst_name: &str, port_name: &str) -> String {
        self.core.borrow().specified_wire_names
            .get(inst_name)
            .and_then(|inst_specified_wire_names| inst_specified_wire_names.get(port_name).cloned())
            .unwrap_or(format!("{}_{}", inst_name, port_name))
    }

    fn emit_recursive(
        &self,
        emitted_module_names: &mut IndexMap<String, Rc<RefCell<ModDefCore>>>,
        file: &mut VastFile,
        leaf_text: &mut Vec<String>,
        enum_remapping: &mut IndexMap<String, IndexMap<String, IndexMap<String, String>>>,
    ) {
        let core = self.core.borrow();
        let mut pipeline_counter = 0usize..;

        match emitted_module_names.entry(core.name.clone()) {
            Entry::Occupied(entry) => {
                let existing_moddef = entry.get();
                if !Rc::ptr_eq(existing_moddef, &self.core) {
                    panic!("Two distinct modules with the same name: {}", core.name);
                } else {
                    return;
                }
            }
            Entry::Vacant(entry) => {
                entry.insert(self.core.clone());
            }
        }

        if core.usage == Usage::EmitNothingAndStop {
            return;
        } else if core.usage == Usage::EmitDefinitionAndStop {
            leaf_text.push(core.generated_verilog.clone().unwrap());
            return;
        }

        // Recursively emit instances

        if core.usage == Usage::EmitDefinitionAndDescend {
            for inst in core.instances.values() {
                ModDef { core: inst.clone() }.emit_recursive(
                    emitted_module_names,
                    file,
                    leaf_text,
                    enum_remapping,
                );
            }
        }

        // Start the module declaration.

        let mut module = file.add_module(&core.name);

        let mut ports: IndexMap<String, LogicRef> = IndexMap::new();

        for port_name in core.ports.keys() {
            let io = core.ports.get(port_name).unwrap();
            if ports.contains_key(port_name) {
                panic!("Port {}.{} is already declared", core.name, port_name);
            }
            let logic_ref =
                match io {
                    IO::Input(width) => module
                        .add_input(port_name, &file.make_bit_vector_type(*width as i64, false)),
                    IO::Output(width) => module
                        .add_output(port_name, &file.make_bit_vector_type(*width as i64, false)),
                    // TODO(sherbst) 11/18/24: Replace with VAST API call
                    IO::InOut(width) => module.add_input(
                        &format!("{}{}", port_name, inout::INOUT_MARKER),
                        &file.make_bit_vector_type(*width as i64, false),
                    ),
                };
            ports.insert(port_name.clone(), logic_ref);
        }

        if core.usage == Usage::EmitStubAndStop {
            return;
        }

        // List out the wires to be used for internal connections.
        let mut nets: IndexMap<String, LogicRef> = IndexMap::new();
        for (inst_name, inst) in core.instances.iter() {
            for (port_name, io) in inst.borrow().ports.iter() {
                if self
                    .core
                    .borrow()
                    .whole_port_tieoffs
                    .contains_key(inst_name)
                    && self.core.borrow().whole_port_tieoffs[inst_name].contains_key(port_name)
                {
                    // skip whole port tieoffs; they are handled in the instantiation
                    continue;
                }
                if core.inst_connections.contains_key(inst_name)
                    && core
                        .inst_connections
                        .get(inst_name)
                        .unwrap()
                        .contains_key(port_name)
                {
                    // Don't create a wire for a port that is directly connected to a module
                    // definition port
                    continue;
                }
                let net_name = self.retrieve_net_name(inst_name, port_name);
                if ports.contains_key(&net_name) {
                    panic!(
                        "{} is already declared as a port of the module containing this instance.",
                        net_name
                    );
                }
                let data_type = file.make_bit_vector_type(io.width() as i64, false);
                if nets
                    .insert(net_name.clone(), module.add_wire(&net_name, &data_type))
                    .is_some()
                {
                    panic!(
                        "Wire name {} is already declared in module {}",
                        net_name, core.name
                    );
                }

                if inst.borrow().enum_ports.contains_key(port_name) {
                    enum_remapping
                        .entry(core.name.clone())
                        .or_default()
                        .entry(inst_name.clone())
                        .or_default()
                        .insert(
                            port_name.clone(),
                            inst.borrow().enum_ports.get(port_name).unwrap().clone(),
                        );
                }
            }
        }

        // Create wires for reserved net definitions.
        for wire in core.reserved_net_definitions.values() {
            if nets
                .insert(
                    wire.name.clone(),
                    module.add_wire(
                        &wire.name,
                        &file.make_bit_vector_type(wire.width as i64, false),
                    ),
                )
                .is_some()
            {
                panic!(
                    "Wire name {} is already declared in module {}",
                    wire.name, core.name
                );
            }
        }

        // Instantiate modules.
        for (inst_name, inst) in core.instances.iter() {
            let module_name = &inst.borrow().name;
            let instance_name = inst_name;
            let parameter_port_names: Vec<&str> = Vec::new();
            let parameter_expressions: Vec<&Expr> = Vec::new();
            let mut connection_port_names = Vec::new();
            let mut connection_expressions = Vec::new();

            for (port_name, io) in inst.borrow().ports.iter() {
                connection_port_names.push(port_name.clone());

                if core.inst_connections.contains_key(inst_name)
                    && core
                        .inst_connections
                        .get(inst_name)
                        .unwrap()
                        .contains_key(port_name)
                {
                    let mut port_slices = core
                        .inst_connections
                        .get(inst_name)
                        .unwrap()
                        .get(port_name)
                        .unwrap()
                        .clone();
                    port_slices.sort_by(|a, b| b.inst_port_slice.msb.cmp(&a.inst_port_slice.msb));

                    let mut concat_entries = Vec::new();
                    let mut msb_expected: i64 = (io.width() as i64) - 1;

                    for port_slice in port_slices {
                        // create a filler if needed
                        if port_slice.inst_port_slice.msb as i64 > msb_expected {
                            panic!(
                                "Instance connection index out of bounds for {}.{}",
                                inst_name, port_name
                            );
                        }

                        if (port_slice.inst_port_slice.msb as i64) < msb_expected {
                            let filler_msb = msb_expected;
                            let filler_lsb = (port_slice.inst_port_slice.msb as i64) + 1;
                            let net_name = format!(
                                "UNUSED_{}_{}_{}_{}",
                                inst_name, port_name, filler_msb, filler_lsb
                            );
                            let data_type =
                                file.make_bit_vector_type(filler_msb - filler_lsb + 1, false);
                            let wire = module.add_wire(&net_name, &data_type);
                            concat_entries.push(wire.to_expr());
                            if nets.insert(net_name.clone(), wire).is_some() {
                                panic!("Wire name {} is already declared in this module", net_name);
                            }
                        }

                        msb_expected = (port_slice.inst_port_slice.lsb as i64) - 1;

                        match &port_slice.connected_to {
                            PortSliceOrWire::PortSlice(port_slice) => concat_entries.push(
                                file.make_slice(
                                    &ports
                                        .get(&port_slice.port.get_port_name())
                                        .unwrap()
                                        .to_indexable_expr(),
                                    port_slice.msb as i64,
                                    port_slice.lsb as i64,
                                )
                                .to_expr(),
                            ),
                            PortSliceOrWire::Wire(wire) => {
                                concat_entries.push(nets.get(&wire.name).unwrap().to_expr());
                            }
                        }
                    }

                    if msb_expected > -1 {
                        let filler_msb = msb_expected;
                        let filler_lsb = 0;
                        let net_name = format!(
                            "UNUSED_{}_{}_{}_{}",
                            inst_name, port_name, filler_msb, filler_lsb
                        );
                        let data_type =
                            file.make_bit_vector_type(filler_msb - filler_lsb + 1, false);
                        let wire = module.add_wire(&net_name, &data_type);
                        concat_entries.push(wire.to_expr());
                        if nets.insert(net_name.clone(), wire).is_some() {
                            panic!("Wire name {} is already declared in this module", net_name);
                        }
                    }

                    if concat_entries.len() == 1 {
                        connection_expressions.push(Some(concat_entries.remove(0)));
                    } else {
                        let slice_references: Vec<&Expr> = concat_entries.iter().collect();
                        connection_expressions.push(Some(file.make_concat(&slice_references)));
                    }
                } else if self
                    .core
                    .borrow()
                    .whole_port_tieoffs
                    .contains_key(inst_name)
                    && self.core.borrow().whole_port_tieoffs[inst_name].contains_key(port_name)
                {
                    let value = self.core.borrow().whole_port_tieoffs[inst_name][port_name].clone();
                    let literal_str = format!("bits[{}]:{}", io.width(), value);
                    let value_expr = file
                        .make_literal(&literal_str, &xlsynth::ir_value::IrFormatPreference::Hex)
                        .unwrap();
                    connection_expressions.push(Some(value_expr));
                } else {
                    let net_name = self.retrieve_net_name(inst_name, port_name);
                    connection_expressions.push(Some(nets.get(&net_name).unwrap().to_expr()));
                }
            }

            let instantiation = file.make_instantiation(
                module_name,
                instance_name,
                &parameter_port_names,
                &parameter_expressions,
                &connection_port_names
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<&str>>(),
                &connection_expressions
                    .iter()
                    .map(|o| o.as_ref())
                    .collect::<Vec<_>>(),
            );
            module.add_member_instantiation(instantiation);
        }

        // Emit assign statements for connections.
        for Assignment { lhs, rhs, pipeline } in &core.assignments {
            let lhs_slice = match lhs {
                PortSlice {
                    port: Port::ModDef { name, .. },
                    msb,
                    lsb,
                } => file.make_slice(
                    &ports.get(name).unwrap().to_indexable_expr(),
                    *msb as i64,
                    *lsb as i64,
                ),
                PortSlice {
                    port:
                        Port::ModInst {
                            inst_name,
                            port_name,
                            ..
                        },
                    msb,
                    lsb,
                } => {
                    let net_name = self.retrieve_net_name(inst_name, port_name);
                    file.make_slice(
                        &nets.get(&net_name).unwrap().to_indexable_expr(),
                        *msb as i64,
                        *lsb as i64,
                    )
                }
            };
            let rhs_slice = match rhs {
                PortSlice {
                    port: Port::ModDef { name, .. },
                    msb,
                    lsb,
                } => file.make_slice(
                    &ports.get(name).unwrap().to_indexable_expr(),
                    *msb as i64,
                    *lsb as i64,
                ),
                PortSlice {
                    port:
                        Port::ModInst {
                            inst_name,
                            port_name,
                            ..
                        },
                    msb,
                    lsb,
                } => {
                    let net_name = self.retrieve_net_name(inst_name, port_name);
                    file.make_slice(
                        &nets.get(&net_name).unwrap().to_indexable_expr(),
                        *msb as i64,
                        *lsb as i64,
                    )
                }
            };
            match pipeline {
                None => {
                    let assignment =
                        file.make_continuous_assignment(&lhs_slice.to_expr(), &rhs_slice.to_expr());
                    module.add_member_continuous_assignment(assignment);
                }
                Some(pipeline) => {
                    // Find a unique name for the pipeline instance
                    let pipeline_inst_name = loop {
                        let name = format!("pipeline_conn_{}", pipeline_counter.next().unwrap());
                        if !core.instances.contains_key(&name) {
                            break name;
                        }
                    };
                    let pipeline_details = PipelineDetails {
                        file,
                        module: &mut module,
                        inst_name: &pipeline_inst_name,
                        clk: &ports
                            .get(&pipeline.clk)
                            .unwrap_or_else(|| {
                                panic!("Pipeline clock {}.{} not found.", core.name, pipeline.clk)
                            })
                            .to_expr(),
                        width: lhs.width(),
                        depth: pipeline.depth,
                        pipe_in: &rhs_slice.to_expr(),
                        pipe_out: &lhs_slice.to_expr(),
                    };
                    add_pipeline(pipeline_details);
                }
            };
        }

        // Emit assign statements for tieoffs.
        for (dst, value) in &core.tieoffs {
            if let Port::ModInst { .. } = &dst.port {
                if dst.port.io().width() == dst.width() {
                    // skip whole port tieoffs; they are handled in the instantiation
                    continue;
                }
            }
            let (dst_expr, width) = match dst {
                PortSlice {
                    port: Port::ModDef { name, .. },
                    msb,
                    lsb,
                } => (
                    file.make_slice(
                        &ports.get(name).unwrap().to_indexable_expr(),
                        *msb as i64,
                        *lsb as i64,
                    ),
                    msb - lsb + 1,
                ),
                PortSlice {
                    port:
                        Port::ModInst {
                            inst_name,
                            port_name,
                            ..
                        },
                    msb,
                    lsb,
                } => {
                    let net_name = self.retrieve_net_name(inst_name, port_name);
                    (
                        file.make_slice(
                            &nets.get(&net_name).unwrap().to_indexable_expr(),
                            *msb as i64,
                            *lsb as i64,
                        ),
                        msb - lsb + 1,
                    )
                }
            };
            let literal_str = format!("bits[{}]:{}", width, value);
            let value_expr =
                file.make_literal(&literal_str, &xlsynth::ir_value::IrFormatPreference::Hex);
            let assignment =
                file.make_continuous_assignment(&dst_expr.to_expr(), &value_expr.unwrap());
            module.add_member_continuous_assignment(assignment);
        }
    }

    /// Defines an interface with the given name. `mapping` is a map from
    /// function names to tuples of `(port_name, msb, lsb)`. For example, if
    /// `mapping` is `{"data": ("a_data", 3, 0), "valid": ("a_valid", 1, 1)}`,
    /// this defines an interface with two functions, `data` and `valid`, where
    /// the `data` function is provided by the port slice `a_data[3:0]` and the
    /// `valid` function is provided by the port slice `[1:1]`.
    pub fn def_intf(
        &self,
        name: impl AsRef<str>,
        mapping: IndexMap<String, (String, usize, usize)>,
    ) -> Intf {
        let mut core = self.core.borrow_mut();
        if core.interfaces.contains_key(name.as_ref()) {
            panic!(
                "Interface {} already exists in module {}",
                name.as_ref(),
                core.name
            );
        }
        core.interfaces.insert(name.as_ref().to_string(), mapping);
        Intf::ModDef {
            name: name.as_ref().to_string(),
            mod_def_core: Rc::downgrade(&self.core),
        }
    }

    /// Defines an interface with the given name, where the function names are
    /// derived from the port names by stripping a common prefix. For example,
    /// if the module has ports `a_data`, `a_valid`, `b_data`, and `b_valid`,
    /// calling `def_intf_from_prefix("a_intf", "a_")` will define an interface
    /// with functions `data` and `valid`, where `data` is provided by the full
    /// port `a_data` and `valid` is provided by the full port `a_valid`.
    pub fn def_intf_from_prefix(&self, name: impl AsRef<str>, prefix: impl AsRef<str>) -> Intf {
        self.def_intf_from_prefixes(name, &[prefix.as_ref()], true)
    }

    /// Defines an interface with the given name, where the function names are
    /// derived from the port names by stripping the prefix `<name>_`. For
    /// example, if the module has ports `a_data`, `a_valid`, `b_data`, and
    /// `b_valid`, calling `def_intf_from_prefix("a")` will define an
    /// interface with functions `data` and `valid`, where `data` is provided by
    /// the full port `a_data` and `valid` is provided by the full port
    /// `a_valid`.
    pub fn def_intf_from_name_underscore(&self, name: impl AsRef<str>) -> Intf {
        let prefix = format!("{}_", name.as_ref());
        self.def_intf_from_prefix(name, prefix)
    }

    /// Defines an interface with the given name, where the signals to be
    /// included are identified by those that start with one of the provided
    /// prefixies. Function names are either the signal names themselves (if
    /// `strip_prefix` is `false`) or by stripping the prefix (if `strip_prefix`
    /// is true). For example, if the module has ports `a_data`, `a_valid`,
    /// `b_data`, and `b_valid`, calling `def_intf_from_prefixes("intf", &["a_",
    /// "b_"], false)` will define an interface with functions `a_data`,
    /// `a_valid`, `b_data`, and `b_valid`, where each function is provided by
    /// the corresponding port.
    pub fn def_intf_from_prefixes(
        &self,
        name: impl AsRef<str>,
        prefixes: &[&str],
        strip_prefix: bool,
    ) -> Intf {
        let mut mapping = IndexMap::new();
        {
            let core = self.core.borrow();
            for port_name in core.ports.keys() {
                for prefix in prefixes {
                    if port_name.starts_with(prefix) {
                        let func_name = if strip_prefix {
                            port_name.strip_prefix(prefix).unwrap().to_string()
                        } else {
                            port_name.clone()
                        };
                        let port = self.get_port(port_name);
                        mapping.insert(func_name, (port_name.clone(), port.io().width() - 1, 0));
                        break;
                    }
                }
            }
        }
        self.def_intf(name, mapping)
    }

    pub fn def_intf_from_regex(
        &self,
        name: impl AsRef<str>,
        search: impl AsRef<str>,
        replace: impl AsRef<str>,
    ) -> Intf {
        self.def_intf_from_regexes(name, &[(search.as_ref(), replace.as_ref())])
    }

    pub fn def_intf_from_regexes(&self, name: impl AsRef<str>, regexes: &[(&str, &str)]) -> Intf {
        let mut mapping = IndexMap::new();
        let regexes = regexes
            .iter()
            .map(|(search, replace)| {
                (
                    Regex::new(search).expect("Failed to compile regex"),
                    replace,
                )
            })
            .collect::<Vec<_>>();
        {
            let core = self.core.borrow();
            for port_name in core.ports.keys() {
                for (regex, replace) in &regexes {
                    if regex.is_match(port_name) {
                        let func_name = regex.replace(port_name, **replace).to_string();
                        let port = self.get_port(port_name);
                        mapping.insert(func_name, (port_name.clone(), port.io().width() - 1, 0));
                        break;
                    }
                }
            }
        }
        self.def_intf(name, mapping)
    }

    /// Returns the interface with the given name; panics if an interface with
    /// that name does not exist.
    pub fn get_intf(&self, name: impl AsRef<str>) -> Intf {
        let core = self.core.borrow();
        if core.interfaces.contains_key(name.as_ref()) {
            Intf::ModDef {
                name: name.as_ref().to_string(),
                mod_def_core: Rc::downgrade(&self.core),
            }
        } else {
            panic!(
                "Interface '{}' does not exist in module '{}'",
                name.as_ref(),
                core.name
            );
        }
    }

    /// Punches a feedthrough through this module definition with the given
    /// input and output names and width. This will create two new ports on the
    /// module definition, `input_name[width-1:0]` and `output_name[width-1:0]`,
    /// and connect them together.
    pub fn feedthrough(
        &self,
        input_name: impl AsRef<str>,
        output_name: impl AsRef<str>,
        width: usize,
    ) {
        self.feedthrough_generic(input_name, output_name, width, None);
    }

    pub fn feedthrough_pipeline(
        &self,
        input_name: impl AsRef<str>,
        output_name: impl AsRef<str>,
        width: usize,
        pipeline: PipelineConfig,
    ) {
        self.feedthrough_generic(input_name, output_name, width, Some(pipeline));
    }

    fn feedthrough_generic(
        &self,
        input_name: impl AsRef<str>,
        output_name: impl AsRef<str>,
        width: usize,
        pipeline: Option<PipelineConfig>,
    ) {
        let input_port = self.add_port(input_name, IO::Input(width));
        let output_port = self.add_port(output_name, IO::Output(width));
        input_port.connect_generic(&output_port, pipeline);
    }

    /// Instantiates this module definition within a new module definition, and
    /// returns the new module definition. The new module definition has all of
    /// the same ports as the original module, which are connected directly to
    /// ports with the same names on the instance of the original module.
    pub fn wrap(&self, def_name: Option<&str>, inst_name: Option<&str>) -> ModDef {
        let original_name = &self.core.borrow().name;

        let def_name_default;
        let def_name = if let Some(name) = def_name {
            name
        } else {
            def_name_default = format!("{}_wrapper", original_name);
            def_name_default.as_str()
        };

        let wrapper = ModDef::new(def_name);

        let inst = wrapper.instantiate(self, inst_name, None);

        // Copy interface definitions.
        {
            let original_core = self.core.borrow();
            let mut wrapper_core = wrapper.core.borrow_mut();

            // Copy interface definitions
            for (intf_name, mapping) in &original_core.interfaces {
                wrapper_core
                    .interfaces
                    .insert(intf_name.clone(), mapping.clone());
            }
        }

        // For each port in the original module, add a corresponding port to the wrapper
        // and connect them.
        for (port_name, io) in self.core.borrow().ports.iter() {
            let wrapper_port = wrapper.add_port(port_name, io.clone());
            let inst_port = inst.get_port(port_name);
            wrapper_port.connect(&inst_port);
        }

        wrapper
    }

    /// Returns a new module definition that is a variant of this module
    /// definition, where the given parameters have been overridden from their
    /// default values. For example, if the module definition has a parameter
    /// `WIDTH` with a default value of `32`, calling `parameterize(&[("WIDTH",
    /// 64)])` will return a new module definition with the same ports and
    /// instances, but with the parameter `WIDTH` set to `64`. This is
    /// implemented by creating a wrapper module that instantiates the original
    /// module with the given parameters. The name of the wrapper module
    /// defaults to
    /// `<original_mod_def_name>_<param_name_0>_<param_value_0>_<param_name_1>_<param_value_1>_.
    /// ..`; this can be overridden via the optional `def_name` argument. The
    /// instance name of the original module within the wrapper is
    /// `<original_mod_def_name>_i`; this can be overridden via the optional
    /// `inst_name` argument.
    pub fn parameterize(
        &self,
        parameters: &[(&str, i32)],
        def_name: Option<&str>,
        inst_name: Option<&str>,
    ) -> ModDef {
        let core = self.core.borrow();

        if core.verilog_import.is_none() {
            panic!("Error parameterizing {}: can only parameterize a module defined in external Verilog sources.", core.name);
        }

        // Determine the name of the definition if not provided.
        let original_name = &self.core.borrow().name;
        let mut def_name_default = original_name.clone();
        for (param_name, param_value) in parameters {
            def_name_default.push_str(&format!("_{}_{}", param_name, param_value));
        }
        let def_name = def_name.unwrap_or(&def_name_default);

        // Determine the name of the instance inside the wrapper if not provided.
        let inst_name_default = format!("{}_i", original_name);
        let inst_name = inst_name.unwrap_or(&inst_name_default);

        // Determine the I/O for the module.
        let parameters_with_string_values = parameters
            .iter()
            .map(|(name, value)| (name.to_string(), value.to_string()))
            .collect::<Vec<(String, String)>>();

        let sources: Vec<&str> = core
            .verilog_import
            .as_ref()
            .unwrap()
            .sources
            .iter()
            .map(|s| s.as_str())
            .collect();

        let incdirs: Vec<&str> = core
            .verilog_import
            .as_ref()
            .unwrap()
            .incdirs
            .iter()
            .map(|s| s.as_str())
            .collect();

        let cfg = SlangConfig {
            sources: sources.as_slice(),
            incdirs: incdirs.as_slice(),
            parameters: &parameters_with_string_values
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect::<Vec<_>>(),
            ignore_unknown_modules: core.verilog_import.as_ref().unwrap().ignore_unknown_modules,
            ..Default::default()
        };

        let parser_ports = extract_ports(&cfg, true);

        // Generate a wrapper that sets the parameters to the given values.
        let mut file = VastFile::new(VastFileType::Verilog);

        let mut wrapped_module = file.add_module(def_name);
        let mut connection_port_names = Vec::new();
        let mut connection_logic_refs = Vec::new();
        let mut connection_expressions = Vec::new();
        for parser_port in parser_ports[&core.name].iter() {
            match parser_port_to_port(parser_port) {
                Ok((name, io)) => {
                    let logic_expr = match io {
                        IO::Input(width) => wrapped_module.add_input(
                            name.as_str(),
                            &file.make_bit_vector_type(width as i64, false),
                        ),
                        IO::Output(width) => wrapped_module.add_output(
                            name.as_str(),
                            &file.make_bit_vector_type(width as i64, false),
                        ),
                        // TODO(sherbst) 11/18/24: Replace with VAST API call
                        IO::InOut(width) => wrapped_module.add_input(
                            &format!("{}{}", name, inout::INOUT_MARKER),
                            &file.make_bit_vector_type(width as i64, false),
                        ),
                    };
                    connection_port_names.push(name.clone());
                    connection_expressions.push(Some(logic_expr.to_expr()));
                    connection_logic_refs.push(logic_expr);
                }
                Err(e) => {
                    if !core.verilog_import.as_ref().unwrap().skip_unsupported {
                        panic!("{e}");
                    } else {
                        continue;
                    }
                }
            }
        }

        let mut parameter_port_names = Vec::new();
        let mut parameter_port_expressions = Vec::new();

        for (name, value) in parameters {
            parameter_port_names.push(name);
            // TODO(sherbst) 09/24/2024: support parameter values other than 32-bit
            // integers.
            let literal_str = format!("bits[{}]:{}", 32, value);
            let expr = file
                .make_literal(&literal_str, &xlsynth::ir_value::IrFormatPreference::Hex)
                .unwrap();
            parameter_port_expressions.push(expr);
        }

        wrapped_module.add_member_instantiation(
            file.make_instantiation(
                core.name.as_str(),
                inst_name,
                &parameter_port_names
                    .iter()
                    .map(|&&s| s)
                    .collect::<Vec<&str>>(),
                &parameter_port_expressions.iter().collect::<Vec<_>>(),
                &connection_port_names
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<&str>>(),
                &connection_expressions
                    .iter()
                    .map(|o| o.as_ref())
                    .collect::<Vec<_>>(),
            ),
        );

        let verilog = file.emit();

        let mut ports = IndexMap::new();
        let mut enum_remapping: IndexMap<String, IndexMap<String, IndexMap<String, String>>> =
            IndexMap::new();
        for parser_port in parser_ports[&core.name].iter() {
            match parser_port_to_port(parser_port) {
                Ok((name, io)) => {
                    ports.insert(name.clone(), io.clone());
                    // Enum input ports that are not a packed array require special handling
                    // They need to have casting to be valid Verilog.
                    if let slang_rs::Type::Enum {
                        name: enum_name,
                        packed_dimensions,
                        unpacked_dimensions,
                        ..
                    } = &parser_port.ty
                    {
                        if packed_dimensions.is_empty() && unpacked_dimensions.is_empty() {
                            if let IO::Input(_) = io {
                                enum_remapping
                                    .entry(def_name.to_string())
                                    .or_default()
                                    .entry(inst_name.to_string())
                                    .or_default()
                                    .insert(name.clone(), enum_name.clone());
                            }
                        }
                    }
                }
                Err(e) => {
                    if !core.verilog_import.as_ref().unwrap().skip_unsupported {
                        panic!("{e}");
                    } else {
                        continue;
                    }
                }
            }
        }

        let verilog = enum_type::remap_enum_types(verilog, &enum_remapping);

        ModDef {
            core: Rc::new(RefCell::new(ModDefCore {
                name: def_name.to_string(),
                ports,
                enum_ports: IndexMap::new(),
                interfaces: IndexMap::new(),
                instances: IndexMap::new(),
                usage: Usage::EmitDefinitionAndStop,
                generated_verilog: Some(verilog.to_string()),
                assignments: Vec::new(),
                unused: Vec::new(),
                tieoffs: Vec::new(),
                whole_port_tieoffs: IndexMap::new(),
                verilog_import: None,
                inst_connections: IndexMap::new(),
                reserved_net_definitions: IndexMap::new(),
                specified_wire_names: IndexMap::new(),
            })),
        }
    }

    /// Validates this module hierarchically; panics if any errors are found.
    /// Validation primarily consists of checking that all inputs are driven
    /// exactly once, and all outputs are used at least once, unless
    /// specifically marked as unused. Validation behavior is controlled via the
    /// usage setting. If this module has the usage `EmitDefinitionAndDescend`,
    /// validation descends into each of those module definitions before
    /// validating the module. If this module definition has a usage other than
    /// `EmitDefinitionAndDescend`, it is not validated, and the modules it
    /// instantiates are not validated.
    pub fn validate(&self) {
        // TODO(sherbst) 10/16/2024: do not validate the same module twice

        if self.core.borrow().usage != Usage::EmitDefinitionAndDescend {
            return;
        }

        // First, recursively validate submodules
        for instance in self.core.borrow().instances.values() {
            ModDef {
                core: instance.clone(),
            }
            .validate();
        }

        let mut driven_bits: IndexMap<PortKey, DrivenPortBits> = IndexMap::new();
        let mut driving_bits: IndexMap<PortKey, DrivingPortBits> = IndexMap::new();

        // Initialize ModDef outputs
        let mod_def_core = self.core.borrow();

        for (port_name, io) in &mod_def_core.ports {
            let width = io.width();
            match io {
                IO::Output(_) => {
                    driven_bits.insert(
                        PortKey::ModDefPort {
                            mod_def_name: mod_def_core.name.clone(),
                            port_name: port_name.clone(),
                        },
                        DrivenPortBits::new(width),
                    );
                }
                IO::Input(_) | IO::InOut(_) => {
                    driving_bits.insert(
                        PortKey::ModDefPort {
                            mod_def_name: mod_def_core.name.clone(),
                            port_name: port_name.clone(),
                        },
                        DrivingPortBits::new(width),
                    );
                }
            }
        }

        // Initialize ModInst ports
        for (inst_name, inst_core) in &mod_def_core.instances {
            let inst_ports = &inst_core.borrow().ports;
            for (port_name, io) in inst_ports {
                let width = io.width();
                match io {
                    IO::Input(_) => {
                        driven_bits.insert(
                            PortKey::ModInstPort {
                                mod_def_name: mod_def_core.name.clone(),
                                inst_name: inst_name.clone(),
                                port_name: port_name.clone(),
                            },
                            DrivenPortBits::new(width),
                        );
                    }
                    IO::Output(_) | IO::InOut(_) => {
                        driving_bits.insert(
                            PortKey::ModInstPort {
                                mod_def_name: mod_def_core.name.clone(),
                                inst_name: inst_name.clone(),
                                port_name: port_name.clone(),
                            },
                            DrivingPortBits::new(width),
                        );
                    }
                }
            }
        }

        // Process unused

        for unused_slice in &self.core.borrow().unused {
            // check msb/lsb range
            unused_slice.check_validity();

            // check directionality
            if !Self::can_drive(unused_slice) {
                panic!(
                    "Cannot mark {} as unused because it is not a driver.",
                    unused_slice.debug_string()
                );
            }

            // check context
            if !Self::is_in_mod_def_core(unused_slice, &self.core) {
                panic!(
                    "Unused slice {} is not in module {}",
                    unused_slice.debug_string(),
                    self.core.borrow().name
                );
            }

            let key = unused_slice.port.to_port_key();

            let result = driving_bits
                .get_mut(&key)
                .unwrap()
                .unused(unused_slice.msb, unused_slice.lsb);

            match result {
                Err(UnusedError::AlreadyMarkedUnused) => {
                    panic!(
                        "{} is marked as unused multiple times.",
                        unused_slice.debug_string()
                    );
                }
                Err(UnusedError::AlreadyUsed) => {
                    panic!(
                        "{} is marked as unused, but is used somewhere.",
                        unused_slice.debug_string()
                    );
                }
                Ok(()) => {}
            }
        }

        // Process tieoffs

        for (tieoff_slice, _) in &self.core.borrow().tieoffs {
            // check msb/lsb range
            tieoff_slice.check_validity();

            // check directionality
            if !Self::can_be_driven(tieoff_slice) {
                panic!(
                    "Cannot tie off {} because it cannot be driven.",
                    tieoff_slice.debug_string()
                );
            }

            // check context
            if !Self::is_in_mod_def_core(tieoff_slice, &self.core) {
                panic!(
                    "Tieoff slice {} is not in module {}",
                    tieoff_slice.debug_string(),
                    self.core.borrow().name
                );
            }

            let key = tieoff_slice.port.to_port_key();

            let result = driven_bits
                .get_mut(&key)
                .unwrap()
                .driven(tieoff_slice.msb, tieoff_slice.lsb);

            if result.is_err() {
                panic!("{} is multiply driven.", tieoff_slice.debug_string());
            }
        }

        // Process assignments

        for Assignment {
            lhs: lhs_slice,
            rhs: rhs_slice,
            pipeline,
        } in &self.core.borrow().assignments
        {
            for slice in [&lhs_slice, &rhs_slice] {
                // check msb/lsb range
                slice.check_validity();

                // check context
                if !Self::is_in_mod_def_core(slice, &self.core) {
                    panic!(
                        "Slice {} is not in module {}",
                        slice.debug_string(),
                        self.core.borrow().name
                    );
                }
            }

            // check directionality

            if !Self::can_be_driven(lhs_slice) {
                panic!("{} cannot be driven.", lhs_slice.debug_string());
            }

            if !Self::can_drive(rhs_slice) {
                panic!("{} cannot drive.", rhs_slice.debug_string());
            }

            // check that widths match
            let lhs_width = lhs_slice.msb - lhs_slice.lsb + 1;
            let rhs_width = rhs_slice.msb - rhs_slice.lsb + 1;
            if lhs_width != rhs_width {
                panic!(
                    "Width mismatch in connection between {} and {}",
                    lhs_slice.debug_string(),
                    rhs_slice.debug_string()
                );
            }

            let lhs_key = lhs_slice.port.to_port_key();
            let rhs_key = rhs_slice.port.to_port_key();

            let result = driven_bits
                .get_mut(&lhs_key)
                .unwrap()
                .driven(lhs_slice.msb, lhs_slice.lsb);
            if result.is_err() {
                panic!("{} is multiply driven.", lhs_slice.debug_string());
            }

            let result = driving_bits
                .get_mut(&rhs_key)
                .unwrap()
                .driving(rhs_slice.msb, rhs_slice.lsb);
            if result.is_err() {
                panic!(
                    "{} is marked as unused, but is used somewhere.",
                    rhs_slice.debug_string()
                );
            }

            if let Some(pipeline) = &pipeline {
                let clk_key = PortKey::ModDefPort {
                    mod_def_name: mod_def_core.name.clone(),
                    port_name: pipeline.clk.clone(),
                };
                let result = driving_bits.get_mut(&clk_key).unwrap().driving(0, 0);
                if result.is_err() {
                    panic!(
                        "Pipeline clock {}.{} is marked as unused.",
                        mod_def_core.name, pipeline.clk
                    );
                }
            }
        }

        // process instance connections

        for inst_connections in mod_def_core.inst_connections.values() {
            for connections in inst_connections.values() {
                for inst_connection in connections {
                    let inst_slice = &inst_connection.inst_port_slice;
                    inst_slice.check_validity();

                    // check context
                    if !Self::is_in_mod_def_core(inst_slice, &self.core) {
                        panic!(
                            "Slice {} is not in module {}",
                            inst_slice.debug_string(),
                            self.core.borrow().name
                        );
                    }

                    // check that widths match
                    let inst_slice_width = inst_slice.msb - inst_slice.lsb + 1;
                    let connected_to_width = match &inst_connection.connected_to {
                        PortSliceOrWire::PortSlice(other_slice) => {
                            other_slice.msb - other_slice.lsb + 1
                        }
                        PortSliceOrWire::Wire(wire) => wire.width,
                    };

                    if inst_slice_width != connected_to_width {
                        panic!(
                            "Width mismatch in connection to {}",
                            inst_slice.debug_string(),
                        );
                    }

                    let inst_slice_key = inst_slice.port.to_port_key();

                    match inst_slice.port.io() {
                        IO::Input(_) => {
                            let result = driven_bits
                                .get_mut(&inst_slice_key)
                                .unwrap()
                                .driven(inst_slice.msb, inst_slice.lsb);
                            if result.is_err() {
                                panic!("{} is multiply driven.", inst_slice.debug_string());
                            }
                        }
                        IO::Output(_) | IO::InOut(_) => {
                            let result = driving_bits
                                .get_mut(&inst_slice_key)
                                .unwrap()
                                .driving(inst_slice.msb, inst_slice.lsb);
                            if result.is_err() {
                                panic!(
                                    "{} is marked as unused, but is used somewhere.",
                                    inst_slice.debug_string()
                                );
                            }
                        }
                    }

                    if let PortSliceOrWire::PortSlice(other_slice) = &inst_connection.connected_to {
                        let other_slice_key = other_slice.port.to_port_key();
                        match other_slice.port.io() {
                            IO::Output(_) => {
                                let result = driven_bits
                                    .get_mut(&other_slice_key)
                                    .unwrap()
                                    .driven(other_slice.msb, other_slice.lsb);
                                if result.is_err() {
                                    panic!("{} is multiply driven.", other_slice.debug_string());
                                }
                            }
                            IO::Input(_) | IO::InOut(_) => {
                                let result = driving_bits
                                    .get_mut(&other_slice_key)
                                    .unwrap()
                                    .driving(other_slice.msb, other_slice.lsb);
                                if result.is_err() {
                                    panic!(
                                        "{} is marked as unused, but is used somewhere.",
                                        other_slice.debug_string()
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        // driven bits should be all driven

        for (key, driven) in &driven_bits {
            if !driven.all_driven() {
                panic!("{} is not fully driven.", key.debug_string());
            }
        }

        // driving bits should be all driving or unused

        for (key, driving) in &driving_bits {
            if !driving.all_driving_or_unused() {
                panic!("{} is not fully used. If some or all of this port is unused, mark those bits as unused.", key.debug_string());
            }
        }
    }

    fn can_be_driven(slice: &PortSlice) -> bool {
        matches!(
            (&slice.port, slice.port.io(),),
            (Port::ModDef { .. }, IO::Output(_),)
                | (Port::ModInst { .. }, IO::Input(_))
                | (_, IO::InOut(_))
        )
    }

    fn can_drive(slice: &PortSlice) -> bool {
        matches!(
            (&slice.port, slice.port.io(),),
            (Port::ModDef { .. }, IO::Input(_),)
                | (Port::ModInst { .. }, IO::Output(_))
                | (_, IO::InOut(_))
        )
    }

    fn is_in_mod_def_core(slice: &PortSlice, mod_def_core: &Rc<RefCell<ModDefCore>>) -> bool {
        Rc::ptr_eq(&slice.port.get_mod_def_core(), mod_def_core)
    }
}

impl Port {
    fn get_mod_def_core(&self) -> Rc<RefCell<ModDefCore>> {
        match self {
            Port::ModDef { mod_def_core, .. } => mod_def_core.upgrade().unwrap(),
            Port::ModInst { mod_def_core, .. } => mod_def_core.upgrade().unwrap(),
        }
    }

    fn get_port_name(&self) -> String {
        match self {
            Port::ModDef { name, .. } => name.clone(),
            Port::ModInst { port_name, .. } => port_name.clone(),
        }
    }

    fn debug_string(&self) -> String {
        match self {
            Port::ModDef { name, mod_def_core } => {
                format!("{}.{}", mod_def_core.upgrade().unwrap().borrow().name, name)
            }
            Port::ModInst {
                inst_name,
                port_name,
                mod_def_core,
            } => format!(
                "{}.{}.{}",
                mod_def_core.upgrade().unwrap().borrow().name,
                inst_name,
                port_name
            ),
        }
    }

    fn debug_string_with_width(&self) -> String {
        format!("{}[{}:{}]", self.debug_string(), self.io().width() - 1, 0)
    }

    /// Connects this port to another port or port slice.
    pub fn connect<T: ConvertibleToPortSlice>(&self, other: &T) {
        self.connect_generic(other, None);
    }

    pub fn connect_pipeline<T: ConvertibleToPortSlice>(&self, other: &T, pipeline: PipelineConfig) {
        self.connect_generic(other, Some(pipeline));
    }

    fn connect_generic<T: ConvertibleToPortSlice>(
        &self,
        other: &T,
        pipeline: Option<PipelineConfig>,
    ) {
        self.to_port_slice().connect_generic(other, pipeline);
    }

    /// Ties off this port to the given constant value, specified as a `BigInt`
    /// or type that can be converted to a `BigInt`.
    pub fn tieoff<T: Into<BigInt>>(&self, value: T) {
        self.to_port_slice().tieoff(value);
    }

    /// Marks this port as unused, meaning that if it is a module instance
    /// output or module definition input, validation will not fail if the port
    /// drives nothing. In fact, validation will fail if the port drives
    /// anything.
    pub fn unused(&self) {
        self.to_port_slice().unused();
    }

    /// Returns a slice of this port from `msb` down to `lsb`, inclusive.
    pub fn slice(&self, msb: usize, lsb: usize) -> PortSlice {
        if msb >= self.io().width() || lsb > msb {
            panic!(
                "Invalid slice [{}:{}] of port {}",
                msb,
                lsb,
                self.debug_string_with_width()
            );
        }
        PortSlice {
            port: self.clone(),
            msb,
            lsb,
        }
    }

    /// Splits this port into `n` equal slices, returning a vector of port
    /// slices. For example, if this port is 8-bit wide and `n` is 4, this will
    /// return a vector of 4 port slices, each 2 bits wide: `[1:0]`, `[3:2]`,
    /// `[5:4]`, and `[7:6]`.
    pub fn subdivide(&self, n: usize) -> Vec<PortSlice> {
        self.to_port_slice().subdivide(n)
    }

    /// Create a new port called `name` on the parent module and connects it to
    /// this port.
    ///
    /// The exact behavior depends on whether this is a port on a module
    /// definition or a module instance. If this is a port on a module
    /// definition, a new port is created on the same module definition, with
    /// the same width, but opposite direction. For example, suppose that this
    /// is a port `a` on a module definition that is an 8-bit input; calling
    /// `export_as("y")` will create an 8-bit output on the same module
    /// definition called `y`.
    ///
    /// If, on the other hand, this is a port on a module instance, a new port
    /// will be created on the module definition containing the instance, with
    /// the same width and direction. For example, if this is an 8-bit input
    /// port `x` on a module instance, calling `export_as("y")` will create a
    /// new 8-bit input port `y` on the module definition that contains the
    /// instance.
    pub fn export_as(&self, name: impl AsRef<str>) -> Port {
        self.to_port_slice().export_as(name)
    }

    /// Same as export_as(), but the new port is created with the same name as
    /// the port being exported. As a result, this method can only be used with
    /// ports on module instances. The method will panic if called on a port on
    /// a module definition.
    pub fn export(&self) -> Port {
        self.to_port_slice().export()
    }

    /// Sets the wire name for the port. Only applies to ports on module instances.
    pub fn set_wire_name(&self, wire_name: impl AsRef<str>) {
        let mod_def_core = self.get_mod_def_core();
        match self {
            Port::ModInst { inst_name, port_name, .. } => {
                mod_def_core.borrow_mut().specified_wire_names
                    .entry(inst_name.clone())
                    .or_default()
                    .insert(port_name.clone(), wire_name.as_ref().to_string());
            }
            _ => panic!("set_wire_name can only be called on ports on module instances"),
        }
    }
}

impl PortSlice {
    fn debug_string(&self) -> String {
        format!("{}[{}:{}]", self.port.debug_string(), self.msb, self.lsb)
    }

    fn get_mod_def_core(&self) -> Rc<RefCell<ModDefCore>> {
        match self {
            PortSlice {
                port: Port::ModDef { mod_def_core, .. },
                ..
            } => mod_def_core.upgrade().unwrap(),
            PortSlice {
                port: Port::ModInst { mod_def_core, .. },
                ..
            } => mod_def_core.upgrade().unwrap(),
        }
    }

    /// Connects this port slice to another port or port slice. Performs some
    /// upfront checks to make sure that the connection is valid in terms of
    /// width and directionality. Panics if any of these checks fail.
    pub fn connect<T: ConvertibleToPortSlice>(&self, other: &T) {
        self.connect_generic(other, None);
    }

    pub fn connect_pipeline<T: ConvertibleToPortSlice>(&self, other: &T, pipeline: PipelineConfig) {
        self.connect_generic(other, Some(pipeline));
    }

    fn connect_generic<T: ConvertibleToPortSlice>(
        &self,
        other: &T,
        pipeline: Option<PipelineConfig>,
    ) {
        let other_as_slice = other.to_port_slice();

        let mod_def_core = self.get_mod_def_core();

        if let (IO::InOut(_), _) | (_, IO::InOut(_)) = (self.port.io(), other_as_slice.port.io()) {
            assert!(pipeline.is_none(), "Cannot pipeline inout ports");
            let mut mod_def_core_borrowed = mod_def_core.borrow_mut();
            match (&self.port, &other_as_slice.port) {
                (Port::ModDef { .. }, Port::ModDef { .. }) => {
                    panic!(
                        "Cannot short inout ports on a module definition: {} and {}",
                        self.debug_string(),
                        other_as_slice.debug_string()
                    );
                }
                (
                    Port::ModDef { .. },
                    Port::ModInst {
                        mod_def_core: _,
                        inst_name,
                        port_name,
                    },
                ) => {
                    mod_def_core_borrowed
                        .inst_connections
                        .entry(inst_name.clone())
                        .or_default()
                        .entry(port_name.clone())
                        .or_default()
                        .push(InstConnection {
                            inst_port_slice: other_as_slice.clone(),
                            connected_to: PortSliceOrWire::PortSlice((*self).clone()),
                        });
                }
                (
                    Port::ModInst {
                        mod_def_core: _,
                        inst_name,
                        port_name,
                    },
                    Port::ModDef { .. },
                ) => {
                    mod_def_core_borrowed
                        .inst_connections
                        .entry(inst_name.clone())
                        .or_default()
                        .entry(port_name.clone())
                        .or_default()
                        .push(InstConnection {
                            inst_port_slice: (*self).clone(),
                            connected_to: PortSliceOrWire::PortSlice(other_as_slice.clone()),
                        });
                }
                (
                    Port::ModInst {
                        inst_name: self_inst_name,
                        port_name: self_port_name,
                        ..
                    },
                    Port::ModInst {
                        inst_name: other_inst_name,
                        port_name: other_port_name,
                        ..
                    },
                ) => {
                    // wire definition
                    let wire_name = format!(
                        "{}_{}_{}_{}_{}_{}_{}_{}",
                        self_inst_name,
                        self_port_name,
                        self.msb,
                        self.lsb,
                        other_inst_name,
                        other_port_name,
                        other_as_slice.msb,
                        other_as_slice.lsb
                    );
                    let wire = Wire {
                        name: wire_name.clone(),
                        width: self.width(),
                    };
                    mod_def_core_borrowed
                        .reserved_net_definitions
                        .insert(wire_name, wire.clone());

                    // self inst connection
                    mod_def_core_borrowed
                        .inst_connections
                        .entry(self_inst_name.clone())
                        .or_default()
                        .entry(self_port_name.clone())
                        .or_default()
                        .push(InstConnection {
                            inst_port_slice: (*self).clone(),
                            connected_to: PortSliceOrWire::Wire(wire.clone()),
                        });

                    // other inst connection
                    mod_def_core_borrowed
                        .inst_connections
                        .entry(other_inst_name.clone())
                        .or_default()
                        .entry(other_port_name.clone())
                        .or_default()
                        .push(InstConnection {
                            inst_port_slice: other_as_slice.clone(),
                            connected_to: PortSliceOrWire::Wire(wire.clone()),
                        });
                }
            }
        } else {
            let (lhs, rhs) = match (
                &self.port,
                self.port.io(),
                &other_as_slice.port,
                other_as_slice.port.io(),
            ) {
                (Port::ModDef { .. }, IO::Output(_), Port::ModDef { .. }, IO::Input(_)) => {
                    (self, &other_as_slice)
                }
                (Port::ModDef { .. }, IO::Input(_), Port::ModDef { .. }, IO::Output(_)) => {
                    (&other_as_slice, self)
                }
                (Port::ModInst { .. }, IO::Input(_), Port::ModDef { .. }, IO::Input(_)) => {
                    (self, &other_as_slice)
                }
                (Port::ModDef { .. }, IO::Input(_), Port::ModInst { .. }, IO::Input(_)) => {
                    (&other_as_slice, self)
                }
                (Port::ModDef { .. }, IO::Output(_), Port::ModInst { .. }, IO::Output(_)) => {
                    (self, &other_as_slice)
                }
                (Port::ModInst { .. }, IO::Output(_), Port::ModDef { .. }, IO::Output(_)) => {
                    (&other_as_slice, self)
                }
                (Port::ModInst { .. }, IO::Input(_), Port::ModInst { .. }, IO::Output(_)) => {
                    (self, &other_as_slice)
                }
                (Port::ModInst { .. }, IO::Output(_), Port::ModInst { .. }, IO::Input(_)) => {
                    (&other_as_slice, self)
                }
                _ => panic!(
                    "Invalid connection between ports: {} ({} {}) and {} ({} {})",
                    self.debug_string(),
                    self.port.variant_name(),
                    self.port.io().variant_name(),
                    other_as_slice.debug_string(),
                    other_as_slice.port.variant_name(),
                    other_as_slice.port.io().variant_name()
                ),
            };

            if let Some(pipeline) = &pipeline {
                if !mod_def_core.borrow().ports.contains_key(&pipeline.clk) {
                    ModDef {
                        core: mod_def_core.clone(),
                    }
                    .add_port(pipeline.clk.clone(), IO::Input(1));
                }
            }
            let lhs = (*lhs).clone();
            let rhs = (*rhs).clone();
            mod_def_core
                .borrow_mut()
                .assignments
                .push(Assignment { lhs, rhs, pipeline });
        }
    }

    /// Ties off this port slice to the given constant value, specified as a
    /// `BigInt` or type that can be converted to a `BigInt`.
    pub fn tieoff<T: Into<BigInt>>(&self, value: T) {
        let mod_def_core = self.get_mod_def_core();

        let big_int_value = value.into();

        mod_def_core
            .borrow_mut()
            .tieoffs
            .push(((*self).clone(), big_int_value.clone()));

        if let Port::ModInst {
            inst_name,
            port_name,
            ..
        } = &self.port
        {
            if self.port.io().width() == self.width() {
                // whole port tieoff
                mod_def_core
                    .borrow_mut()
                    .whole_port_tieoffs
                    .entry(inst_name.clone())
                    .or_default()
                    .insert(port_name.clone(), big_int_value);
            }
        }
    }

    /// Marks this port slice as unused, meaning that if it is an module
    /// instance output or module definition input, validation will not fail if
    /// the slice drives nothing. In fact, validation will fail if the slice
    /// drives anything.
    pub fn unused(&self) {
        let mod_def_core = self.get_mod_def_core();
        mod_def_core.borrow_mut().unused.push((*self).clone());
    }

    fn check_validity(&self) {
        if self.msb >= self.port.io().width() {
            panic!(
                "Port slice {} is invalid: msb must be less than the width of the port.",
                self.debug_string()
            );
        } else if self.lsb > self.msb {
            panic!(
                "Port slice {} is invalid: lsb must be less than or equal to msb.",
                self.debug_string()
            );
        }
    }
}

impl ModInst {
    /// Returns the port on this instance with the given name. Panics if no such
    /// port exists.
    pub fn get_port(&self, name: impl AsRef<str>) -> Port {
        ModDef {
            core: self.mod_def_core.upgrade().unwrap().borrow().instances[&self.name].clone(),
        }
        .get_port(name)
        .assign_to_inst(self)
    }

    /// Returns a slice of the port on this instance with the given name, from
    /// `msb` down to `lsb`, inclusive. Panics if no such port exists.
    pub fn get_port_slice(&self, name: impl AsRef<str>, msb: usize, lsb: usize) -> PortSlice {
        self.get_port(name).slice(msb, lsb)
    }

    /// Returns a vector of ports on this instance with the given prefix, or all
    /// ports if `prefix` is `None`.
    pub fn get_ports(&self, prefix: Option<&str>) -> Vec<Port> {
        let result = ModDef {
            core: self.mod_def_core.upgrade().unwrap(),
        }
        .get_ports(prefix);
        result
            .into_iter()
            .map(|port| port.assign_to_inst(self))
            .collect()
    }

    /// Returns the interface on this instance with the given name. Panics if no
    /// such interface exists.
    pub fn get_intf(&self, name: impl AsRef<str>) -> Intf {
        let mod_def_core = self.mod_def_core.upgrade().unwrap();
        let instances = &mod_def_core.borrow().instances;

        let inst_core = match instances.get(&self.name) {
            Some(inst_core) => inst_core.clone(),
            None => panic!(
                "Interface '{}' does not exist on module definition '{}'",
                name.as_ref(),
                mod_def_core.borrow().name
            ),
        };

        let inst_core_borrowed = inst_core.borrow();

        if inst_core_borrowed.interfaces.contains_key(name.as_ref()) {
            Intf::ModInst {
                intf_name: name.as_ref().to_string(),
                inst_name: self.name.clone(),
                mod_def_core: self.mod_def_core.clone(),
            }
        } else {
            panic!(
                "Interface '{}' does not exist in instance '{}'",
                name.as_ref(),
                self.debug_string()
            );
        }
    }

    /// Returns the ModDef that this is an instance of.
    pub fn get_mod_def(&self) -> ModDef {
        ModDef {
            core: self
                .mod_def_core
                .upgrade()
                .unwrap()
                .borrow()
                .instances
                .get(&self.name)
                .unwrap_or_else(|| panic!("Instance named {} not found", self.name))
                .clone(),
        }
    }

    fn debug_string(&self) -> String {
        format!(
            "{}.{}",
            self.mod_def_core.upgrade().unwrap().borrow().name,
            self.name
        )
    }
}

/// Represents an interface on a module definition or module instance.
/// Interfaces are used to connect modules together by function name.
pub enum Intf {
    ModDef {
        name: String,
        mod_def_core: Weak<RefCell<ModDefCore>>,
    },
    ModInst {
        intf_name: String,
        inst_name: String,
        mod_def_core: Weak<RefCell<ModDefCore>>,
    },
}

impl std::fmt::Debug for Intf {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mod_def_core = self.get_mod_def_core();
        let core = mod_def_core.borrow();
        match self {
            Intf::ModDef { name, .. } => {
                writeln!(f, "Interface Mapping:")?;
                for (func_name, (port_name, msb, lsb)) in core.interfaces.get(name).unwrap() {
                    writeln!(
                        f,
                        "{}: (port_name: {}, msb: {}, lsb: {})",
                        func_name, port_name, msb, lsb
                    )?;
                }
            }
            Intf::ModInst {
                inst_name,
                intf_name,
                ..
            } => {
                let inst_core = core.instances.get(inst_name).unwrap();
                let inst_binding = inst_core.borrow();
                writeln!(f, "Interface Mapping:")?;
                for (func_name, (port_name, msb, lsb)) in
                    inst_binding.interfaces.get(intf_name).unwrap()
                {
                    writeln!(
                        f,
                        "{}: (port_name: {}, msb: {}, lsb: {})",
                        func_name, port_name, msb, lsb
                    )?;
                }
            }
        };

        Ok(())
    }
}

impl Intf {
    fn get_mod_def_core(&self) -> Rc<RefCell<ModDefCore>> {
        match self {
            Intf::ModDef { mod_def_core, .. } => mod_def_core.upgrade().unwrap(),
            Intf::ModInst { mod_def_core, .. } => mod_def_core.upgrade().unwrap(),
        }
    }

    fn get_port_slices(&self) -> IndexMap<String, PortSlice> {
        match self {
            Intf::ModDef {
                mod_def_core, name, ..
            } => {
                let core = mod_def_core.upgrade().unwrap();
                let binding = core.borrow();
                let mod_def = ModDef { core: core.clone() };
                let mapping = binding.interfaces.get(name).unwrap();
                mapping
                    .iter()
                    .map(|(func_name, (port_name, msb, lsb))| {
                        (
                            func_name.clone(),
                            mod_def.get_port_slice(port_name, *msb, *lsb),
                        )
                    })
                    .collect()
            }
            Intf::ModInst {
                inst_name,
                intf_name,
                mod_def_core,
                ..
            } => {
                let core = mod_def_core.upgrade().unwrap();
                let binding = core.borrow();
                let mod_def = ModDef { core: core.clone() };
                let inst = mod_def.get_instance(inst_name);
                let inst_core = binding.instances.get(inst_name).unwrap();
                let inst_binding = inst_core.borrow();
                let inst_mapping = inst_binding.interfaces.get(intf_name).unwrap();
                inst_mapping
                    .iter()
                    .map(|(func_name, (port_name, msb, lsb))| {
                        (
                            func_name.clone(),
                            inst.get_port_slice(port_name, *msb, *lsb),
                        )
                    })
                    .collect()
            }
        }
    }

    fn get_intf_name(&self) -> String {
        match self {
            Intf::ModDef { name, .. } => name.clone(),
            Intf::ModInst { intf_name, .. } => intf_name.clone(),
        }
    }

    fn debug_string(&self) -> String {
        match self {
            Intf::ModDef { name, .. } => {
                format!("{}.{}", self.get_mod_def_core().borrow().name, name)
            }
            Intf::ModInst {
                inst_name,
                intf_name,
                ..
            } => format!(
                "{}.{}.{}",
                self.get_mod_def_core().borrow().name,
                inst_name,
                intf_name
            ),
        }
    }

    /// Connects this interface to another interface. Interfaces are connected
    /// by matching up ports with the same function name and connecting them.
    /// For example, if this interface is {"data": "a_data", "valid": "a_valid"}
    /// and the other interface is {"data": "b_data", "valid": "b_valid"}, then
    /// "a_data" will be connected to "b_data" and "a_valid" will be connected
    /// to "b_valid".
    ///
    /// Unless `allow_mismatch` is `true`, this method will panic if a function
    /// in this interface is not in the other interface. Continuing the previous
    /// example, if this interface also contained function "ready", but the
    /// other interface did not, this method would panic unless `allow_mismatch`
    /// was `true`.
    pub fn connect(&self, other: &Intf, allow_mismatch: bool) {
        self.connect_generic(other, None, allow_mismatch);
    }
    pub fn connect_pipeline(&self, other: &Intf, pipeline: PipelineConfig, allow_mismatch: bool) {
        self.connect_generic(other, Some(pipeline), allow_mismatch);
    }

    fn connect_generic(
        &self,
        other: &Intf,
        pipeline: Option<PipelineConfig>,
        allow_mismatch: bool,
    ) {
        let self_ports = self.get_port_slices();
        let other_ports = other.get_port_slices();

        for (func_name, self_port) in &self_ports {
            if let Some(other_port) = other_ports.get(func_name) {
                self_port.connect_generic(other_port, pipeline.clone());
            } else if !allow_mismatch {
                panic!(
                    "Interfaces {} and {} have mismatched functions and allow_mismatch is false. Example: function '{}' is present in {} but not in {}.",
                    self.debug_string(),
                    other.debug_string(),
                    func_name,
                    self.debug_string(),
                    other.debug_string()
                );
            }
        }

        if !allow_mismatch {
            for (func_name, _) in &other_ports {
                if !self_ports.contains_key(func_name) {
                    panic!(
                        "Interfaces {} and {} have mismatched functions and allow_mismatch is false. Example: function '{}' is present in {} but not in {}",
                        self.debug_string(),
                        other.debug_string(),
                        func_name,
                        other.debug_string(),
                        self.debug_string()
                    );
                }
            }
        }
    }

    /// Signals matching regex `pattern_a` on one interface are connected to
    /// signals matching regex `pattern_b` on the other interface, and vice
    /// versa. For example, suppose that this interface is `{"data_tx":
    /// "a_data_tx", "data_rx": "a_data_rx"}` and the other interface is
    /// `{"data_tx": "b_data_tx", "data_rx": "b_data_rx"}`. One might write
    /// this_intf.crossover(&other_intf, "(.*)_tx", "(.*)_rx") to connect the
    /// `data_tx` function on this interface (mapped to `a_data_tx`) to the
    /// `data_rx` function on the other interface (mapped to `b_data_rx`), and
    /// vice versa.
    pub fn crossover(&self, other: &Intf, pattern_a: impl AsRef<str>, pattern_b: impl AsRef<str>) {
        self.crossover_generic(other, pattern_a, pattern_b, None);
    }

    pub fn crossover_pipeline(
        &self,
        other: &Intf,
        pattern_a: impl AsRef<str>,
        pattern_b: impl AsRef<str>,
        pipeline: PipelineConfig,
    ) {
        self.crossover_generic(other, pattern_a, pattern_b, Some(pipeline));
    }

    fn crossover_generic(
        &self,
        other: &Intf,
        pattern_a: impl AsRef<str>,
        pattern_b: impl AsRef<str>,
        pipeline: Option<PipelineConfig>,
    ) {
        let pattern_a_regex = Regex::new(pattern_a.as_ref()).unwrap();
        let pattern_b_regex = Regex::new(pattern_b.as_ref()).unwrap();

        let mut self_a_matches: IndexMap<String, PortSlice> = IndexMap::new();
        let mut self_b_matches: IndexMap<String, PortSlice> = IndexMap::new();
        let mut other_a_matches: IndexMap<String, PortSlice> = IndexMap::new();
        let mut other_b_matches: IndexMap<String, PortSlice> = IndexMap::new();

        const CONCAT_SEP: &str = "_";

        for (func_name, port_slice) in self.get_port_slices() {
            if let Some(captures) = pattern_a_regex.captures(&func_name) {
                self_a_matches.insert(concat_captures(&captures, CONCAT_SEP), port_slice);
            } else if let Some(captures) = pattern_b_regex.captures(&func_name) {
                self_b_matches.insert(concat_captures(&captures, CONCAT_SEP), port_slice);
            }
        }

        for (func_name, port_slice) in other.get_port_slices() {
            if let Some(captures) = pattern_a_regex.captures(&func_name) {
                other_a_matches.insert(concat_captures(&captures, CONCAT_SEP), port_slice);
            } else if let Some(captures) = pattern_b_regex.captures(&func_name) {
                other_b_matches.insert(concat_captures(&captures, CONCAT_SEP), port_slice);
            }
        }

        for (func_name, self_a_port) in self_a_matches {
            if let Some(other_b_port) = other_b_matches.get(&func_name) {
                self_a_port.connect_generic(other_b_port, pipeline.clone());
            }
        }

        for (func_name, self_b_port) in self_b_matches {
            if let Some(other_a_port) = other_a_matches.get(&func_name) {
                self_b_port.connect_generic(other_a_port, pipeline.clone());
            }
        }
    }

    /// Ties off driven signals on this interface to the given constant value. A
    /// "driven signal" is an input of a module instance or an output of a
    /// module definition; it's a signal that would appear on the left hand side
    /// of a Verilog `assign` statement.
    pub fn tieoff<T: Into<BigInt> + Clone>(&self, value: T) {
        for (_, port_slice) in self.get_port_slices() {
            match port_slice {
                PortSlice {
                    port: Port::ModDef { .. },
                    ..
                } => {
                    if let IO::Output(_) = port_slice.port.io() {
                        port_slice.tieoff(value.clone());
                    }
                }
                PortSlice {
                    port: Port::ModInst { .. },
                    ..
                } => {
                    if let IO::Input(_) = port_slice.port.io() {
                        port_slice.tieoff(value.clone());
                    }
                }
            }
        }
    }

    /// Marks unused driving signals on this interface. A "driving signal" is an
    /// output of a module instance or an input of a module definition; it's a
    /// signal that would appear on the right hand side of a Verilog `assign`
    /// statement.
    pub fn unused(&self) {
        for (_, port_slice) in self.get_port_slices() {
            match port_slice {
                PortSlice {
                    port: Port::ModDef { .. },
                    ..
                } => {
                    if let IO::Input(_) = port_slice.port.io() {
                        port_slice.unused();
                    }
                }
                PortSlice {
                    port: Port::ModInst { .. },
                    ..
                } => {
                    if let IO::Output(_) = port_slice.port.io() {
                        port_slice.unused();
                    }
                }
            }
        }
    }

    pub fn unused_and_tieoff<T: Into<BigInt> + Clone>(&self, value: T) {
        self.unused();
        self.tieoff(value);
    }

    /// Creates a new interface on the parent module and connects it to this
    /// interface. The new interface will have the same functions as this
    /// interface; signal names are formed by concatenating the given prefix and
    /// the function name. For example, if this interface is `{"data": "a_data",
    /// "valid": "a_valid"}` and the prefix is "b_", the new interface will be
    /// `{"data": "b_data", "valid": "b_valid"}`. The `name` argument specifies
    /// the name of the new interface, which is used to retrieve the interface
    /// with `get_intf`.
    pub fn export_with_prefix(&self, name: impl AsRef<str>, prefix: impl AsRef<str>) -> Intf {
        let mut mapping = IndexMap::new();
        for (func_name, port_slice) in self.get_port_slices() {
            let mod_def_port_name = format!("{}{}", prefix.as_ref(), func_name);
            port_slice.export_as(&mod_def_port_name);
            mapping.insert(func_name, (mod_def_port_name, port_slice.width() - 1, 0));
        }
        ModDef {
            core: self.get_mod_def_core(),
        }
        .def_intf(name, mapping)
    }

    /// Export an interface using the given name, with a signal prefix of the
    /// name followed by an underscore. For example, if a block has an interface
    /// called "a" with signals "a_data" and "a_valid", calling
    /// export_with_name_underscore("b") will create a new interface called "b"
    /// with signals "b_data" and "b_valid".
    pub fn export_with_name_underscore(&self, name: impl AsRef<str>) -> Intf {
        let prefix = format!("{}_", name.as_ref());
        self.export_with_prefix(name, prefix)
    }

    /// Exports an interface from a module instance to the parent module
    /// definition, returning a new interface. The new interface has the same
    /// name as the original interface, as well as the same signal names and
    /// signal functions. For example, calling this method on an interface on an
    /// intance called "a" with signals "a_data" and "a_valid" will create a new
    /// interface called "a" on the parent module definition with signals
    /// "a_data" and "a_valid".
    pub fn export(&self) -> Intf {
        if matches!(self, Intf::ModDef { .. }) {
            panic!("Cannot export() {}; must use export_with_prefix() or export_with_name_underscore() instead.", self.debug_string());
        }

        let mut mapping = IndexMap::new();
        for (func_name, port_slice) in self.get_port_slices() {
            let exported_port = port_slice.export();
            mapping.insert(
                func_name,
                (exported_port.get_port_name(), port_slice.width() - 1, 0),
            );
        }
        ModDef {
            core: self.get_mod_def_core(),
        }
        .def_intf(self.get_intf_name(), mapping)
    }

    pub fn flip_to(&self, mod_def: &ModDef) -> Intf {
        let mut mapping = IndexMap::new();
        for (func_name, port_slice) in self.get_port_slices() {
            let port = mod_def.add_port(port_slice.port.name(), port_slice.port.io().flip());
            mapping.insert(func_name, (port.get_port_name(), port_slice.width() - 1, 0));
        }
        mod_def.def_intf(self.get_intf_name(), mapping)
    }

    pub fn copy_to(&self, mod_def: &ModDef) -> Intf {
        let mut mapping = IndexMap::new();
        for (func_name, port_slice) in self.get_port_slices() {
            let port = mod_def.add_port(port_slice.port.name(), port_slice.port.io());
            mapping.insert(func_name, (port.get_port_name(), port_slice.width() - 1, 0));
        }
        mod_def.def_intf(self.get_intf_name(), mapping)
    }

    pub fn feedthrough(
        &self,
        moddef: &ModDef,
        flipped: impl AsRef<str>,
        original: impl AsRef<str>,
    ) -> (Intf, Intf) {
        self.feedthrough_generic(moddef, flipped, original, None)
    }

    pub fn feedthrough_pipeline(
        &self,
        moddef: &ModDef,
        flipped: impl AsRef<str>,
        original: impl AsRef<str>,
        pipeline: PipelineConfig,
    ) -> (Intf, Intf) {
        self.feedthrough_generic(moddef, flipped, original, Some(pipeline))
    }

    fn feedthrough_generic(
        &self,
        moddef: &ModDef,
        flipped: impl AsRef<str>,
        original: impl AsRef<str>,
        pipeline: Option<PipelineConfig>,
    ) -> (Intf, Intf) {
        let mut flipped_mapping = IndexMap::new();
        let mut original_mapping = IndexMap::new();

        for (func_name, port_slice) in self.get_port_slices() {
            let flipped_port = moddef.add_port(
                format!("{}_{}", flipped.as_ref(), func_name),
                port_slice.port.io().flip(),
            );
            let original_port = moddef.add_port(
                format!("{}_{}", original.as_ref(), func_name),
                port_slice.port.io(),
            );

            flipped_mapping.insert(
                func_name.clone(),
                (flipped_port.get_port_name(), port_slice.width() - 1, 0),
            );
            original_mapping.insert(
                func_name.clone(),
                (original_port.get_port_name(), port_slice.width() - 1, 0),
            );

            flipped_port.connect_generic(&original_port, pipeline.clone());
        }

        let flipped_intf = moddef.def_intf(flipped, flipped_mapping);
        let original_intf = moddef.def_intf(original, original_mapping);

        (flipped_intf, original_intf)
    }

    pub fn connect_through(
        &self,
        other: &Intf,
        through: &[&ModInst],
        prefix: impl AsRef<str>,
        allow_mismatch: bool,
    ) {
        let mut through_generic = Vec::new();
        for inst in through {
            through_generic.push((*inst, None));
        }
        self.connect_through_generic(other, &through_generic, prefix, allow_mismatch);
    }

    pub fn connect_through_generic(
        &self,
        other: &Intf,
        through: &[(&ModInst, Option<PipelineConfig>)],
        prefix: impl AsRef<str>,
        allow_mismatch: bool,
    ) {
        if through.is_empty() {
            self.connect(other, allow_mismatch);
            return;
        }

        let flipped = format!("{}_flipped_{}", prefix.as_ref(), self.get_intf_name());
        let original = format!("{}_original_{}", prefix.as_ref(), self.get_intf_name());

        for (i, (inst, pipeline)) in through.iter().enumerate() {
            self.feedthrough_generic(
                &inst.get_mod_def(),
                &flipped,
                &original,
                pipeline.as_ref().cloned(),
            );
            if i == 0 {
                self.connect(&inst.get_intf(&flipped), false);
            } else {
                through[i - 1]
                    .0
                    .get_intf(&original)
                    .connect(&inst.get_intf(&flipped), false);
            }

            if i == through.len() - 1 {
                other.connect(&inst.get_intf(&original), allow_mismatch);
            }
        }
    }

    pub fn crossover_through(
        &self,
        other: &Intf,
        through: &[&ModInst],
        pattern_a: impl AsRef<str>,
        pattern_b: impl AsRef<str>,
        prefix: impl AsRef<str>,
    ) {
        let mut through_generic = Vec::new();
        for inst in through {
            through_generic.push((*inst, None));
        }
        self.crossover_through_generic(other, &through_generic, pattern_a, pattern_b, prefix);
    }

    pub fn crossover_through_generic(
        &self,
        other: &Intf,
        through: &[(&ModInst, Option<PipelineConfig>)],
        pattern_a: impl AsRef<str>,
        pattern_b: impl AsRef<str>,
        prefix: impl AsRef<str>,
    ) {
        if through.is_empty() {
            self.crossover(other, pattern_a, pattern_b);
            return;
        }

        let flipped = format!("{}_flipped_{}", prefix.as_ref(), self.get_intf_name());
        let original = format!("{}_original_{}", prefix.as_ref(), other.get_intf_name());

        for (i, (inst, pipeline)) in through.iter().enumerate() {
            self.feedthrough_generic(
                &inst.get_mod_def(),
                &flipped,
                &original,
                pipeline.as_ref().cloned(),
            );
            if i == 0 {
                self.connect(&inst.get_intf(&flipped), false);
            } else {
                through[i - 1]
                    .0
                    .get_intf(&original)
                    .connect(&inst.get_intf(&flipped), false);
            }

            if i == through.len() - 1 {
                other.crossover(&inst.get_intf(&original), &pattern_a, &pattern_b);
            }
        }
    }

    /// Divides each signal in this interface into `n` equal slices, returning a
    /// vector of interfaces. For example, if this interface is `{"data":
    /// "a_data[31:0]", "valid": "a_valid[3:0]"}` and `n` is 4, this will return
    /// a vector of 4 interfaces, each with signals `{"data": "a_data[7:0]",
    /// "valid": "a_valid[0:0]"}`, `{"data": "a_data[15:8]", "valid":
    /// "a_valid[1:1]"}`, and so on. The names of the new interfaces are formed
    /// by appending "_0", "_1", "_2", and so on to the name of this interface;
    /// these names can be used to retrieve specific slices of the interface
    /// with `get_intf`.
    pub fn subdivide(&self, n: usize) -> Vec<Intf> {
        let mut result = Vec::new();

        let mut mappings: Vec<IndexMap<String, (String, usize, usize)>> = Vec::with_capacity(n);
        for _ in 0..n {
            mappings.push(IndexMap::new());
        }

        for (func_name, port_slice) in self.get_port_slices() {
            let slices = port_slice.subdivide(n);
            for (i, slice) in slices.into_iter().enumerate() {
                let port_name = port_slice.port.get_port_name();
                mappings[i].insert(func_name.clone(), (port_name.clone(), slice.msb, slice.lsb));
            }
        }

        for i in 0..n {
            let intf = match self {
                Intf::ModDef { name, .. } => {
                    let name = format!("{}_{}", name, i);
                    ModDef {
                        core: self.get_mod_def_core(),
                    }
                    .def_intf(&name, mappings.remove(0))
                }
                _ => panic!(
                    "Error subdividing {}: subdividing ModInst interfaces is not supported.",
                    self.debug_string()
                ),
            };
            result.push(intf);
        }

        result
    }
}

pub struct Funnel {
    a_in: PortSlice,
    a_out: PortSlice,
    b_in: PortSlice,
    b_out: PortSlice,
    a_in_offset: usize,
    a_out_offset: usize,
}

impl Funnel {
    pub fn new(
        a: (impl ConvertibleToPortSlice, impl ConvertibleToPortSlice),
        b: (impl ConvertibleToPortSlice, impl ConvertibleToPortSlice),
    ) -> Self {
        let a0 = a.0.to_port_slice();
        let a1 = a.1.to_port_slice();

        let (a_in, a_out) = match (a0.port.io(), a1.port.io()) {
            (IO::Input(_), IO::Output(_)) => (a0, a1),
            (IO::Output(_), IO::Input(_)) => (a1, a0),
            (IO::Input(_), IO::Input(_)) => panic!(
                "Funnel error: Side A cannot have both ports as inputs ({} and {})",
                a0.debug_string(),
                a1.debug_string()
            ),
            (IO::Output(_), IO::Output(_)) => panic!(
                "Funnel error: Side A cannot have both ports as outputs ({} and {})",
                a0.debug_string(),
                a1.debug_string()
            ),
            (IO::InOut(_), _) => panic!(
                "Funnel error: Side A cannot have inout ports ({})",
                a0.debug_string()
            ),
            (_, IO::InOut(_)) => panic!(
                "Funnel error: Side A cannot have inout ports ({})",
                a1.debug_string()
            ),
        };

        let b0 = b.0.to_port_slice();
        let b1 = b.1.to_port_slice();

        let (b_in, b_out) = match (b0.port.io(), b1.port.io()) {
            (IO::Input(_), IO::Output(_)) => (b0, b1),
            (IO::Output(_), IO::Input(_)) => (b1, b0),
            (IO::Input(_), IO::Input(_)) => panic!(
                "Funnel error: Side B cannot have both ports as inputs ({}, {})",
                b0.debug_string(),
                b1.debug_string()
            ),
            (IO::Output(_), IO::Output(_)) => panic!(
                "Funnel error: Side B cannot have both ports as outputs ({}, {})",
                b0.debug_string(),
                b1.debug_string()
            ),
            (IO::InOut(_), _) => panic!(
                "Funnel error: Side B cannot have inout ports ({})",
                b0.debug_string()
            ),
            (_, IO::InOut(_)) => panic!(
                "Funnel error: Side B cannot have inout ports ({})",
                b1.debug_string()
            ),
        };

        assert!(
            a_in.width() == b_out.width(),
            "Funnel error: Side A input and side B output must have the same width ({}, {})",
            a_in.debug_string(),
            b_out.debug_string()
        );
        assert!(
            a_out.width() == b_in.width(),
            "Funnel error: Side A output and side B input must have the same width ({}, {})",
            a_out.debug_string(),
            b_in.debug_string()
        );

        Self {
            a_in,
            a_out,
            b_in,
            b_out,
            a_in_offset: 0,
            a_out_offset: 0,
        }
    }

    pub fn connect(&mut self, a: &impl ConvertibleToPortSlice, b: &impl ConvertibleToPortSlice) {
        let a = a.to_port_slice();
        let b = b.to_port_slice();

        assert!(
            a.width() == b.width(),
            "Funnel error: a and b must have the same width ({}, {})",
            a.debug_string(),
            b.debug_string()
        );

        if a.port.is_driver() {
            if b.port.is_driver() {
                panic!(
                    "Funnel error: Cannot connect two outputs together ({}, {})",
                    a.debug_string(),
                    b.debug_string()
                );
            } else {
                assert!(
                    self.a_in_offset + a.width() <= self.a_in.width(),
                    "Funnel out of capacity."
                );
                self.a_in
                    .slice_relative(self.a_in_offset, a.width())
                    .connect(&a);
                self.b_out
                    .slice_relative(self.a_in_offset, b.width())
                    .connect(&b);
                self.a_in_offset += a.width();
            }
        } else if b.port.is_driver() {
            assert!(
                self.a_out_offset + a.width() <= self.a_out.width(),
                "Funnel out of capacity."
            );
            self.a_out
                .slice_relative(self.a_out_offset, a.width())
                .connect(&a);
            self.b_in
                .slice_relative(self.a_out_offset, b.width())
                .connect(&b);
            self.a_out_offset += a.width();
        } else {
            panic!(
                "Funnel error: Cannot connect two inputs together ({}, {})",
                a.debug_string(),
                b.debug_string()
            );
        }
    }

    pub fn connect_intf(&mut self, a: &Intf, b: &Intf, allow_mismatch: bool) {
        let a_ports = a.get_port_slices();
        let b_ports = b.get_port_slices();

        for (a_func_name, a_port) in &a_ports {
            if let Some(b_port) = b_ports.get(a_func_name) {
                self.connect(a_port, b_port);
            } else if !allow_mismatch {
                panic!("Funnel error: interfaces {} and {} have mismatched functions and allow_mismatch is false. Example: function '{}' is present in {} but not in {}",
                    a.debug_string(),
                    b.debug_string(),
                    a_func_name,
                    a.debug_string(),
                    b.debug_string()
                );
            }
        }

        if !allow_mismatch {
            for (func_name, _) in &b_ports {
                if !a_ports.contains_key(func_name) {
                    panic!(
                        "Interfaces {} and {} have mismatched functions and allow_mismatch is false. Example: function '{}' is present in {} but not in {}",
                        a.debug_string(),
                        b.debug_string(),
                        func_name,
                        b.debug_string(),
                        a.debug_string()
                    );
                }
            }
        }
    }

    pub fn crossover_intf(
        &mut self,
        x: &Intf,
        y: &Intf,
        pattern_a: impl AsRef<str>,
        pattern_b: impl AsRef<str>,
    ) {
        let pattern_a_regex = Regex::new(pattern_a.as_ref()).unwrap();
        let pattern_b_regex = Regex::new(pattern_b.as_ref()).unwrap();

        let mut x_a_matches: IndexMap<String, PortSlice> = IndexMap::new();
        let mut x_b_matches: IndexMap<String, PortSlice> = IndexMap::new();
        let mut y_a_matches: IndexMap<String, PortSlice> = IndexMap::new();
        let mut y_b_matches: IndexMap<String, PortSlice> = IndexMap::new();

        const CONCAT_SEP: &str = "_";

        for (x_func_name, x_port_slice) in x.get_port_slices() {
            if let Some(captures) = pattern_a_regex.captures(&x_func_name) {
                x_a_matches.insert(concat_captures(&captures, CONCAT_SEP), x_port_slice);
            } else if let Some(captures) = pattern_b_regex.captures(&x_func_name) {
                x_b_matches.insert(concat_captures(&captures, CONCAT_SEP), x_port_slice);
            }
        }

        for (y_func_name, y_port_slice) in y.get_port_slices() {
            if let Some(captures) = pattern_a_regex.captures(&y_func_name) {
                y_a_matches.insert(concat_captures(&captures, CONCAT_SEP), y_port_slice);
            } else if let Some(captures) = pattern_b_regex.captures(&y_func_name) {
                y_b_matches.insert(concat_captures(&captures, CONCAT_SEP), y_port_slice);
            }
        }

        for (x_func_name, x_port_slice) in x_a_matches {
            if let Some(y_port_slice) = y_b_matches.get(&x_func_name) {
                self.connect(&x_port_slice, y_port_slice);
            }
        }

        for (x_func_name, x_port_slice) in x_b_matches {
            if let Some(y_port_slice) = y_a_matches.get(&x_func_name) {
                self.connect(&x_port_slice, y_port_slice);
            }
        }
    }

    pub fn done(&mut self) {
        if self.a_in_offset != self.a_in.width() {
            self.a_in
                .slice_relative(self.a_in_offset, self.a_in.width() - self.a_in_offset)
                .tieoff(0);
            self.b_out
                .slice_relative(self.a_in_offset, self.b_out.width() - self.a_in_offset)
                .unused();
            self.a_in_offset = self.a_in.width();
        }

        if self.a_out_offset != self.a_out.width() {
            self.a_out
                .slice_relative(self.a_out_offset, self.a_out.width() - self.a_out_offset)
                .unused();
            self.b_in
                .slice_relative(self.a_out_offset, self.b_in.width() - self.a_out_offset)
                .tieoff(0);
            self.a_out_offset = self.a_out.width();
        }
    }
}

fn parser_port_to_port(parser_port: &slang_rs::Port) -> Result<(String, IO), String> {
    let size = parser_port.ty.width().unwrap();
    let port_name = parser_port.name.clone();

    match parser_port.dir {
        slang_rs::PortDir::Input => Ok((port_name, IO::Input(size))),
        slang_rs::PortDir::Output => Ok((port_name, IO::Output(size))),
        slang_rs::PortDir::InOut => Ok((port_name, IO::InOut(size))),
    }
}

fn concat_captures(captures: &regex::Captures, sep: &str) -> String {
    captures
        .iter()
        .skip(1)
        .filter_map(|m| m.map(|m| m.as_str().to_string()))
        .collect::<Vec<String>>()
        .join(sep)
}