vj 0.3.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
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
//! Net resolution (LRM 1800-2023 §28.12, Table 28-7/28-8): nets whose
//! value is the resolution of several drivers, or of a net type with its own
//! rule (`tri0`/`tri1` pull, `wand`/`wor` wired logic, `supply0/1`).
//!
//! A net needs resolving when it has two or more continuous drivers -- a
//! continuous assign or net declaration assignment, a primitive's output
//! terminal (`crate::primitives`), a port connection driving it (a child's
//! input port net, a parent net on an output port) --
//! or when its net type resolves on its own (`tri0`, `tri1`, `wand`,
//! `triand`, `wor`, `trior`, `supply0`, `supply1`). An `inout` port
//! connection makes the parent net and the child's port net one net (a
//! group), resolved together and seen identically on both sides; so does
//! an `alias` (LRM 1800-2023 §10.11).
//!
//! Bidirectional switches (`tran`, `tranif0`, `tranif1` and their resistive
//! `r` forms, §28.8) connect bits of groups into a switch network
//! ([`Network`]), resolved as a whole by `crate::switches`: every group a
//! switch touches has all its drivers routed to contributions, whatever
//! their number.
//!
//! Each driver of a resolved group writes its own contribution cell (in one
//! synthetic "bank" state instance, every cell starting all-`z`, i.e. not
//! driving) instead of the net; a resolver process, sensitive to every
//! contribution of the group, folds them per bit
//! (`vj_sim::state::resolve_values`) and writes the result to each net
//! of the group. A net with a single ordinary driver is left alone.

use std::collections::{HashMap, HashSet};

use sv_lang::kinds::{ExpressionKind, SymbolKind};
use sv_lang::{ArgumentDirection, Expression, Symbol, SyntaxTree};
use vj_codegen::process_lower::{SignalSlot, SignalSlotClass};
use vj_sim::netlist::InstanceId;
use vj_sim::state::{DriveStrength, DriveStrengthPair, NetKind};
use vj_sim::symid::{SymbolId, SymbolUid};

/// A net: its instance and symbol.
pub(crate) type NetId = (InstanceId, SymbolId);

/// One continuous driver: the construct and the net it drives.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub(crate) enum DriverKey {
    /// A continuous assign (its symbol) or net declaration assignment (the
    /// net's symbol), in `InstanceId`.
    /// Hidden cell number `u32` of a primitive input terminal expression in
    /// `InstanceId` (`primitives::HiddenTerm`): written by a kernel of that
    /// instance, never a driver of any net.
    Hidden(InstanceId, u32),
    Assign(InstanceId, SymbolId, SymbolId),
    /// Port `port` of child instance `InstanceId`, driving net `SymbolId`
    /// (the child's input port net, or a parent net on an output port).
    Port(InstanceId, SymbolId, SymbolId),
    /// Primitive instance `SymbolId` in `InstanceId`, driving net
    /// `SymbolId` from an output terminal.
    Prim(InstanceId, SymbolId, SymbolId),
    /// Primitive instance `SymbolId` in `InstanceId`, driving the element
    /// `Vec<i64>` of the interconnect array `SymbolId` (a terminal on such an
    /// element is a scalar wire, LRM 23.3.3.7.2).
    PrimElem(InstanceId, SymbolId, SymbolId, Vec<i64>),
    /// A module path's own retimed commit point for net `SymbolId` in
    /// `InstanceId` (`docs/superpowers/plans/2026-10-03-sdf.md` Task 4a) --
    /// unlike the three variants above, this one never names the
    /// CONSTRUCT that drives the net (a module path never independently
    /// decides a value, LRM 30.6's own text -- `crate::specify::plan`'s own
    /// module doc explains why), only the NET it retimes, since LRM 30.5.3
    /// merges every module path that targets one destination bit into one
    /// retimer (Task 6's own scope) sharing one commit point. Looked up the
    /// SAME way [`DriverKey::Prim`] is (`Resolution::slot`) -- `None` until
    /// a future task (multi-driver mixing, Task 9) actually inserts an
    /// entry for it; a net with a single ordinary driver writes directly
    /// (see [`crate::specify::plan`]'s own doc comment).
    SpecifyPath(InstanceId, SymbolId),
    /// A module path's VARIABLE destination (LRM 30.4.1's "net or
    /// variable"; `docs/superpowers/plans/2026-10-03-sdf.md` Task 4b),
    /// written by exactly one nonblocking procedural assignment in
    /// `InstanceId` -- unlike [`DriverKey::Assign`] (keyed on the
    /// CONTINUOUS-ASSIGN construct that drives a net), there is no single
    /// `SymbolId` construct to key on here (the driver is a statement
    /// inside a `ProceduralBlock`, not a module member with its own
    /// identity `crate::specify::plan` can re-locate the way a
    /// `ContinuousAssign` symbol is), so this variant names only the
    /// DESTINATION variable itself, exactly like [`DriverKey::SpecifyPath`]
    /// does for nets. Looked up by `vj-codegen`'s own lvalue-write
    /// lowering (`crate::run::run_design`'s `specify_dest_redirect` wiring)
    /// to redirect EVERY procedural write of the variable (blocking writes
    /// at their segment's flush, nonblocking writes at their staging; one
    /// statement or several) to its one staging cell.
    ProcVar(InstanceId, SymbolId),
}

/// A switch's ends (instance, net, bit), when it conducts, and whether it
/// is resistive, before the groups exist; the last pair names the storage row
/// of each end that is an element of an unpacked-array net (LRM 28.7).
type PendingSwitch = (
    (InstanceId, SymbolId, u32),
    (InstanceId, SymbolId, u32),
    Conducts,
    bool,
    (Option<u32>, Option<u32>),
);

/// The joint a switch end names: one row of an unpacked-array net, or a net.
fn end_joint(n: NetId, row: Option<u32>) -> Joint {
    match row {
        Some(r) => Joint::Row(n, r),
        None => Joint::Typed(n),
    }
}

/// A group of nets resolved together.
pub(crate) struct Group {
    pub kind: NetKind,
    pub width: u32,
    /// The nets (one, or several joined by `inout` ports).
    pub nets: Vec<NetId>,
    /// Each driver's bank slot and strength.
    pub drivers: Vec<(u32, DriveStrengthPair)>,
    /// Part of a switch network (`Resolution::networks`), which resolves it.
    pub switched: bool,
    /// The user-defined nettype (an index into `UserNets::types`) of a group
    /// of user-nettype nets, resolved by its resolution function instead of
    /// per bit (LRM 6.6.7).
    pub user: Option<usize>,
    /// Elements of unpacked-array nets (net, row in storage order) that are
    /// part of this ONE simulated net: each array element is a net of its own
    /// (LRM 6.6.7), and a port or interconnect connection merges elements one
    /// by one (6.6.8, 23.3.3.7). `width` is an element's width.
    pub rows: Vec<(NetId, u32)>,
    /// Bank cells (1 bit) of interconnect array elements a primitive terminal
    /// is connected to: such an element is a scalar wire (LRM 23.3.3.7.2),
    /// written by this group like a net.
    pub cells: Vec<u32>,
    /// Parallel to `drivers`: the row of the driver's contribution MEMORY
    /// that belongs to this group (`None`: the driver's cell is one value).
    pub driver_rows: Vec<Option<u32>>,
}

/// One continuous driver of a net: its key, strength and, for an unpacked-array
/// net, the element it addresses (`None`: the whole net).
#[derive(Clone)]
struct Driver {
    key: DriverKey,
    strength: DriveStrengthPair,
    path: Option<ElemPath>,
}

/// An output port connected to a whole net of the same width (see
/// `analyze`): the child's port net, the parent net, the port, and the
/// parent-net driver the port would otherwise be.
struct OutCand {
    child: NetId,
    /// The parent nets the port's drivers land on (one for a whole-net
    /// connection).
    parents: Vec<NetId>,
    port: (InstanceId, SymbolId),
    keys: Vec<DriverKey>,
    /// A connection to a constant select or a concatenation of nets: the
    /// bit-by-bit joints to make instead of unioning whole nets
    /// (LRM 23.3.3.2).
    switches: Option<Vec<PendingSwitch>>,
}

/// A bidirectional switch's control terminal.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Control {
    /// Bit `u32` of a signal of an instance.
    Bit(InstanceId, SignalSlot, u32),
    /// A constant: 0, 1, or 2 for unknown.
    Const(u8),
    /// A 1-bit bank cell: a delayed copy of the written control, which a
    /// `tranif*` with a turn-on/turn-off delay conducts on (LRM 28.8, 28.16;
    /// see [`DelayedControl`]).
    Bank(u32),
}

/// The delay line of a `tranif0/1` (`rtranif0/1`) with a turn-on/turn-off
/// delay (LRM 28.16: the first delay is the control's turn-on, the second its
/// turn-off, the smaller applies to a change to x/z, one delay is both). The
/// switch conducts on the bank cell `cell`, which `crate::primitives::plan`
/// drives from `source` through a delay line.
#[derive(Clone, Debug)]
pub(crate) struct DelayedControl {
    pub inst: InstanceId,
    pub prim: SymbolId,
    pub source: (InstanceId, SignalSlot, u32),
    pub cell: u32,
    /// `tranif1` (`true`) turns on when the control rises to 1; `tranif0`
    /// when it falls to 0.
    pub on_is_one: bool,
}

/// When a bidirectional switch conducts.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Conducts {
    Always,
    /// `tranif1` (`true`) / `tranif0` (`false`): when the control is 1 / 0.
    When(Control, bool),
}

/// One bit-to-bit bidirectional switch: `(group, bit)` ends, indices into
/// `Resolution::groups`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Switch {
    pub a: (usize, u32),
    pub b: (usize, u32),
    pub conducts: Conducts,
    /// `rtran*`: a signal crossing it loses a strength level.
    pub resistive: bool,
}

/// Groups connected by bidirectional switches, resolved together.
pub(crate) struct Network {
    pub groups: Vec<usize>,
    pub switches: Vec<Switch>,
}

/// The resolved nets of a design.
#[derive(Default)]
pub(crate) struct Resolution {
    pub groups: Vec<Group>,
    /// A resolved driver's contribution slot in the bank.
    pub contrib: HashMap<DriverKey, u32>,
    /// The bank's slot widths.
    pub bank_widths: Vec<u32>,
    /// `inout` port connections (child, port) realized by a group, not a
    /// port wire.
    pub inout_ports: HashSet<(InstanceId, SymbolId)>,
    /// The switch networks (`crate::switches`).
    pub networks: Vec<Network>,
    /// A contribution slot's strength-ambiguity mask slot: its bits that are
    /// `L`/`H` (`crate::primitives`), 0 or 1 at the value's strength or `z`.
    pub ambiguous: HashMap<u32, u32>,
    /// A MOS gate driver's strength source (its data input's net): the
    /// `%v` strength passes through the gate (`crate::primitives`).
    pub strength_src: HashMap<u32, vj_sim::image::StrengthSrc>,
    /// A group's strength-change bank cell, by index into `groups`, for each
    /// group some `strength_src` reads.
    pub strength_ticks: HashMap<usize, u32>,
    /// The bank slots that are memories: one contribution cell per driver of
    /// an unpacked-array net whose elements are resolved one by one. Each is
    /// the array's own slot description (leaf width, class, row count).
    pub bank_mem: HashMap<u32, SignalSlot>,
    /// The bank cell of an interconnect array element a primitive terminal
    /// is connected to (instance, net, index path).
    pub ic_elem: HashMap<IcElem, u32>,
    /// Unconnected input-port nets of modules under `` `unconnected_drive ``
    /// (LRM 22.5.2): (instance, port, port net, pulled to one). Each has a
    /// pull-strength [`DriverKey::Prim`] driver (keyed on the port) that
    /// `crate::primitives::plan` writes as a constant `pullup`/`pulldown`.
    pub open_pulls: Vec<(InstanceId, SymbolId, SymbolId, bool)>,
    /// The delayed controls of switches with a turn-on/turn-off delay.
    pub delayed_controls: Vec<DelayedControl>,
}

/// One element of an interconnect array: (instance, net, index path).
pub(crate) type IcElem = (InstanceId, SymbolId, Vec<i64>);

impl Resolution {
    /// The contribution slot of driver `key`, if its net is resolved.
    pub(crate) fn slot(&self, key: &DriverKey) -> Option<u32> {
        self.contrib.get(key).copied()
    }
}

fn strong() -> DriveStrengthPair {
    DriveStrengthPair {
        s0: DriveStrength::Strong,
        s1: DriveStrength::Strong,
    }
}

/// An sv-lang strength pair as STATE's (unspecified = strong; `highz` =
/// weakest).
fn strength_of(p: sv_lang::DriveStrengthPair) -> DriveStrengthPair {
    let one = |s: Option<sv_lang::DriveStrength>| match s {
        None | Some(sv_lang::DriveStrength::Strong) => DriveStrength::Strong,
        Some(sv_lang::DriveStrength::Supply) => DriveStrength::Supply,
        Some(sv_lang::DriveStrength::Pull) => DriveStrength::Pull,
        Some(sv_lang::DriveStrength::HighZ) => DriveStrength::HighZ,
        Some(_) => DriveStrength::Weak,
    };
    DriveStrengthPair {
        s0: one(p.strength0),
        s1: one(p.strength1),
    }
}

/// Per net, the `(lo, width)` windows its drivers drive (`None`: the whole net).
pub(crate) type DrivenWindows = HashMap<(InstanceId, SymbolId), Vec<Option<(u32, u32)>>>;

/// Whether a net symbol's value type is 4-state. A 2-state port such as
/// `input int a` has a net internal symbol, but no X or Z exists to start it
/// at: it keeps its 2-state default of 0 (LRM 1800-2023 6.8, Table 6-7) until
/// its connection is evaluated.
fn is_four_state_net(net: Symbol<'_>) -> bool {
    net.value_type().is_none_or(|t| t.is_four_state())
}

/// The bits of each net that some driver drives -- a net declaration
/// assignment, a continuous assignment, a primitive output or a port
/// connection -- as `(lo, width)` windows (`None`: the whole net). A driven
/// bit starts X (its driver has produced no value yet: a delayed `assign #2`
/// leaves it X until then), an undriven one Z (LRM 6.6.1).
pub(crate) fn driven_windows<'d>(
    instances: &[(InstanceId, Symbol<'d>, Symbol<'d>, Option<InstanceId>)],
    signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    trees: &[SyntaxTree],
) -> DrivenWindows {
    type Windows = DrivenWindows;
    fn add<'d>(
        out: &mut Windows,
        id: InstanceId,
        e: Expression<'d>,
        own: &HashMap<SymbolId, SignalSlot>,
    ) {
        for (root, window) in lvalue_windows(e, own) {
            if root.kind() == SymbolKind::Net && is_four_state_net(root) {
                out.entry((id, root.uid())).or_default().push(window);
            }
        }
    }
    let mut out: Windows = HashMap::new();
    for (id, body, _, _) in instances {
        for m in vj_sim::netlist::module_items(body) {
            if m.kind() == SymbolKind::Net && m.initializer().is_some() {
                out.entry((*id, m.uid())).or_default().push(None);
            } else if m.kind() == SymbolKind::ContinuousAssign
                && let Some(lhs) = m.continuous_assign_assignment().and_then(|a| a.left())
            {
                add(&mut out, *id, lhs, &signals[id]);
            }
        }
        for inst in crate::primitives::instances(body) {
            if let Ok(sh) = crate::primitives::shape(&inst, trees) {
                for o in sh.outputs {
                    add(&mut out, *id, o, &signals[id]);
                }
            }
        }
    }
    for (id, _, inst, parent) in instances {
        let Some(parent) = parent else {
            continue;
        };
        for conn in inst.instance_port_connections() {
            let port = conn.port();
            if port.kind() == SymbolKind::InterfacePort {
                continue;
            }
            let Some(expr) = conn.expression() else {
                continue;
            };
            let member = port.port_internal_symbol().unwrap_or(port);
            match port.port_direction() {
                ArgumentDirection::In
                    if member.kind() == SymbolKind::Net && is_four_state_net(member) =>
                {
                    out.entry((*id, member.uid())).or_default().push(None);
                }
                ArgumentDirection::Out => {
                    let lhs = if expr.kind() == ExpressionKind::Assignment {
                        expr.left()
                    } else {
                        Some(expr)
                    };
                    if let Some(lhs) = lhs {
                        add(&mut out, *parent, lhs, &signals[parent]);
                    }
                }
                ArgumentDirection::In | ArgumentDirection::InOut | ArgumentDirection::Ref => {}
            }
        }
    }
    out
}

/// The window of a one-dimensional unpacked-array net `e` (a select chain
/// over it) drives, in the net's flat bit image (`row * row_width + bit`):
/// `None` unless the element index and any bit/part select are constants.
fn memory_window(
    e: Expression<'_>,
    row_width: u32,
    num_rows: u32,
    lower_index: i64,
) -> Option<(u32, u32)> {
    // The select applied directly to the array is the element select.
    let mut row_sel = e;
    loop {
        let base = row_sel.select_value()?;
        if !matches!(
            base.kind(),
            ExpressionKind::ElementSelect | ExpressionKind::RangeSelect
        ) {
            break;
        }
        row_sel = base;
    }
    // One unpacked dimension only: a row is then one element.
    if row_sel.kind() != ExpressionKind::ElementSelect
        || row_sel.expr_type().is_none_or(|t| t.is_unpacked_array())
    {
        return None;
    }
    let row = row_sel
        .selector()?
        .constant_value()?
        .as_i64()?
        .checked_sub(lower_index)?;
    if row < 0 || row >= i64::from(num_rows) {
        return None;
    }
    let (lo, width) = vj_codegen::select::constant_window_skip(e, row_width, 1).ok()?;
    Some((row as u32 * row_width + lo, width))
}

/// The `(net, window)` pairs an lvalue expression drives: a name is the whole
/// net, a constant select its window, a concatenation each operand's; any
/// other target conservatively counts as its whole roots.
fn lvalue_windows<'d>(
    e: Expression<'d>,
    own: &HashMap<SymbolId, SignalSlot>,
) -> Vec<(Symbol<'d>, Option<(u32, u32)>)> {
    let mut e = e;
    while e.kind() == ExpressionKind::Conversion {
        match e.operand() {
            Some(o) => e = o,
            None => break,
        }
    }
    match e.kind() {
        ExpressionKind::Concatenation => e
            .operands()
            .into_iter()
            .flat_map(|o| lvalue_windows(o, own))
            .collect(),
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect => {
            let mut base = e;
            while let ExpressionKind::ElementSelect | ExpressionKind::RangeSelect = base.kind() {
                match base.select_value() {
                    Some(b) => base = b,
                    None => break,
                }
            }
            match base
                .referenced_symbol()
                .filter(|_| base.kind() == ExpressionKind::NamedValue)
            {
                Some(sym) => {
                    let window = own.get(&sym.uid()).and_then(|slot| match slot.class {
                        SignalSlotClass::Memory {
                            num_rows,
                            lower_index,
                        } => memory_window(e, slot.width, num_rows, lower_index),
                        _ => vj_codegen::select::constant_window(e, slot.width).ok(),
                    });
                    vec![(sym, window)]
                }
                None => lvalue_roots(e).into_iter().map(|r| (r, None)).collect(),
            }
        }
        _ => lvalue_roots(e).into_iter().map(|r| (r, None)).collect(),
    }
}

/// `body`'s `trireg` nets. They start with an unknown charge (LRM 6.6.4.1),
/// not the Z every other undriven net starts at (`state::layout`).
pub(crate) fn trireg_nets(body: &Symbol<'_>, trees: &[SyntaxTree]) -> Vec<SymbolId> {
    vj_sim::netlist::module_items(body)
        .into_iter()
        .filter(|m| m.kind() == SymbolKind::Net && net_kind_of(m, trees) == NetKind::TriReg)
        .map(|m| m.uid())
        .collect()
}

/// A `trireg` net's charge strength as a `%v` code (LRM 28.16.1): 5 `small`,
/// 4 `medium` (the default), 6 `large`.
pub(crate) fn charge_code_of(net: &Symbol<'_>, trees: &[SyntaxTree]) -> u8 {
    use sv_lang::AstNode;
    use sv_lang::kinds::{SyntaxKind, TokenKind};
    use sv_lang::nodes::{NetDeclarationSyntax, NetStrengthSyntax};
    for tree in trees {
        let Some(mut node) = net.syntax(tree) else {
            continue;
        };
        loop {
            if node.kind() == SyntaxKind::NetDeclaration
                && let Some(n) = NetDeclarationSyntax::cast(node)
            {
                return match n.strength() {
                    Some(NetStrengthSyntax::ChargeStrength(c)) => {
                        match c.strength().map(|t| t.kind()) {
                            Some(TokenKind::SmallKeyword) => 5,
                            Some(TokenKind::LargeKeyword) => 6,
                            _ => 4,
                        }
                    }
                    _ => 4,
                };
            }
            match node.parent() {
                Some(p) => node = p,
                None => break,
            }
        }
        break;
    }
    4
}

/// The `scalared` / `vectored` keyword of `net`'s declaration (LRM 6.9.1,
/// `vpiExplicitScalared` / `vpiExplicitVectored` of 37.16): `Some(true)` for
/// `scalared`, `Some(false)` for `vectored`, `None` when the declaration
/// carries neither.
pub(crate) fn expansion_hint_of(net: &Symbol<'_>, trees: &[SyntaxTree]) -> Option<bool> {
    use sv_lang::AstNode;
    use sv_lang::kinds::{SyntaxKind, TokenKind};
    use sv_lang::nodes::NetDeclarationSyntax;
    for tree in trees {
        let Some(mut node) = net.syntax(tree) else {
            continue;
        };
        loop {
            if node.kind() == SyntaxKind::NetDeclaration
                && let Some(n) = NetDeclarationSyntax::cast(node)
            {
                return match n.expansion_hint().map(|t| t.kind()) {
                    Some(TokenKind::ScalaredKeyword) => Some(true),
                    Some(TokenKind::VectoredKeyword) => Some(false),
                    _ => None,
                };
            }
            match node.parent() {
                Some(p) => node = p,
                None => break,
            }
        }
        break;
    }
    None
}

/// `net`'s net type, from its declaration's keyword (`wire` when none).
pub(crate) fn net_kind_of(net: &Symbol<'_>, trees: &[SyntaxTree]) -> NetKind {
    use sv_lang::AstNode;
    use sv_lang::kinds::{SyntaxKind, TokenKind};
    use sv_lang::nodes::{
        ImplicitAnsiPortSyntax, NetDeclarationSyntax, PortDeclarationSyntax, PortHeaderSyntax,
    };
    let of_token = |tok: sv_lang::kinds::TokenKind| match tok {
        TokenKind::TriKeyword => NetKind::Tri,
        TokenKind::Tri0Keyword => NetKind::Tri0,
        TokenKind::Tri1Keyword => NetKind::Tri1,
        TokenKind::WAndKeyword => NetKind::WAnd,
        TokenKind::TriAndKeyword => NetKind::TriAnd,
        TokenKind::WOrKeyword => NetKind::WOr,
        TokenKind::TriOrKeyword => NetKind::TriOr,
        TokenKind::TriRegKeyword => NetKind::TriReg,
        TokenKind::Supply0Keyword => NetKind::Supply0,
        TokenKind::Supply1Keyword => NetKind::Supply1,
        TokenKind::UWireKeyword => NetKind::UWire,
        _ => NetKind::Wire,
    };
    // An implicit net has no declaration keyword: it takes the scope's
    // `default_nettype (LRM 6.10, 22.8).
    if net.net_is_implicit()
        && let Some(k) = std::iter::successors(net.parent(), |s| s.parent())
            .find_map(|s| s.default_net_type())
            .map(|t| t.net_kind())
    {
        use sv_lang::NetKind as K;
        match k {
            K::WAnd => return NetKind::WAnd,
            K::WOr => return NetKind::WOr,
            K::Tri => return NetKind::Tri,
            K::TriAnd => return NetKind::TriAnd,
            K::TriOr => return NetKind::TriOr,
            K::Tri0 => return NetKind::Tri0,
            K::Tri1 => return NetKind::Tri1,
            K::TriReg => return NetKind::TriReg,
            K::Supply0 => return NetKind::Supply0,
            K::Supply1 => return NetKind::Supply1,
            K::UWire => return NetKind::UWire,
            _ => {}
        }
    }
    // A port's net type is the keyword of its header (`inout wand w`).
    let header_kind = |h: PortHeaderSyntax<'_>| match h {
        PortHeaderSyntax::NetPortHeader(h) => h.net_type().map(|t| of_token(t.kind())),
        _ => None,
    };
    for tree in trees {
        let Some(mut node) = net.syntax(tree) else {
            continue;
        };
        loop {
            if node.kind() == SyntaxKind::NetDeclaration
                && let Some(n) = NetDeclarationSyntax::cast(node)
                && let Some(tok) = n.net_type()
            {
                return of_token(tok.kind());
            }
            let port_kind = if let Some(p) = ImplicitAnsiPortSyntax::cast(node) {
                header_kind(p.header())
            } else if let Some(p) = PortDeclarationSyntax::cast(node) {
                header_kind(p.header())
            } else {
                None
            };
            if let Some(k) = port_kind {
                return k;
            }
            match node.parent() {
                Some(p) => node = p,
                None => break,
            }
        }
        break;
    }
    NetKind::Wire
}

/// The net type of the simulated net a port connection between an internal
/// net of kind `internal` and an external net of kind `external` collapses to
/// (LRM 1800-2023 23.3.3.7, Table 23-1): the dominating net's, else the
/// external net's. Kinds the table does not list (a user-defined nettype)
/// keep the external one.
fn dominating_kind(internal: NetKind, external: NetKind) -> NetKind {
    // The table's row/column order.
    let index = |k: NetKind| match k {
        NetKind::Wire | NetKind::Tri => Some(0),
        NetKind::WAnd | NetKind::TriAnd => Some(1),
        NetKind::WOr | NetKind::TriOr => Some(2),
        NetKind::TriReg => Some(3),
        NetKind::Tri0 => Some(4),
        NetKind::Tri1 => Some(5),
        NetKind::UWire => Some(6),
        NetKind::Supply0 => Some(7),
        NetKind::Supply1 => Some(8),
        _ => None,
    };
    let (Some(i), Some(e)) = (index(internal), index(external)) else {
        return external;
    };
    // The columns of each internal row whose cell says `internal`.
    let internal_wins = match i {
        1..=3 if e == 0 => true,
        4 | 5 => e == 0 || e == 3,
        6 => e <= 5,
        7 | 8 => e <= 6,
        _ => false,
    };
    if internal_wins { internal } else { external }
}

/// Whether a net of `kind` resolves even with a single driver.
fn resolves_alone(kind: NetKind) -> bool {
    matches!(
        kind,
        NetKind::Tri0
            | NetKind::Tri1
            | NetKind::WAnd
            | NetKind::TriAnd
            | NetKind::WOr
            | NetKind::TriOr
            | NetKind::Supply0
            | NetKind::Supply1
            // A `trireg` stores charge when its drivers turn off.
            | NetKind::TriReg
    )
}

/// The variables/nets an assignment target writes (`w`, `w[3:0]`, `{a, b}`).
pub(crate) fn lvalue_roots<'d>(e: Expression<'d>) -> Vec<Symbol<'d>> {
    let kind = e.kind();
    if vj_sim::symid::is_value_name(kind) {
        e.referenced_symbol().into_iter().collect()
    } else if matches!(
        kind,
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect
    ) {
        e.select_value().map(lvalue_roots).unwrap_or_default()
    } else if kind == ExpressionKind::MemberAccess {
        e.operand().map(lvalue_roots).unwrap_or_default()
    } else if kind == ExpressionKind::Concatenation {
        e.operands().into_iter().flat_map(lvalue_roots).collect()
    } else if kind == ExpressionKind::Conversion {
        e.operand().map(lvalue_roots).unwrap_or_default()
    } else {
        Vec::new()
    }
}

/// The element path an assignment target addresses within its unpacked-array
/// net: the constant indices of the element selects of UNPACKED dimensions
/// (`w[1][0]` -> `[1, 0]`; a select of a packed dimension or a part-select is
/// a slice of an element, not another element). The path stops at the first
/// select that is not a constant (so it then covers every element below its
/// prefix); a target that is a concatenation gives `None` -- its parts are
/// not tracked.
fn element_path(e: Expression<'_>) -> Option<ElemPath> {
    let constant = |x: Option<Expression<'_>>| {
        x.and_then(|s| s.constant_value())
            .as_ref()
            .and_then(sv_lang::ConstantValue::as_integer)
            .and_then(sv_lang::SVInt::as_i64)
    };
    let mut idx: Vec<Option<i64>> = Vec::new();
    // The packed bits selected out of the element, as an inclusive interval
    // of the select's own index space: the innermost packed select (the one
    // applied to the element) bounds every select applied over it.
    let mut bits: Option<(i64, i64)> = None;
    let mut cur = e;
    loop {
        let kind = cur.kind();
        if kind == ExpressionKind::ElementSelect {
            let base = cur.select_value()?;
            if base.expr_type().is_some_and(|t| t.is_unpacked_array()) {
                idx.push(constant(cur.selector()));
            } else {
                // A packed-dimension select: everything gathered so far was
                // selected out of this element, so it is not an element index.
                idx.clear();
                bits = constant(cur.selector()).map(|c| (c, c));
            }
            cur = base;
        } else if kind == ExpressionKind::RangeSelect {
            let base = cur.select_value()?;
            idx.clear();
            bits = if base.expr_type().is_some_and(|t| t.is_unpacked_array()) {
                None
            } else {
                range_bits(cur, constant(cur.range_left()), constant(cur.range_right()))
            };
            cur = base;
        } else if kind == ExpressionKind::MemberAccess {
            // Bits of a member are not bits of the element's own range.
            bits = None;
            cur = cur.operand()?;
        } else if kind == ExpressionKind::Conversion {
            cur = cur.operand()?;
        } else if vj_sim::symid::is_value_name(kind) {
            break;
        } else {
            return None;
        }
    }
    idx.reverse();
    let full = idx.iter().all(Option::is_some);
    Some(ElemPath {
        idx: idx.into_iter().map_while(|i| i).collect(),
        bits: bits.filter(|_| full),
    })
}

/// A constant part-select's inclusive bit interval (`None` when a bound is
/// not constant).
fn range_bits(e: Expression<'_>, left: Option<i64>, right: Option<i64>) -> Option<(i64, i64)> {
    let (left, right) = (left?, right?);
    use vj_codegen::expr::RangeSelectionKindClass as K;
    let kind = vj_codegen::expr::classify_range_selection_kind(e.range_selection_kind()?).ok()?;
    if kind == K::Simple {
        Some((left.min(right), left.max(right)))
    } else if right <= 0 {
        None
    } else if kind == K::IndexedUp {
        Some((left, left + right - 1))
    } else {
        Some((left - right + 1, left))
    }
}

/// Where a continuous assign drives an unpacked-array net: the element
/// (a prefix of constant indices: a shorter path covers a whole sub-array)
/// and, for a constant part- or bit-select of one element, its bits.
#[derive(Clone, Debug)]
struct ElemPath {
    idx: Vec<i64>,
    bits: Option<(i64, i64)>,
}

/// Whether two element paths overlap: one is a prefix of the other, unless
/// both select disjoint bits of the same element.
fn paths_overlap(a: &ElemPath, b: &ElemPath) -> bool {
    let n = a.idx.len().min(b.idx.len());
    if a.idx[..n] != b.idx[..n] {
        return false;
    }
    match (a.bits, b.bits) {
        (Some((alo, ahi)), Some((blo, bhi))) if a.idx.len() == b.idx.len() => {
            alo <= bhi && blo <= ahi
        }
        _ => true,
    }
}

/// A union-find over keys (nets, or the elements of interconnect nets).
struct Find<K = NetId>(HashMap<K, K>);

impl<K: Clone + Eq + std::hash::Hash> Find<K> {
    fn root(&mut self, n: &K) -> K {
        let mut cur = n.clone();
        while let Some(p) = self.0.get(&cur).cloned() {
            if p == cur {
                break;
            }
            cur = p;
        }
        cur
    }
    fn union(&mut self, a: &K, b: &K) {
        let (ra, rb) = (self.root(a), self.root(b));
        if ra != rb {
            self.0.insert(ra, rb);
        }
    }
}

/// One thing a port connection merges (LRM 1800-2023 23.3.3.7.1): an element
/// of an `interconnect` net (its unpacked-array index path; empty for a scalar
/// one), or a net that has a type.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Joint {
    Interconnect(InstanceId, SymbolId, Vec<i64>),
    Typed(NetId),
    /// One row (storage order) of a one-dimensional unpacked-array net.
    Row(NetId, u32),
}

/// Whether `slot` is an unpacked-array memory.
fn is_memory(slot: &SignalSlot) -> bool {
    matches!(slot.class, SignalSlotClass::Memory { .. })
}

/// The index paths of the elements of an interconnect array of unpacked
/// dimensions `dims` (declared `(left, right)` bounds) that start with
/// `prefix`, in declaration order (the order elements pair up in across a port
/// connection, 7.6).
fn interconnect_elements(dims: &[(i32, i32)], prefix: &[i64]) -> Vec<Vec<i64>> {
    let mut out: Vec<Vec<i64>> = vec![Vec::new()];
    for (d, &(l, r)) in dims.iter().enumerate() {
        let idxs: Vec<i64> = match prefix.get(d) {
            Some(&p) => vec![p],
            None if l <= r => (i64::from(l)..=i64::from(r)).collect(),
            None => (i64::from(r)..=i64::from(l)).rev().collect(),
        };
        out = out
            .into_iter()
            .flat_map(|t| {
                idxs.iter().map(move |i| {
                    let mut t = t.clone();
                    t.push(*i);
                    t
                })
            })
            .collect();
    }
    out
}

/// The unpacked dimensions of `s` when it is an `interconnect` net.
fn interconnect_dims_of(s: &Symbol<'_>) -> Option<Vec<(i32, i32)>> {
    if s.kind() != SymbolKind::Net {
        return None;
    }
    vj_sim::state::storage::interconnect_dims(&s.value_type()?)
}

/// A primitive terminal that is an element of an interconnect array (`ic[1]`,
/// `ic[0][2]`): the array's symbol and the element, `(instance, array,
/// index tuple)`. Such an element is a scalar wire (LRM 23.3.3.7.2). `Err`
/// when the terminal selects only part of the array's dimensions.
pub(crate) fn ic_element<'d>(
    e: Expression<'d>,
    inst: InstanceId,
) -> Result<Option<(Symbol<'d>, IcElem)>, String> {
    let e = connection_target(e);
    if e.kind() != ExpressionKind::ElementSelect {
        return Ok(None);
    }
    let roots = lvalue_roots(e);
    let [root] = roots[..] else {
        return Ok(None);
    };
    let Some(dims) = interconnect_dims_of(&root) else {
        return Ok(None);
    };
    match element_path(e) {
        Some(p) if p.idx.len() == dims.len() && p.bits.is_none() => {
            Ok(Some((root, (inst, root.uid(), p.idx))))
        }
        _ => Err(format!(
            "{}: a primitive terminal must select one element (every unpacked dimension, with constant indices) of an interconnect array (LRM 23.3.3.7.2: it is treated as a scalar wire)",
            root.hierarchical_path()
        )),
    }
}

/// Whether the port connection `expr` to `port` has an interconnect net on
/// either side: such a connection merges nets (`analyze`) and is never
/// wired or compiled as an assignment.
pub(crate) fn connects_interconnect<'d>(port: &Symbol<'d>, expr: Expression<'d>) -> bool {
    let member = port.port_internal_symbol().unwrap_or(*port);
    interconnect_dims_of(&member).is_some()
        || lvalue_roots(connection_target(expr))
            .iter()
            .any(|r| interconnect_dims_of(r).is_some())
}

/// A connection expression stripped of the assignment/conversion wrappers a
/// port connection carries.
pub(crate) fn connection_target<'d>(e: Expression<'d>) -> Expression<'d> {
    let e = if e.kind() == ExpressionKind::Assignment {
        e.left().unwrap_or(e)
    } else {
        e
    };
    if e.kind() == ExpressionKind::Conversion {
        e.operand().unwrap_or(e)
    } else {
        e
    }
}

/// The rows of an unpacked-array net: `(storage row, index tuple)` in
/// declaration order, per net (`None`: the layout cannot be enumerated).
type RowsOf = HashMap<NetId, Option<Vec<(u32, Vec<i64>)>>>;

/// The rows of the unpacked-array net `s` (a memory of `num_rows` rows, every
/// unpacked dimension flattened row-major, lowest index first) in declaration
/// order, each with the index it has in every dimension. A dimension declared
/// `[l:r]` with `l > r` counts down, so its declaration-order position `p` is
/// storage position `n - 1 - p`.
fn net_rows(s: &Symbol<'_>, num_rows: u32) -> Option<Vec<(u32, Vec<i64>)>> {
    let mut ty = s.value_type()?;
    let mut dims: Vec<(i64, i64)> = Vec::new();
    while ty.is_unpacked_array() {
        let r = ty.fixed_unpacked_array_range();
        dims.push((i64::from(r.left), i64::from(r.right)));
        ty = ty.element_type()?;
    }
    let lens: Vec<i64> = dims.iter().map(|(l, r)| (l - r).abs() + 1).collect();
    if lens.iter().product::<i64>() != i64::from(num_rows) {
        return None;
    }
    let mut out: Vec<(i64, Vec<i64>)> = vec![(0, Vec::new())];
    for (&(l, r), &n) in dims.iter().zip(&lens) {
        let mut next = Vec::new();
        for (row, idx) in &out {
            for p in 0..n {
                let (value, pos) = if l <= r {
                    (l + p, p)
                } else {
                    (l - p, n - 1 - p)
                };
                let mut idx = idx.clone();
                idx.push(value);
                next.push((row * n + pos, idx));
            }
        }
        out = next;
    }
    Some(
        out.into_iter()
            .map(|(row, idx)| (row as u32, idx))
            .collect(),
    )
}

/// The elements a whole net takes part in a connection as: itself, or each of
/// its rows (declaration order, 7.6) when it is an unpacked array.
fn elements_of(net: &NetId, rows_of: &RowsOf) -> Result<Vec<Joint>, String> {
    match rows_of.get(net) {
        None => Ok(vec![Joint::Typed(net.clone())]),
        Some(Some(rows)) => Ok(rows
            .iter()
            .map(|(r, _)| Joint::Row(net.clone(), *r))
            .collect()),
        Some(None) => Err(format!(
            "{}: an unpacked-array net of this shape joined to another net is not supported",
            net.1.path()
        )),
    }
}

/// Joins two whole nets into one simulated net, element by element (an
/// unpacked-array net is one net per element, LRM 6.6.7, 23.3.3.7).
fn union_nets(
    find: &mut Find<Joint>,
    a: &NetId,
    b: &NetId,
    rows_of: &RowsOf,
) -> Result<(), String> {
    let (ea, eb) = (elements_of(a, rows_of)?, elements_of(b, rows_of)?);
    if ea.len() != eb.len() {
        return Err(format!(
            "{}: a connection of unpacked-array nets of {} and {} elements",
            a.1.path(),
            ea.len(),
            eb.len()
        ));
    }
    for (x, y) in ea.iter().zip(&eb) {
        find.union(x, y);
    }
    Ok(())
}

/// Whether a driver addressing `path` of an unpacked-array net drives the
/// element with index tuple `idx` (a path is a prefix of constant indices; a
/// shorter one covers a whole sub-array).
fn covers(path: &Option<ElemPath>, idx: &[i64]) -> bool {
    path.as_ref()
        .is_none_or(|p| p.idx.len() <= idx.len() && p.idx[..] == idx[..p.idx.len()])
}

/// One class of elements that are ONE simulated net.
struct Class {
    root: Joint,
    nets: Vec<NetId>,
    rows: Vec<(NetId, u32)>,
    /// The interconnect array elements primitive terminals make wires.
    cells: Vec<IcElem>,
    /// The nets the members belong to, in order.
    owners: Vec<NetId>,
    /// Each driver, its row of an unpacked-array owner's contribution memory,
    /// and the owner.
    ds: Vec<(Driver, Option<u32>, NetId)>,
    kind: NetKind,
    user: Option<usize>,
    switched: bool,
    width: u32,
}

/// Set when a VPI library is loaded: `vpi_get_value` with `vpiStrengthVal`
/// (LRM 38.15) reads the same per-net strengths `%v` does, so every resolved
/// net keeps them, and a net driven below the default strength is resolved
/// even alone (a net with one default-strength driver is strong by
/// construction). No other design pays for it.
static TRACK_STRENGTHS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Makes resolved nets keep their strengths for `vpiStrengthVal`.
pub(crate) fn track_strengths() {
    TRACK_STRENGTHS.store(true, std::sync::atomic::Ordering::Relaxed);
}

/// Whether nets keep their strengths for a VPI library ([`track_strengths`]).
pub(crate) fn tracks_strengths() -> bool {
    TRACK_STRENGTHS.load(std::sync::atomic::Ordering::Relaxed)
}

/// Whether nets keep their strengths: a string literal of `trees` holds a
/// `%v` specifier (LRM 21.2.1.5), or the design uses a MOS switch, whose
/// output carries its data input's strength into resolution (LRM 28.4,
/// Table 28-8). No other design pays for it (`vj_exec::nets`).
pub(crate) fn shows_strength(trees: &[SyntaxTree]) -> bool {
    let has_v = |s: &str| {
        let b = s.as_bytes();
        let mut i = 0;
        while i < b.len() {
            if b[i] == b'%' {
                let mut j = i + 1;
                while j < b.len() && matches!(b[j], b'-' | b'#' | b'.' | b'0'..=b'9') {
                    j += 1;
                }
                if j < b.len() && matches!(b[j], b'v' | b'V') {
                    return true;
                }
                i = j.max(i + 1);
            } else {
                i += 1;
            }
        }
        false
    };
    let mut found = false;
    for tree in trees {
        tree.root().visit_with_tokens(|c| {
            if let sv_lang::Child::Token(t) = c
                && ((t.kind() == sv_lang::kinds::TokenKind::StringLiteral && has_v(t.text()))
                    || matches!(
                        t.text(),
                        "nmos" | "pmos" | "cmos" | "rnmos" | "rpmos" | "rcmos"
                            // `$countdrivers` (LRM D.2) reads what resolution records.
                            | "$countdrivers"
                            // `$dumpports` writes each port bit's strength
                            // and conflict state (LRM 21.7.4.3).
                            | "$dumpports"
                    ))
            {
                found = true;
                return sv_lang::Walk::Break;
            }
            sv_lang::Walk::Continue
        });
        if found {
            return true;
        }
    }
    false
}

/// Whether the design calls `$dumpports`, whose port states need the test
/// fixture's and the DUT's drivers resolved apart (LRM 21.7.4.3.2).
pub(crate) fn uses_dumpports(trees: &[SyntaxTree]) -> bool {
    let mut found = false;
    for tree in trees {
        tree.root().visit_with_tokens(|c| {
            if let sv_lang::Child::Token(t) = c
                && t.text() == "$dumpports"
            {
                found = true;
                return sv_lang::Walk::Break;
            }
            sv_lang::Walk::Continue
        });
        if found {
            return true;
        }
    }
    false
}

/// Whether the design calls `$sdf_annotate`. SDF names a net's sources by
/// their output ports (LRM 32.4.4), and a collapsed output port is no
/// longer a source of its own, so such a design refuses an output port that
/// would need collapsing (a child reading its own output net must see the
/// parent's other drivers) rather than silently keeping one-way semantics.
fn uses_sdf(trees: &[SyntaxTree]) -> bool {
    let mut found = false;
    for tree in trees {
        tree.root().visit_with_tokens(|c| {
            if let sv_lang::Child::Token(t) = c
                && t.text() == "$sdf_annotate"
            {
                found = true;
                return sv_lang::Walk::Break;
            }
            sv_lang::Walk::Continue
        });
        if found {
            return true;
        }
    }
    false
}

/// Whether instance `id` itself reads the net `net` (not only drives it):
/// in a continuous assign's right side, a net initializer, a procedural
/// block, a child instance's input or inout connection, or a primitive's
/// non-first terminal (a gate's first terminals are its outputs; reading a
/// multi-output gate's later output counts as a read, conservatively).
fn instance_reads_net<'d>(
    instances: &[(InstanceId, Symbol<'d>, Symbol<'d>, Option<InstanceId>)],
    id: InstanceId,
    net: SymbolId,
) -> bool {
    let mentions = |roots: Vec<sv_lang::SemNode<'d>>| {
        crate::run::referenced_values(roots)
            .iter()
            .any(|s| s.uid() == net)
    };
    for (i, body, _, _) in instances {
        if *i != id {
            continue;
        }
        let mut roots = Vec::new();
        for m in vj_sim::netlist::module_items(body) {
            match m.kind() {
                SymbolKind::ProceduralBlock => {
                    roots.extend(vj_sim::process::cfg::proc_body(&m).map(|b| b.as_sem_node()))
                }
                SymbolKind::ContinuousAssign => roots.extend(
                    m.continuous_assign_assignment()
                        .and_then(|a| a.right())
                        .map(|e| e.as_sem_node()),
                ),
                SymbolKind::Net | SymbolKind::Variable => {
                    roots.extend(m.initializer().map(|e| e.as_sem_node()));
                }
                _ => {}
            }
        }
        for prim in crate::primitives::instances(body) {
            roots.extend(
                prim.primitive_instance_port_connections()
                    .skip(1)
                    .map(|e| e.as_sem_node()),
            );
        }
        if mentions(roots) {
            return true;
        }
    }
    let mut roots = Vec::new();
    for (_, _, inst, parent) in instances {
        if *parent != Some(id) {
            continue;
        }
        for conn in inst.instance_port_connections() {
            if conn.port().port_direction() != ArgumentDirection::Out
                && let Some(e) = conn.expression()
            {
                roots.push(e.as_sem_node());
            }
        }
    }
    mentions(roots)
}

/// Finds every resolved net group of the design. `instances` lists each
/// elaborated instance with its body symbol, instance symbol and parent;
/// `signals` is each instance's own signal map.
pub(crate) fn analyze<'d>(
    instances: &[(InstanceId, Symbol<'d>, Symbol<'d>, Option<InstanceId>)],
    signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    trees: &[SyntaxTree],
    user: &crate::usernets::UserNets<'d>,
    specify_dests: &HashSet<NetId>,
) -> Result<Resolution, String> {
    let shows_strength = shows_strength(trees);
    // A module-path destination driven bit by bit by primitives (`buf b[1:0] (a, x)`) is not
    // resolved: no two drivers share a bit, and `specify::plan` retimes each bit from the
    // gates' shared staging cell instead (LRM 30.4). Windows are computed only for such nets.
    let windows = if specify_dests.is_empty() {
        DrivenWindows::new()
    } else {
        driven_windows(instances, signals, trees)
    };
    let mut drivers: HashMap<NetId, Vec<Driver>> = HashMap::new();
    // Output-port drivers `(parent net, driver key, child port net)`: the
    // port driver inherits the child net's drive strength (LRM 23.3.3.2).
    let mut out_inherit: Vec<(NetId, DriverKey, NetId)> = Vec::new();
    let mut kinds: HashMap<NetId, NetKind> = HashMap::new();
    // The net symbols (for an unpacked-array net's dimensions).
    let mut net_syms: HashMap<NetId, Symbol<'d>> = HashMap::new();
    let mut find = Find::<Joint>(HashMap::new());
    // The drivers of the interconnect array elements primitive terminals
    // make scalar wires (LRM 23.3.3.7.2).
    let mut cell_drivers: HashMap<IcElem, Vec<Driver>> = HashMap::new();
    let mut out = Resolution::default();
    let is_net = |s: &Symbol<'_>| s.kind() == SymbolKind::Net;

    for (id, body, _, _) in instances {
        let own = &signals[id];
        for m in vj_sim::netlist::module_items(body) {
            let kind = m.kind();
            if kind == SymbolKind::Net && own.contains_key(&m.uid()) {
                let net = (*id, m.uid());
                kinds.insert(
                    net.clone(),
                    if user.by_net.contains_key(&net) {
                        NetKind::UserDefined
                    } else {
                        net_kind_of(&m, trees)
                    },
                );
                net_syms.insert(net.clone(), m);
                if m.initializer().is_some() {
                    drivers.entry(net).or_default().push(Driver {
                        key: DriverKey::Assign(*id, m.uid(), m.uid()),
                        strength: strength_of(m.net_drive_strength()),
                        path: None,
                    });
                }
            } else if kind == SymbolKind::ContinuousAssign
                && let Some(lhs) = m.continuous_assign_assignment().and_then(|a| a.left())
            {
                for root in lvalue_roots(lhs) {
                    if is_net(&root) && own.contains_key(&root.uid()) {
                        drivers.entry((*id, root.uid())).or_default().push(Driver {
                            key: DriverKey::Assign(*id, m.uid(), root.uid()),
                            strength: strength_of(m.continuous_assign_drive_strength()),
                            path: element_path(lhs),
                        });
                    }
                }
            }
        }
        // A checker's output formal drives its actual like a continuous
        // assignment (LRM 17.3), keyed by the formal.
        for checker in vj_sim::netlist::checker_instances(body) {
            for out in vj_sim::netlist::checker_outputs(&checker) {
                let Some(lhs) = out.assign.and_then(|a| a.left()) else {
                    continue;
                };
                for root in lvalue_roots(lhs) {
                    if is_net(&root) && own.contains_key(&root.uid()) {
                        drivers.entry((*id, root.uid())).or_default().push(Driver {
                            key: DriverKey::Assign(*id, out.formal.uid(), root.uid()),
                            strength: strong(),
                            path: element_path(lhs),
                        });
                    }
                }
            }
        }
        // A clocking block's output clock variable (`output io`, LRM 14.16)
        // drives its net like a continuous assignment: the synchronous drive
        // is a procedural write, redirected (`DriverKey::ProcVar`) to a
        // contribution cell of the resolved group, so it resolves against
        // the net's other drivers and reaches the nets an `inout` port joins
        // it to instead of being overwritten by the next resolution.
        for cb in vj_sim::netlist::module_items(body) {
            if cb.kind() != SymbolKind::ClockingBlock {
                continue;
            }
            for cv in cb.members() {
                if cv.kind() != SymbolKind::ClockVar
                    || cv.clock_var_direction() == ArgumentDirection::In
                {
                    continue;
                }
                let Some(target) = cv.initializer() else {
                    continue;
                };
                for root in lvalue_roots(target) {
                    if !is_net(&root) || !own.contains_key(&root.uid()) {
                        continue;
                    }
                    let key = DriverKey::ProcVar(*id, root.uid());
                    let list = drivers.entry((*id, root.uid())).or_default();
                    if list.iter().all(|d| d.key != key) {
                        list.push(Driver {
                            key,
                            strength: strong(),
                            path: element_path(target),
                        });
                    }
                }
            }
        }
        // An unsupported primitive is reported when it is planned
        // (`crate::primitives::plan`); a switch joins nets instead (below).
        for inst in crate::primitives::instances(body) {
            if crate::primitives::is_switch(&inst, trees) {
                continue;
            }
            let Ok(sh) = crate::primitives::shape(&inst, trees) else {
                continue;
            };
            let strength = crate::primitives::strength(&inst, sh.gate, sh.resistive);
            for out in sh.outputs {
                if let Some((root, elem)) = ic_element(out, *id)? {
                    let key = DriverKey::PrimElem(*id, inst.uid(), root.uid(), elem.2.clone());
                    cell_drivers.entry(elem).or_default().push(Driver {
                        key,
                        strength,
                        path: None,
                    });
                    continue;
                }
                for root in lvalue_roots(out) {
                    if is_net(&root) && own.contains_key(&root.uid()) {
                        drivers.entry((*id, root.uid())).or_default().push(Driver {
                            key: DriverKey::Prim(*id, inst.uid(), root.uid()),
                            strength,
                            path: None,
                        });
                    }
                }
            }
        }
    }
    // The nets in a fixed order, and each unpacked-array net's rows.
    let order = |a: &NetId, b: &NetId| (a.0.0, &a.1).cmp(&(b.0.0, &b.1));
    let mut all: Vec<NetId> = kinds.keys().cloned().collect();
    all.sort_by(order);
    let mut rows_of: RowsOf = HashMap::new();
    for n in &all {
        if let SignalSlotClass::Memory { num_rows, .. } = signals[&n.0][&n.1].class {
            rows_of.insert(n.clone(), net_rows(&net_syms[n], num_rows));
        }
    }
    // The index tuple of each row.
    let row_idx: HashMap<(NetId, u32), &Vec<i64>> = rows_of
        .iter()
        .filter_map(|(n, rows)| rows.as_ref().map(|r| (n, r)))
        .flat_map(|(n, rows)| rows.iter().map(move |(r, idx)| ((n.clone(), *r), idx)))
        .collect();

    // A scalar `interconnect` net on a primitive terminal is treated as a
    // scalar wire (LRM 23.3.3.7.2): its 1-bit placeholder is such a net.
    let mut ic_wires: HashSet<NetId> = HashSet::new();
    // An element of an interconnect ARRAY on a terminal is one too: a
    // 1-bit cell of its own.
    let mut ic_cells: Vec<IcElem> = Vec::new();
    for (id, body, _, _) in instances {
        for inst in crate::primitives::instances(body) {
            for e in inst.primitive_instance_port_connections() {
                if let Some((_, elem)) = ic_element(e, *id)? {
                    if !ic_cells.contains(&elem) {
                        ic_cells.push(elem);
                    }
                    continue;
                }
                for root in lvalue_roots(e) {
                    let Some(dims) = interconnect_dims_of(&root) else {
                        continue;
                    };
                    if !dims.is_empty() {
                        return Err(format!(
                            "{}: a primitive terminal connected to an interconnect array as a whole (LRM 23.3.3.7.2: a terminal is a scalar wire)",
                            inst.hierarchical_path()
                        ));
                    }
                    ic_wires.insert((*id, root.uid()));
                }
            }
        }
    }
    ic_cells.sort_by(|a, b| (a.0.0, &a.1, &a.2).cmp(&(b.0.0, &b.1, &b.2)));
    // Interconnect connections (LRM 23.3.3.7.1): every port connection with
    // an interconnect net on either side merges the two sides, element by
    // element, whatever the port's direction. The classes of merged things
    // are resolved once every port is seen (below).
    let mut joints = Find::<Joint>(HashMap::new());
    let mut joint_list: Vec<Joint> = Vec::new();
    let mut joint_seen: HashSet<Joint> = HashSet::new();
    // Each merge of an internal net (first) and an external net (second), in
    // order: replayed to pick the simulated net's type (Table 23-1).
    let mut merges: Vec<(NetId, NetId)> = Vec::new();
    let mut ic_ports: Vec<(InstanceId, SymbolId)> = Vec::new();
    // Always-on bit switches an `inout` port connected to a bit-/part-select
    // of a parent net makes (LRM 23.3.3.7: the port net and the selected bits
    // are one simulated net; modeled as a non-resistive `tran` per bit).
    let mut select_port_switches: Vec<PendingSwitch> = Vec::new();
    // Output ports whose child net and parent net are both whole nets of one
    // width: collapsed into one simulated net (LRM 23.3.3.7) once it is known
    // whether the parent side has drivers of its own (`out_cands`, below).
    let mut out_cands: Vec<OutCand> = Vec::new();
    // Port connections: a child's input port drives its port net; an output
    // port drives the parent's nets; an inout port joins the two nets.
    for (id, _, inst, parent) in instances {
        let Some(parent) = parent else {
            continue;
        };
        for conn in inst.instance_port_connections() {
            let port = conn.port();
            if port.kind() == SymbolKind::InterfacePort {
                continue;
            }
            let Some(expr) = conn.expression() else {
                // LRM 22.5.2: an unconnected input port net of a module under
                // `unconnected_drive pull0/pull1` is pulled, not left at `z`.
                let pull_one = match inst
                    .instance_definition()
                    .and_then(|d| d.definition_unconnected_drive())
                {
                    Some(sv_lang::UnconnectedDrive::Pull0) => Some(false),
                    Some(sv_lang::UnconnectedDrive::Pull1) => Some(true),
                    _ => None,
                };
                let member = port.port_internal_symbol().unwrap_or(port);
                if let Some(one) = pull_one
                    && port.port_direction() == ArgumentDirection::In
                    && is_net(&member)
                    && let Some(slot) = signals[id].get(&member.uid())
                {
                    if is_memory(slot) {
                        return Err(format!(
                            "{}: `unconnected_drive on an unconnected unpacked-array input port `{}` is not supported",
                            inst.hierarchical_path(),
                            port.name()
                        ));
                    }
                    drivers
                        .entry((*id, member.uid()))
                        .or_default()
                        .push(Driver {
                            key: DriverKey::Prim(*id, port.uid(), member.uid()),
                            strength: DriveStrengthPair {
                                s0: DriveStrength::Pull,
                                s1: DriveStrength::Pull,
                            },
                            path: None,
                        });
                    out.open_pulls.push((*id, port.uid(), member.uid(), one));
                }
                continue;
            };
            let member = port.port_internal_symbol().unwrap_or(port);
            let target = connection_target(expr);
            let roots = lvalue_roots(target);
            let member_ic = interconnect_dims_of(&member);
            let expr_ic = roots
                .iter()
                .find_map(|r| interconnect_dims_of(r).map(|d| (*r, d)));
            if member_ic.is_some() || expr_ic.is_some() {
                let what = || format!("{}: port `{}`", inst.hierarchical_path(), port.name());
                // What a side of the connection is, element by element.
                let typed = |side: InstanceId, s: &Symbol<'d>| -> Result<Vec<Joint>, String> {
                    if is_net(s) && signals[&side].contains_key(&s.uid()) {
                        elements_of(&(side, s.uid()), &rows_of)
                    } else {
                        Err(format!(
                            "{}: an interconnect port is connected to something other than a whole net or an interconnect net: a variable, including a ref port's, may not be connected to an interconnect net or port (LRM 23.3.3.2, 6.6.8)",
                            what()
                        ))
                    }
                };
                let member_side = match &member_ic {
                    Some(dims) => interconnect_elements(dims, &[])
                        .into_iter()
                        .map(|t| Joint::Interconnect(*id, member.uid(), t))
                        .collect(),
                    None => typed(*id, &member)?,
                };
                let expr_side = match &expr_ic {
                    Some((root, dims)) => {
                        if roots.len() != 1 {
                            return Err(format!(
                                "{}: an interconnect net in a concatenation on a port connection is not supported",
                                what()
                            ));
                        }
                        let prefix = element_path(target).map(|p| p.idx).ok_or_else(|| {
                            format!("{}: an interconnect select that is not constant", what())
                        })?;
                        interconnect_elements(dims, &prefix)
                            .into_iter()
                            .map(|t| Joint::Interconnect(*parent, root.uid(), t))
                            .collect()
                    }
                    None => {
                        let whole = vj_sim::symid::is_value_name(target.kind())
                            .then(|| target.referenced_symbol())
                            .flatten();
                        match whole {
                            Some(s) => typed(*parent, &s)?,
                            None => {
                                return Err(format!(
                                    "{}: an interconnect port is connected to an expression that is not a net (LRM 6.6.8)",
                                    what()
                                ));
                            }
                        }
                    }
                };
                if member_side.len() != expr_side.len() {
                    return Err(format!(
                        "{}: an interconnect connection of {} elements to {}",
                        what(),
                        member_side.len(),
                        expr_side.len()
                    ));
                }
                for (a, b) in member_side.iter().zip(&expr_side) {
                    for j in [a, b] {
                        if joint_seen.insert(j.clone()) {
                            joint_list.push(j.clone());
                        }
                    }
                    joints.union(a, b);
                }
                ic_ports.push((*id, port.uid()));
                continue;
            }
            // A port both of whose sides are whole nets of a user-defined
            // nettype collapses to ONE simulated net, whatever its direction
            // (LRM 23.3.3.7); the two nettypes must be the same (23.3.3). A
            // connection with a user nettype on one side only is a
            // continuous assignment (below). An unpacked array of such nets
            // collapses element by element.
            if let Some(&child_ty) = user.by_net.get(&(*id, member.uid())) {
                let parent_net = vj_sim::symid::is_value_name(target.kind())
                    .then(|| target.referenced_symbol())
                    .flatten()
                    .filter(|pn| is_net(pn) && signals[parent].contains_key(&pn.uid()));
                if let Some(pn) = parent_net
                    && let Some(&parent_ty) = user.by_net.get(&(*parent, pn.uid()))
                {
                    if parent_ty != child_ty {
                        return Err(format!(
                            "{}: port `{}` of nettype `{}` is connected to net `{}` of nettype `{}` (LRM 23.3.3: both sides must be the same nettype)",
                            inst.hierarchical_path(),
                            port.name(),
                            user.types[child_ty].name,
                            pn.name(),
                            user.types[parent_ty].name
                        ));
                    }
                    union_nets(
                        &mut find,
                        &(*id, member.uid()),
                        &(*parent, pn.uid()),
                        &rows_of,
                    )?;
                    out.inout_ports.insert((*id, port.uid()));
                    continue;
                }
            }
            match port.port_direction() {
                ArgumentDirection::In => {
                    if is_net(&member) && signals[id].contains_key(&member.uid()) {
                        drivers
                            .entry((*id, member.uid()))
                            .or_default()
                            .push(Driver {
                                key: DriverKey::Port(*id, port.uid(), member.uid()),
                                strength: strong(),
                                path: None,
                            });
                    }
                }
                ArgumentDirection::Out => {
                    let lhs = if expr.kind() == ExpressionKind::Assignment {
                        expr.left()
                    } else {
                        Some(expr)
                    };
                    if vj_sim::symid::is_value_name(target.kind())
                        && let Some(pn) = target.referenced_symbol()
                        && is_net(&pn)
                        && is_net(&member)
                        && !user.by_net.contains_key(&(*parent, pn.uid()))
                        && !user.by_net.contains_key(&(*id, member.uid()))
                        && let Some(ps) = signals[parent].get(&pn.uid())
                        && let Some(cs) = signals[id].get(&member.uid())
                        && !is_memory(ps)
                        && !is_memory(cs)
                        && ps.width == cs.width
                    {
                        out_cands.push(OutCand {
                            child: (*id, member.uid()),
                            parents: vec![(*parent, pn.uid())],
                            port: (*id, port.uid()),
                            keys: vec![DriverKey::Port(*id, port.uid(), pn.uid())],
                            switches: None,
                        });
                    } else if is_net(&member)
                        && !user.by_net.contains_key(&(*id, member.uid()))
                        && let Some(cs) = signals[id].get(&member.uid())
                        && !is_memory(cs)
                        && let Some((planned, bases)) = out_select_plan(
                            target,
                            cs.width,
                            (*id, member.uid()),
                            *parent,
                            &signals[parent],
                            &user.by_net,
                        )
                    {
                        // A select or concatenation of parent nets: the
                        // port joins them bit by bit when they have other
                        // drivers (below).
                        out_cands.push(OutCand {
                            child: (*id, member.uid()),
                            keys: bases
                                .iter()
                                .map(|b| DriverKey::Port(*id, port.uid(), b.clone()))
                                .collect(),
                            parents: bases.into_iter().map(|b| (*parent, b)).collect(),
                            port: (*id, port.uid()),
                            switches: Some(planned),
                        });
                    }
                    for root in lhs.map(lvalue_roots).unwrap_or_default() {
                        if is_net(&root) && signals[parent].contains_key(&root.uid()) {
                            if is_net(&member) {
                                out_inherit.push((
                                    (*parent, root.uid()),
                                    DriverKey::Port(*id, port.uid(), root.uid()),
                                    (*id, member.uid()),
                                ));
                            }
                            drivers
                                .entry((*parent, root.uid()))
                                .or_default()
                                .push(Driver {
                                    key: DriverKey::Port(*id, port.uid(), root.uid()),
                                    strength: strong(),
                                    path: lhs.and_then(element_path),
                                });
                        }
                    }
                }
                ArgumentDirection::InOut => {
                    if vj_sim::symid::is_value_name(target.kind())
                        && let Some(pn) = target.referenced_symbol()
                        && is_net(&pn)
                        && is_net(&member)
                        && signals[parent].contains_key(&pn.uid())
                        && signals[id].contains_key(&member.uid())
                    {
                        union_nets(
                            &mut find,
                            &(*id, member.uid()),
                            &(*parent, pn.uid()),
                            &rows_of,
                        )?;
                        merges.push(((*id, member.uid()), (*parent, pn.uid())));
                        out.inout_ports.insert((*id, port.uid()));
                    } else if let Some((pn, row)) =
                        inout_element_target(target, signals, parent, &rows_of)
                        && is_net(&pn)
                        && is_net(&member)
                        && !user.by_net.contains_key(&(*parent, pn.uid()))
                        && !user.by_net.contains_key(&(*id, member.uid()))
                        && signals[id].contains_key(&member.uid())
                        && !rows_of.contains_key(&(*id, member.uid()))
                        && kinds.get(&(*id, member.uid())) == kinds.get(&(*parent, pn.uid()))
                        && signals[parent][&pn.uid()].width == signals[id][&member.uid()].width
                    {
                        // LRM 23.3.3.3 / 6.6.7: one element of an unpacked
                        // array of nets is a net of its own, so the port net
                        // and that element join as one simulated net.
                        find.union(
                            &Joint::Typed((*id, member.uid())),
                            &Joint::Row((*parent, pn.uid()), row),
                        );
                        out.inout_ports.insert((*id, port.uid()));
                    } else if let Some((sel, base)) = inout_select_target(target)
                        && let Some(pn) = base.referenced_symbol()
                        && is_net(&pn)
                        && is_net(&member)
                        && !user.by_net.contains_key(&(*parent, pn.uid()))
                        && !user.by_net.contains_key(&(*id, member.uid()))
                        && let Some(ps) = signals[parent].get(&pn.uid())
                        && let Some(cs) = signals[id].get(&member.uid())
                        && !is_memory(ps)
                        && !is_memory(cs)
                        && let Ok((lo, w)) = vj_codegen::select::constant_window(sel, ps.width)
                        && w == cs.width
                    {
                        for k in 0..w {
                            select_port_switches.push((
                                (*id, member.uid(), k),
                                (*parent, pn.uid(), lo + k),
                                Conducts::Always,
                                false,
                                (None, None),
                            ));
                        }
                        out.inout_ports.insert((*id, port.uid()));
                    } else if let Some(leaves) = inout_concat_leaves(target)
                        && is_net(&member)
                        && !user.by_net.contains_key(&(*id, member.uid()))
                        && let Some(cs) = signals[id].get(&member.uid())
                        && !is_memory(cs)
                    {
                        // LRM 23.3.3.2: a concatenation of nets and constant
                        // selects joins the port bit by bit, the first
                        // operand at the most significant end.
                        let mut planned: Vec<PendingSwitch> = Vec::new();
                        let mut top = cs.width;
                        let mut ok = true;
                        for (base, sel) in leaves {
                            let Some(pn) = base.referenced_symbol() else {
                                ok = false;
                                break;
                            };
                            let ps = signals[parent].get(&pn.uid());
                            let win = match (ps, sel) {
                                (Some(ps), None) if !is_memory(ps) => Some((0, ps.width)),
                                (Some(ps), Some(sel)) if !is_memory(ps) => {
                                    vj_codegen::select::constant_window(sel, ps.width).ok()
                                }
                                _ => None,
                            };
                            let Some((lo, w)) = win else {
                                ok = false;
                                break;
                            };
                            if !is_net(&pn)
                                || user.by_net.contains_key(&(*parent, pn.uid()))
                                || w > top
                            {
                                ok = false;
                                break;
                            }
                            top -= w;
                            for k in 0..w {
                                planned.push((
                                    (*id, member.uid(), top + k),
                                    (*parent, pn.uid(), lo + k),
                                    Conducts::Always,
                                    false,
                                    (None, None),
                                ));
                            }
                        }
                        if ok && top == 0 {
                            select_port_switches.extend(planned);
                            out.inout_ports.insert((*id, port.uid()));
                        }
                    }
                }
                ArgumentDirection::Ref => {}
            }
        }
    }

    // The merged classes: each is one simulated net, which must end up typed
    // (LRM 23.3.3.7.1: an interconnect simulated net is illegal), so every
    // typed net or element of a class -- and every interconnect scalar a
    // primitive terminal makes a wire -- joins one group, the dominating net
    // kind being chosen as for any port collapsing (23.3.3.7).
    let mut ic_classes: Vec<(Joint, Vec<Joint>)> = Vec::new();
    {
        let mut index: HashMap<Joint, usize> = HashMap::new();
        for j in &joint_list {
            let r = joints.root(j);
            let k = *index.entry(r.clone()).or_insert_with(|| {
                ic_classes.push((r, Vec::new()));
                ic_classes.len() - 1
            });
            ic_classes[k].1.push(j.clone());
        }
    }
    for (_, members) in &ic_classes {
        // The element a member is in the simulated net (`None`: an
        // interconnect element that stays untyped).
        let typed: Vec<Joint> = members
            .iter()
            .filter_map(|j| match j {
                Joint::Typed(_) | Joint::Row(..) => Some(j.clone()),
                Joint::Interconnect(i, s, _) if ic_wires.contains(&(*i, s.clone())) => {
                    Some(Joint::Typed((*i, s.clone())))
                }
                // An element a primitive terminal reads or drives: a wire.
                Joint::Interconnect(i, s, t) if ic_cells.contains(&(*i, s.clone(), t.clone())) => {
                    Some(j.clone())
                }
                Joint::Interconnect(..) => None,
            })
            .collect();
        let name = members
            .iter()
            .find_map(|j| match j {
                Joint::Interconnect(_, s, _) => Some(s.path()),
                Joint::Typed(_) | Joint::Row(..) => None,
            })
            .unwrap_or_default();
        // A net with a type leads (an element cell has none).
        let Some(first) = typed
            .iter()
            .find(|j| !matches!(j, Joint::Interconnect(..)))
            .or(typed.first())
        else {
            return Err(format!(
                "interconnect net `{name}` is never connected to a net with a type: a simulated net of interconnect type is illegal (LRM 23.3.3.7.1)"
            ));
        };
        let owner = |j: &Joint| match j {
            Joint::Typed(n) | Joint::Row(n, _) => n.clone(),
            Joint::Interconnect(i, s, _) => (*i, s.clone()),
        };
        // An element cell is a scalar wire: one bit, no nettype.
        let width_of = |j: &Joint| match j {
            Joint::Interconnect(..) => 1,
            _ => signals[&owner(j).0][&owner(j).1].width,
        };
        let width = width_of(first);
        let user_ty = match first {
            Joint::Interconnect(..) => None,
            _ => user.by_net.get(&owner(first)),
        };
        for j in &typed {
            let n = owner(j);
            let n_user = match j {
                Joint::Interconnect(..) => None,
                _ => user.by_net.get(&n),
            };
            if width_of(j) != width {
                return Err(format!(
                    "interconnect net `{name}` joins nets of different widths ({} and {})",
                    n.1.path(),
                    owner(first).1.path()
                ));
            }
            if n_user != user_ty {
                return Err(format!(
                    "interconnect net `{name}` joins nets of different net types ({} and {}) (LRM 23.3.3)",
                    n.1.path(),
                    owner(first).1.path()
                ));
            }
            find.union(first, j);
            if !matches!(first, Joint::Interconnect(..)) && !matches!(j, Joint::Interconnect(..)) {
                merges.push((owner(first), n));
            }
        }
    }
    out.inout_ports.extend(ic_ports);
    // An interconnect net no connection ever mentions is a simulated net of
    // interconnect type, which is as illegal (23.3.3.7.1). A port's own net
    // is judged by what is connected to it, so only body nets count here.
    for (id, body, inst, parent) in instances {
        let ports: HashSet<SymbolId> = if parent.is_some() {
            inst.instance_port_connections()
                .map(|c| {
                    let p = c.port();
                    p.port_internal_symbol().unwrap_or(p).uid()
                })
                .collect()
        } else {
            HashSet::new()
        };
        for m in vj_sim::netlist::module_items(body) {
            if interconnect_dims_of(&m).is_none()
                || ports.contains(&m.uid())
                || ic_wires.contains(&(*id, m.uid()))
                || ic_cells.iter().any(|(i, s, _)| i == id && *s == m.uid())
            {
                continue;
            }
            if !joint_seen
                .iter()
                .any(|j| matches!(j, Joint::Interconnect(i, s, _) if i == id && *s == m.uid()))
            {
                return Err(format!(
                    "{}: interconnect net `{}` is never connected to a net with a type: a simulated net of interconnect type is illegal (LRM 23.3.3.7.1)",
                    m.hierarchical_path(),
                    m.name()
                ));
            }
        }
    }

    // Aliases: whole nets of one width joined.
    let mut pending_switches: Vec<PendingSwitch> = select_port_switches;
    for (id, body, _, _) in instances {
        let own = &signals[id];
        let mut join = |what: &str, refs: Vec<Expression<'d>>, at: &Symbol<'d>| {
            let whole_net = |e: Expression<'d>| {
                let e = connection_target(e);
                vj_sim::symid::is_value_name(e.kind())
                    .then(|| e.referenced_symbol())
                    .flatten()
                    .filter(|s| is_net(s) && own.contains_key(&s.uid()))
            };
            // An alias of bit-selects, part-selects or concatenations
            // (`alias {a, b} = c;`, LRM 1800-2023 10.11): the same net per
            // bit. Joined bit by bit through always-conducting bidirectional
            // connections, which resolve exactly as one net does.
            if refs.iter().any(|&e| whole_net(e).is_none()) {
                fn bits_of<'d>(
                    e: Expression<'d>,
                    own: &HashMap<SymbolId, SignalSlot>,
                    out: &mut Vec<(SymbolId, u32)>,
                ) -> bool {
                    let e = connection_target(e);
                    if e.kind() == ExpressionKind::Concatenation {
                        // Operands run most significant first.
                        let mut ops = e.operands();
                        ops.reverse();
                        return ops.into_iter().all(|o| bits_of(o, own, out));
                    }
                    let Some((net, lo, w, None)) =
                        switch_terminal(e, own, &HashMap::new(), InstanceId(0))
                    else {
                        return false;
                    };
                    out.extend((0..w).map(|k| (net.clone(), lo + k)));
                    true
                }
                let mut lanes: Vec<Vec<(SymbolId, u32)>> = Vec::new();
                for &e in &refs {
                    let mut bits = Vec::new();
                    if !bits_of(e, own, &mut bits) {
                        return Err(format!(
                            "{}: {what} of something other than nets, bit-selects, part-selects or concatenations of them (LRM 10.11)",
                            at.hierarchical_path()
                        ));
                    }
                    lanes.push(bits);
                }
                if lanes.windows(2).any(|w| w[0].len() != w[1].len()) {
                    return Err(format!(
                        "{}: {what} of operands of different widths",
                        at.hierarchical_path()
                    ));
                }
                if lanes
                    .iter()
                    .flatten()
                    .any(|(n, _)| user.by_net.contains_key(&(*id, n.clone())))
                {
                    return Err(format!(
                        "{}: {what} of a bit-select or concatenation of a net of a user-defined nettype (only whole nets of one nettype alias, LRM 6.6.7)",
                        at.hierarchical_path()
                    ));
                }
                for w in lanes.windows(2) {
                    for (a, b) in w[0].iter().zip(&w[1]) {
                        pending_switches.push((
                            (*id, a.0.clone(), a.1),
                            (*id, b.0.clone(), b.1),
                            Conducts::Always,
                            false,
                            (None, None),
                        ));
                    }
                }
                return Ok(());
            }
            let mut nets = Vec::new();
            for e in refs {
                nets.push(whole_net(e).expect("checked above"));
            }
            let width = |n: &Symbol<'_>| own[&n.uid()].width;
            if nets.windows(2).any(|w| width(&w[0]) != width(&w[1])) {
                return Err(format!(
                    "{}: {what} of nets of different widths",
                    at.hierarchical_path()
                ));
            }
            for w in nets.windows(2) {
                union_nets(&mut find, &(*id, w[0].uid()), &(*id, w[1].uid()), &rows_of)?;
            }
            Ok(())
        };
        for m in vj_sim::netlist::module_items(body) {
            if m.kind() == SymbolKind::NetAlias {
                join("an alias", m.net_alias_net_references().collect(), &m)?;
            }
        }
        // Bidirectional switches: their bit-to-bit connections, joined into
        // networks once the groups exist (below).
        for inst in crate::primitives::instances(body) {
            let Some(name) = crate::primitives::type_name(&inst, trees) else {
                continue;
            };
            let (resistive, base) = match name.strip_prefix('r') {
                Some(rest) if rest.starts_with("tran") => (true, rest.to_string()),
                _ => (false, name.clone()),
            };
            if !base.starts_with("tran") {
                continue;
            }
            let at = || inst.hierarchical_path();
            let conns: Vec<Expression<'d>> = inst.primitive_instance_port_connections().collect();
            let conducts_on = match base.as_str() {
                "tran" => None,
                "tranif1" => Some(true),
                "tranif0" => Some(false),
                other => return Err(format!("{}: unknown switch `{other}`", at())),
            };
            let expected = if conducts_on.is_some() { 3 } else { 2 };
            if conns.len() != expected {
                return Err(format!("{}: a switch with {} terminals", at(), conns.len()));
            }
            let (a_net, a_lo, a_w, a_row) = switch_terminal(conns[0], own, &rows_of, *id)
                .ok_or_else(|| {
                    format!(
                        "{}: a switch terminal that is not a net or a bit of one",
                        at()
                    )
                })?;
            let (b_net, b_lo, b_w, b_row) = switch_terminal(conns[1], own, &rows_of, *id)
                .ok_or_else(|| {
                    format!(
                        "{}: a switch terminal that is not a net or a bit of one",
                        at()
                    )
                })?;
            // An element of an array of switches takes its own slice of a
            // wide terminal (LRM 28.3.5); slang hands a bidirectional
            // primitive the whole terminal for every element.
            let (arr_n, arr_pos) =
                switch_array_position(&inst).map_err(|e| format!("{}: {e}", at()))?;
            let slice = |lo: u32, w: u32| {
                array_slice(lo, w, arr_n, arr_pos).ok_or_else(|| {
                    format!(
                        "{}: a switch-array terminal of {w} bits does not divide among {arr_n} elements (LRM 28.3.5)",
                        at()
                    )
                })
            };
            let (a_lo, a_w) = slice(a_lo, a_w)?;
            let (b_lo, b_w) = slice(b_lo, b_w)?;
            if a_w != b_w {
                return Err(format!("{}: switch terminals of different widths", at()));
            }
            // A net of a user-defined nettype is switched as a whole, never
            // bit by bit (LRM 28.8: a switch connects nets, of one nettype).
            let is_user = |n: &SymbolId| user.by_net.contains_key(&(*id, n.clone()));
            let n_bits = if is_user(&a_net) || is_user(&b_net) {
                for (net, w) in [(&a_net, a_w), (&b_net, b_w)] {
                    if is_user(net) && w != own[net].width {
                        return Err(format!(
                            "{}: a switch terminal that is a bit-select of a net of a user-defined nettype (LRM 28.8: a switch connects whole nets)",
                            at()
                        ));
                    }
                }
                1
            } else {
                a_w
            };
            let conducts = match conducts_on {
                None => Conducts::Always,
                Some(on) => {
                    let control = control_terminal(conns[2], *id, own, (arr_n, arr_pos))
                        .ok_or_else(|| {
                            format!(
                                "{}: a switch control that is not a signal bit or a constant",
                                at()
                            )
                        })?;
                    // LRM 28.8 / 28.16: a tranif's delay is its turn-on / turn-off
                    // time: the switch conducts on a delayed copy of the control.
                    let control = match control {
                        Control::Bit(ci, cslot, cbit)
                            if inst.primitive_instance_delay().is_some() =>
                        {
                            if matches!(cslot.class, SignalSlotClass::Memory { .. }) {
                                return Err(format!(
                                    "{}: a `{name}` switch with a turn-on/turn-off delay whose control is an element of an unpacked array (LRM 28.16) is not supported",
                                    at()
                                ));
                            }
                            let cell = out.bank_widths.len() as u32;
                            out.bank_widths.push(1);
                            out.delayed_controls.push(DelayedControl {
                                inst: *id,
                                prim: inst.uid(),
                                source: (ci, cslot, cbit),
                                cell,
                                on_is_one: on,
                            });
                            Control::Bank(cell)
                        }
                        c => c,
                    };
                    Conducts::When(control, on)
                }
            };
            for k in 0..n_bits {
                pending_switches.push((
                    (*id, a_net.clone(), a_lo + k),
                    (*id, b_net.clone(), b_lo + k),
                    conducts,
                    resistive,
                    (a_row, b_row),
                ));
            }
        }
    }

    // Output ports (LRM 23.3.3.7): a child's output net and the whole parent
    // net it is connected to are ONE net, so the child reads what the others
    // drive too. Only a port whose parent net (with everything already joined
    // to it) has a driver besides this port's own needs it; any other output
    // stays a one-way driver of the parent, at no cost. Iterated: collapsing
    // one port can bring outside drivers to a net behind another (a chain of
    // output ports up the hierarchy).
    let mut pending = std::mem::take(&mut out_cands);
    let sdf = uses_sdf(trees);
    // A module with a `specify` block keeps its output ports one-way
    // drivers: a module path retimes the port net's own driver (LRM 30.4),
    // which a collapsed net no longer has.
    let specified: HashSet<InstanceId> = instances
        .iter()
        .filter(|(_, body, _, _)| body.members().any(|m| m.kind() == SymbolKind::SpecifyBlock))
        .map(|(id, ..)| *id)
        .collect();
    pending.retain(|c| !specified.contains(&c.child.0));
    while !pending.is_empty() {
        let mut per_root: HashMap<Joint, usize> = HashMap::new();
        for (n, ds) in &drivers {
            *per_root
                .entry(find.root(&Joint::Typed(n.clone())))
                .or_default() += ds.len();
        }
        let before = pending.len();
        let mut rest = Vec::new();
        for c in pending {
            let ck = kinds[&c.child];
            let mut roots: Vec<Joint> = Vec::new();
            for p in &c.parents {
                let r = find.root(&Joint::Typed(p.clone()));
                if !roots.contains(&r) {
                    roots.push(r);
                }
            }
            let total: usize = roots
                .iter()
                .map(|r| per_root.get(r).copied().unwrap_or(0))
                .sum();
            let own: usize = c
                .parents
                .iter()
                .collect::<HashSet<_>>()
                .into_iter()
                .map(|p| {
                    drivers.get(p).map_or(0, |ds| {
                        ds.iter().filter(|d| c.keys.contains(&d.key)).count()
                    })
                })
                .sum();
            let kinds_ok = c
                .parents
                .iter()
                .all(|p| ck == kinds[p] || ck == NetKind::Wire || kinds[p] == NetKind::Wire);
            if total - own == 0 || !kinds_ok {
                rest.push(c);
                continue;
            }
            if sdf && instance_reads_net(instances, c.child.0, c.child.1.clone()) {
                return Err(format!(
                    "the child of output port `{}` reads its own port net, which shares its net with drivers outside the child, which port collapsing (LRM 23.3.3.7) would merge into one net with the parent's other drivers, but this design calls $sdf_annotate and SDF INTERCONNECT names sources by output port; the combination is not supported (drive the parent net through a separate net, or drop the annotation)",
                    c.port.1.path()
                ));
            }
            if sdf {
                // Nothing in the child reads the port net, so the one-way
                // driver is exact and SDF keeps its per-port source.
                rest.push(c);
                continue;
            }
            match &c.switches {
                None => {
                    union_nets(&mut find, &c.child, &c.parents[0], &rows_of)?;
                    merges.push((c.child.clone(), c.parents[0].clone()));
                }
                Some(sw) => pending_switches.extend(sw.iter().cloned()),
            }
            for p in &c.parents {
                if let Some(ds) = drivers.get_mut(p) {
                    ds.retain(|d| !c.keys.contains(&d.key));
                }
            }
            out_inherit.retain(|(_, k, _)| !c.keys.contains(k));
            out.inout_ports.insert(c.port);
        }
        if rest.len() == before {
            break;
        }
        pending = rest;
    }

    // Net collapsing (LRM 23.3.3.7): replay the merges in order, each giving
    // the class it forms the type Table 23-1 picks from its two sides.
    let mut collapse: Find<NetId> = Find(HashMap::new());
    let mut collapsed: HashMap<NetId, NetKind> = HashMap::new();
    for (internal, external) in &merges {
        let (ri, re) = (collapse.root(internal), collapse.root(external));
        let ki = collapsed.get(&ri).copied().unwrap_or(kinds[internal]);
        let ke = collapsed.get(&re).copied().unwrap_or(kinds[external]);
        let k = dominating_kind(ki, ke);
        if ri != re {
            collapse.union(internal, external);
        }
        let root = collapse.root(internal);
        collapsed.insert(root, k);
    }

    // Classes: the elements joined by inout ports, aliases, interconnect
    // connections or user-net port collapsing, else each net or element
    // alone.
    let mut elems: Vec<Joint> = Vec::new();
    let mut legacy_mem: Vec<NetId> = Vec::new();
    for n in &all {
        match rows_of.get(n) {
            Some(Some(rows)) => {
                elems.extend(rows.iter().map(|(r, _)| Joint::Row(n.clone(), *r)));
            }
            Some(None) => legacy_mem.push(n.clone()),
            None => elems.push(Joint::Typed(n.clone())),
        }
    }
    elems.extend(
        ic_cells
            .iter()
            .map(|(i, s, t)| Joint::Interconnect(*i, s.clone(), t.clone())),
    );
    // Strength passes through an output port: when every driver of the child
    // net has one strength pair, the port's driver takes it (so a
    // `(strong0, pull1)` gate behind a port still loses to a strong driver
    // of the parent net, and not the other way round). Iterated so a chain of
    // ports settles; a child net with mixed strengths stays strong.
    for _ in 0..out_inherit.len().min(32) {
        let mut changed = false;
        for (pnet, key, cnet) in &out_inherit {
            let Some(cs) = drivers.get(cnet) else {
                continue;
            };
            let Some(first) = cs.first().map(|d| d.strength) else {
                continue;
            };
            if cs.iter().any(|d| d.strength != first) {
                continue;
            }
            if let Some(d) = drivers
                .get_mut(pnet)
                .and_then(|v| v.iter_mut().find(|d| d.key == *key))
                && d.strength != first
            {
                d.strength = first;
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    // An unpacked-array net whose layout cannot be enumerated keeps the old
    // behaviour: its elements are driven straight into its rows, never
    // resolved, so two drivers of one element are a loud error.
    for n in &legacy_mem {
        let paths: Vec<&ElemPath> = drivers
            .get(n)
            .map(|ds| ds.iter().filter_map(|d| d.path.as_ref()).collect())
            .unwrap_or_default();
        for (i, a) in paths.iter().enumerate() {
            if paths[i + 1..].iter().any(|b| paths_overlap(a, b)) {
                return Err(format!(
                    "{}: two continuous drivers of one element of the unpacked-array net `{}` are not supported (an unpacked-array net's elements are not resolved)",
                    n.1.path(),
                    n.1.path()
                ));
            }
        }
    }
    let mut classes: Vec<Class> = Vec::new();
    {
        let mut index: HashMap<Joint, usize> = HashMap::new();
        let mut members: Vec<Vec<Joint>> = Vec::new();
        let mut roots: Vec<Joint> = Vec::new();
        for j in &elems {
            let r = find.root(j);
            let k = *index.entry(r.clone()).or_insert_with(|| {
                members.push(Vec::new());
                roots.push(r);
                members.len() - 1
            });
            members[k].push(j.clone());
        }
        // The groups a switch touches (by root) are resolved whatever their
        // drivers.
        let switched_roots: HashSet<Joint> = pending_switches
            .iter()
            .flat_map(|(a, b, _, _, (ra, rb))| {
                [((a.0, a.1.clone()), *ra), ((b.0, b.1.clone()), *rb)]
            })
            .map(|(n, row)| find.root(&end_joint(n, row)))
            .collect();
        for (root, js) in roots.into_iter().zip(members) {
            let mut nets = Vec::new();
            let mut rows = Vec::new();
            let mut cells: Vec<IcElem> = Vec::new();
            let mut owners: Vec<NetId> = Vec::new();
            for j in &js {
                let n = match j {
                    Joint::Typed(n) => {
                        nets.push(n.clone());
                        n
                    }
                    Joint::Row(n, r) => {
                        rows.push((n.clone(), *r));
                        n
                    }
                    Joint::Interconnect(i, s, t) => {
                        cells.push((*i, s.clone(), t.clone()));
                        continue;
                    }
                };
                if !owners.contains(n) {
                    owners.push(n.clone());
                }
            }
            let mut ds = Vec::new();
            for cell in &cells {
                for d in cell_drivers
                    .get(cell)
                    .map(Vec::as_slice)
                    .unwrap_or_default()
                {
                    ds.push((d.clone(), None, (cell.0, cell.1.clone())));
                }
            }
            for o in &owners {
                for d in drivers.get(o).map(Vec::as_slice).unwrap_or_default() {
                    if nets.contains(o) {
                        ds.push((d.clone(), None, o.clone()));
                    }
                    for (n, r) in rows.iter().filter(|(n, _)| n == o) {
                        if covers(&d.path, row_idx[&(n.clone(), *r)]) {
                            ds.push((d.clone(), Some(*r), o.clone()));
                        }
                    }
                }
            }
            // The simulated net's type: the merges' Table 23-1 result per
            // collapsed class; classes joined only by aliases or switches
            // contribute their first non-`wire` type.
            let kind = owners
                .iter()
                .map(|n| {
                    collapsed
                        .get(&collapse.root(n))
                        .copied()
                        .unwrap_or(kinds[n])
                })
                .find(|k| *k != NetKind::Wire)
                .unwrap_or(NetKind::Wire);
            let user_ty = owners.iter().find_map(|n| user.by_net.get(n).copied());
            let switched = switched_roots.contains(&root);
            // A class of element cells alone is 1 bit wide (scalar wires).
            let width = owners.first().map_or(1, |o| signals[&o.0][&o.1].width);
            classes.push(Class {
                root,
                nets,
                rows,
                cells,
                owners,
                ds,
                kind,
                user: user_ty,
                switched,
                width,
            });
        }
    }
    // Which classes become groups. A user-defined nettype (LRM 6.6.7): the
    // nets of a class share one nettype. With a resolution function, every
    // class resolves -- even with a single driver or none (the function is
    // called at least once at time 0, 6.7.3). Without one, a net has at most
    // one driver.
    let mut made: Vec<bool> = Vec::with_capacity(classes.len());
    for c in &classes {
        let first_name = c
            .owners
            .first()
            .map(|o| o.1.path())
            .or_else(|| c.cells.first().map(|e| e.1.path()))
            .unwrap_or_default();
        if let Some(t) = c.user {
            let ty = &user.types[t];
            if ty.func.is_none() && c.ds.len() > 1 {
                return Err(format!(
                    "{}: net of nettype `{}` has {} drivers, but the nettype has no resolution function (LRM 6.6.7: at most one driver)",
                    first_name,
                    ty.name,
                    c.ds.len()
                ));
            }
            if ty.func.is_some() && ty.data_array {
                return Err(format!(
                    "{}: nettype `{}` has an unpacked-array data type AND a resolution function, which is not supported: the function's `input T driver[]` is a dynamic array of unpacked arrays, which the compiler cannot lower yet (LRM 6.6.7)",
                    first_name, ty.name
                ));
            }
        }
        if !c.rows.is_empty() && c.kind == NetKind::TriReg {
            return Err(format!(
                "{}: an element of an unpacked array of `trireg` nets is not supported (LRM 28.16.2)",
                first_name
            ));
        }
        let user_resolves = c.user.is_some_and(|t| user.types[t].func.is_some());
        let disjoint_prims = c.ds.len() >= 2
            && c.nets.len() == 1
            && c.rows.is_empty()
            && c.cells.is_empty()
            && !c.switched
            && c.user.is_none()
            && !resolves_alone(c.kind)
            && specify_dests.contains(&c.nets[0])
            && c.ds.iter().all(|(d, row, _)| {
                row.is_none()
                    && matches!(d.key, DriverKey::Prim(..))
                    && d.strength == vj_sim::state::DriveStrengthPair::STRONG
            })
            && windows.get(&c.nets[0]).is_some_and(|w| {
                w.len() == c.ds.len()
                    && w.iter().enumerate().all(|(i, a)| {
                        a.is_some_and(|(alo, aw)| {
                            w[i + 1..].iter().all(|b| {
                                b.is_some_and(|(blo, bw)| alo + aw <= blo || blo + bw <= alo)
                            })
                        })
                    })
            });
        made.push(
            (c.ds.len() >= 2 && !disjoint_prims)
                || c.nets.len() + c.rows.len() + c.cells.len() >= 2
                || !c.cells.is_empty()
                || resolves_alone(c.kind)
                || c.switched
                || user_resolves
                // `%v` prints a net's strengths, which only a resolver
                // computes: a driven net is resolved even alone.
                || (shows_strength && !c.ds.is_empty())
                // A VPI library reads `vpiStrengthVal`: a net driven below
                // the default strength is resolved to record it.
                || (tracks_strengths()
                    && c.ds.iter().any(|(d, _, _)| {
                        d.strength != vj_sim::state::DriveStrengthPair::STRONG
                    })),
        );
    }
    // An unpacked-array net resolved through some element is resolved through
    // all of them: its drivers write contribution memories, never the net.
    let mut classes_of: HashMap<NetId, Vec<usize>> = HashMap::new();
    for (k, c) in classes.iter().enumerate() {
        for (n, _) in &c.rows {
            let list = classes_of.entry(n.clone()).or_default();
            if !list.contains(&k) {
                list.push(k);
            }
        }
    }
    let mut changed = true;
    while changed {
        changed = false;
        for list in classes_of.values() {
            if list.iter().any(|&k| made[k]) && list.iter().any(|&k| !made[k]) {
                for &k in list {
                    made[k] = true;
                }
                changed = true;
            }
        }
    }

    let mut group_of_root: HashMap<Joint, usize> = HashMap::new();
    // One contribution memory per driver of an unpacked-array net, shared by
    // the groups of its elements.
    let mut mem_cell: HashMap<DriverKey, u32> = HashMap::new();
    for (c, made) in classes.into_iter().zip(made) {
        if !made {
            continue;
        }
        let mut group = Group {
            kind: c.kind,
            width: c.width,
            nets: c.nets,
            drivers: Vec::new(),
            switched: c.switched,
            user: c.user,
            rows: c.rows,
            cells: Vec::new(),
            driver_rows: Vec::new(),
        };
        // Each element a primitive terminal reads is a 1-bit bank cell the
        // resolver writes.
        for cell in c.cells {
            let slot = out.bank_widths.len() as u32;
            out.bank_widths.push(1);
            out.ic_elem.insert(cell, slot);
            group.cells.push(slot);
        }
        if c.switched {
            group_of_root.insert(c.root.clone(), out.groups.len());
        }
        for (d, row, owner) in c.ds {
            let slot = match row {
                Some(_) => *mem_cell.entry(d.key.clone()).or_insert_with(|| {
                    let slot = out.bank_widths.len() as u32;
                    let net_slot = signals[&owner.0][&owner.1];
                    out.bank_widths.push(net_slot.width);
                    out.bank_mem.insert(slot, net_slot);
                    out.contrib.insert(d.key.clone(), slot);
                    slot
                }),
                None => {
                    let slot = out.bank_widths.len() as u32;
                    out.bank_widths.push(c.width);
                    out.contrib.insert(d.key.clone(), slot);
                    slot
                }
            };
            group.drivers.push((slot, d.strength));
            group.driver_rows.push(row);
        }
        out.groups.push(group);
    }
    // Switch networks: the groups joined by switches, each with its own.
    let mut switches = Vec::new();
    for (a, b, conducts, resistive, (ra, rb)) in pending_switches {
        let ga = group_of_root[&find.root(&end_joint((a.0, a.1), ra))];
        let gb = group_of_root[&find.root(&end_joint((b.0, b.1), rb))];
        switches.push(Switch {
            a: (ga, a.2),
            b: (gb, b.2),
            conducts,
            resistive,
        });
    }
    let mut parent: Vec<usize> = (0..out.groups.len()).collect();
    fn top(p: &mut [usize], mut x: usize) -> usize {
        while p[x] != x {
            p[x] = p[p[x]];
            x = p[x];
        }
        x
    }
    for s in &switches {
        let (x, y) = (top(&mut parent, s.a.0), top(&mut parent, s.b.0));
        if x != y {
            parent[x] = y;
        }
    }
    let mut by_top: std::collections::BTreeMap<usize, Network> = std::collections::BTreeMap::new();
    for g in 0..out.groups.len() {
        if out.groups[g].switched {
            let t = top(&mut parent, g);
            by_top
                .entry(t)
                .or_insert_with(|| Network {
                    groups: Vec::new(),
                    switches: Vec::new(),
                })
                .groups
                .push(g);
        }
    }
    for s in switches {
        let t = top(&mut parent, s.a.0);
        by_top
            .get_mut(&t)
            .expect("a switch's group is switched")
            .switches
            .push(s);
    }
    out.networks = by_top.into_values().collect();
    // A switch network of user-defined nettype nets (LRM 28.8): `tran`,
    // `tranif0` and `tranif1` may connect them; the nets must all be of one
    // nettype (a switch may not join a user-defined and a built-in net, or two
    // different user-defined nettypes); `rtran*` are for built-in scalar nets
    // only. Without a resolution function two driven groups cannot be joined
    // (6.6.7: such a net has at most one driver).
    for net in &out.networks {
        let ty = out.groups[net.groups[0]].user;
        let any_user = net.groups.iter().any(|&g| out.groups[g].user.is_some());
        let name = || {
            net.groups
                .iter()
                .find_map(|&g| out.groups[g].nets.first())
                .map(|n| n.1.path())
                .unwrap_or_default()
        };
        // A switch network writes the elements of unpacked-array nets (LRM
        // 28.7) but not the cells of an interconnect element.
        if net.groups.iter().any(|&g| !out.groups[g].cells.is_empty()) {
            return Err(format!(
                "{}: a switch network that reaches an interconnect array element is not supported",
                name()
            ));
        }
        if !any_user {
            continue;
        }
        if net.groups.iter().any(|&g| out.groups[g].user != ty) || ty.is_none() {
            return Err(format!(
                "{}: a switch connects nets of different nettypes, or a net of a user-defined nettype and a built-in net (LRM 28.8)",
                name()
            ));
        }
        if net.switches.iter().any(|s| s.resistive) {
            return Err(format!(
                "{}: an rtran, rtranif0 or rtranif1 switch on a net of a user-defined nettype (LRM 28.8: only scalar and bit-select built-in nets)",
                name()
            ));
        }
        if let Some(t) = ty
            && user.types[t].func.is_none()
            && net
                .groups
                .iter()
                .filter(|&&g| !out.groups[g].drivers.is_empty())
                .count()
                > 1
        {
            return Err(format!(
                "{}: a switch can join two driven nets of nettype `{}`, which has no resolution function (LRM 6.6.7: at most one driver)",
                name(),
                user.types[t].name
            ));
        }
    }
    Ok(out)
}

/// The named value under a chain of constant-index element/part-selects, when
/// `e` is such a select (`None` for a bare name or anything else).
/// The unpacked-array net and storage row a whole-element connection target
/// (`w[1]`, `w[i][0]` with constant indices over every unpacked dimension, no
/// packed select) names, when the net's rows can be enumerated.
fn inout_element_target<'d>(
    target: Expression<'d>,
    signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    parent: &InstanceId,
    rows_of: &RowsOf,
) -> Option<(Symbol<'d>, u32)> {
    if target.kind() != ExpressionKind::ElementSelect {
        return None;
    }
    let path = element_path(target)?;
    if path.bits.is_some() {
        return None;
    }
    let mut base = target;
    while base.kind() == ExpressionKind::ElementSelect {
        base = base.select_value()?;
    }
    if !vj_sim::symid::is_value_name(base.kind()) {
        return None;
    }
    let pn = base.referenced_symbol()?;
    signals.get(parent)?.get(&pn.uid())?;
    let rows = rows_of.get(&(*parent, pn.uid()))?.as_ref()?;
    let (row, _) = rows.iter().find(|(_, idx)| *idx == path.idx)?;
    Some((pn, *row))
}

fn inout_select_target<'d>(e: Expression<'d>) -> Option<(Expression<'d>, Expression<'d>)> {
    let e = if e.kind() == ExpressionKind::Conversion {
        e.operand()?
    } else {
        e
    };
    if !matches!(
        e.kind(),
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect
    ) {
        return None;
    }
    let sel = e;
    let mut base = e;
    while matches!(
        base.kind(),
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect
    ) {
        base = base.select_value()?;
    }
    vj_sim::symid::is_value_name(base.kind()).then_some((sel, base))
}

/// The operands of an inout port's concatenation connection, flattened
/// (nested concatenations included), first operand first: each a net name
/// (`None`) or a constant select of one (`Some(select)`), paired with its
/// base name. `None` when the target is no concatenation or has another
/// kind of operand.
fn inout_concat_leaves<'d>(
    e: Expression<'d>,
) -> Option<Vec<(Expression<'d>, Option<Expression<'d>>)>> {
    let e = if e.kind() == ExpressionKind::Conversion {
        e.operand()?
    } else {
        e
    };
    if e.kind() != ExpressionKind::Concatenation {
        return None;
    }
    let mut out = Vec::new();
    for o in e.operands() {
        let o = if o.kind() == ExpressionKind::Conversion {
            o.operand()?
        } else {
            o
        };
        if o.kind() == ExpressionKind::Concatenation {
            out.extend(inout_concat_leaves(o)?);
        } else if vj_sim::symid::is_value_name(o.kind()) {
            out.push((o, None));
        } else {
            let (sel, base) = inout_select_target(o)?;
            out.push((base, Some(sel)));
        }
    }
    Some(out)
}

/// The bit-by-bit joints of an output port connected to a constant select or
/// a concatenation of parent nets (LRM 23.3.3.2), with the base nets they
/// touch; `None` when the connection is anything else or the widths differ.
fn out_select_plan(
    target: Expression<'_>,
    width: u32,
    child: NetId,
    parent: InstanceId,
    pscope: &HashMap<SymbolId, SignalSlot>,
    by_net: &HashMap<NetId, usize>,
) -> Option<(Vec<PendingSwitch>, Vec<SymbolId>)> {
    let leaves = if let Some((sel, base)) = inout_select_target(target) {
        vec![(base, Some(sel))]
    } else {
        inout_concat_leaves(target)?
    };
    let mut planned: Vec<PendingSwitch> = Vec::new();
    let mut bases: Vec<SymbolId> = Vec::new();
    let mut top = width;
    for (base, sel) in leaves {
        let pn = base.referenced_symbol()?;
        let ps = pscope.get(&pn.uid())?;
        if pn.kind() != SymbolKind::Net || is_memory(ps) || by_net.contains_key(&(parent, pn.uid()))
        {
            return None;
        }
        let (lo, w) = match sel {
            None => (0, ps.width),
            Some(sel) => vj_codegen::select::constant_window(sel, ps.width).ok()?,
        };
        if w > top {
            return None;
        }
        top -= w;
        for k in 0..w {
            planned.push((
                (child.0, child.1.clone(), top + k),
                (parent, pn.uid(), lo + k),
                Conducts::Always,
                false,
                (None, None),
            ));
        }
        if !bases.contains(&pn.uid()) {
            bases.push(pn.uid());
        }
    }
    (top == 0).then_some((planned, bases))
}

/// A switch terminal: a net of this instance (all its bits) or a constant
/// bit-select of one -- `(net, first bit, bit count)`.
///
/// An element of an unpacked-array net with constant indices over every
/// unpacked dimension (`n[1]`, `n[1][2]`, `n[1][2:3]`; LRM 28.7) is a
/// terminal too: its storage row is the fourth component.
fn switch_terminal(
    e: Expression<'_>,
    own: &HashMap<SymbolId, SignalSlot>,
    rows_of: &RowsOf,
    inst: InstanceId,
) -> Option<(SymbolId, u32, u32, Option<u32>)> {
    let e = if e.kind() == ExpressionKind::Assignment {
        e.left()?
    } else {
        e
    };
    let e = if e.kind() == ExpressionKind::Conversion {
        e.operand()?
    } else {
        e
    };
    if let Some(t) = element_terminal(e, own, rows_of, inst) {
        return Some(t);
    }
    if vj_sim::symid::is_value_name(e.kind()) {
        let s = e.referenced_symbol()?;
        // An unpacked-array net as a whole is a memory and is not switched.
        let slot = own
            .get(&s.uid())
            .filter(|slot| s.kind() == SymbolKind::Net && !is_memory(slot))?;
        return Some((s.uid(), 0, slot.width, None));
    }
    if e.kind() == ExpressionKind::RangeSelect {
        let (s, slot, lo, w) = select_range(e, own)?;
        return (s.kind() == SymbolKind::Net && !is_memory(&slot)).then_some((
            s.uid(),
            lo,
            w,
            None,
        ));
    }
    let (s, slot, bit) = select_bit(e, own)?;
    (s.kind() == SymbolKind::Net && !is_memory(&slot)).then_some((
        s.uid(),
        bit,
        slot.width.min(1),
        None,
    ))
}

/// `e` as an element of an unpacked-array net, or a constant bit- or
/// part-select of one: `n[i]`, `n[i][j]`, `n[i][b]`, `n[i][a:b]` with
/// constant indices over every unpacked dimension (LRM 28.7). `(net, first
/// bit, bit count, storage row)`; `None` for anything else (the caller then
/// falls back to the whole-net forms).
fn element_terminal(
    e: Expression<'_>,
    own: &HashMap<SymbolId, SignalSlot>,
    rows_of: &RowsOf,
    inst: InstanceId,
) -> Option<(SymbolId, u32, u32, Option<u32>)> {
    let constant = |x: Option<Expression<'_>>| {
        x.and_then(|s| s.constant_value())
            .as_ref()
            .and_then(sv_lang::ConstantValue::as_integer)
            .and_then(sv_lang::SVInt::as_i64)
    };
    // The packed select applied to the element, if any.
    let mut elem = e;
    let packed = match e.kind() {
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect => {
            let base = e.select_value()?;
            if base.expr_type().is_some_and(|t| t.is_unpacked_array()) {
                None
            } else {
                elem = base;
                Some(e)
            }
        }
        _ => None,
    };
    // The unpacked indices, outermost last while walking in.
    let mut idx: Vec<i64> = Vec::new();
    let mut cur = elem;
    while cur.kind() == ExpressionKind::ElementSelect {
        let base = cur.select_value()?;
        if !base.expr_type().is_some_and(|t| t.is_unpacked_array()) {
            return None;
        }
        idx.push(constant(cur.selector())?);
        cur = base;
    }
    if idx.is_empty() || !vj_sim::symid::is_value_name(cur.kind()) {
        return None;
    }
    idx.reverse();
    let s = cur.referenced_symbol()?;
    let slot = own.get(&s.uid())?;
    if s.kind() != SymbolKind::Net || !is_memory(slot) {
        return None;
    }
    let rows = rows_of.get(&(inst, s.uid()))?.as_ref()?;
    // A path shorter than the net's unpacked dimensions names a sub-array.
    let (row, _) = rows.iter().find(|(_, i)| *i == idx)?;
    let width = slot.width;
    let Some(sel) = packed else {
        return Some((s.uid(), 0, width, Some(*row)));
    };
    // The element's packed range maps declared indices to storage bits.
    let (left, right) = match elem.expr_type() {
        Some(t) if t.is_integral() => {
            let r = t.bit_vector_range();
            (i64::from(r.left), i64::from(r.right))
        }
        _ => (i64::from(width) - 1, 0),
    };
    let off = |i: i64| if left >= right { i - right } else { right - i };
    let (lo, w) = if sel.kind() == ExpressionKind::ElementSelect {
        (off(constant(sel.selector())?), 1)
    } else {
        vj_codegen::expr::classify_range_selection_kind(sel.range_selection_kind()?)
            .ok()
            .filter(|k| *k == vj_codegen::expr::RangeSelectionKindClass::Simple)?;
        let a = off(constant(sel.range_left())?);
        let b = off(constant(sel.range_right())?);
        (a.min(b), (a - b).abs() + 1)
    };
    (lo >= 0 && lo + w <= i64::from(width)).then_some((s.uid(), lo as u32, w as u32, Some(*row)))
}

/// `e` as a constant simple part-select `net[a:b]` of a signal of this
/// instance: `(signal, slot, lowest storage bit, width)`.
fn select_range<'d>(
    e: Expression<'d>,
    own: &HashMap<SymbolId, SignalSlot>,
) -> Option<(Symbol<'d>, SignalSlot, u32, u32)> {
    let base = e.select_value()?;
    if !vj_sim::symid::is_value_name(base.kind()) {
        return None;
    }
    let s = base.referenced_symbol()?;
    let slot = *own.get(&s.uid())?;
    e.range_selection_kind().filter(|k| {
        vj_codegen::expr::classify_range_selection_kind(*k)
            == Ok(vj_codegen::expr::RangeSelectionKindClass::Simple)
    })?;
    let (rl, rr) = match base.expr_type() {
        Some(t) if t.is_integral() => {
            let r = t.bit_vector_range();
            (i64::from(r.left), i64::from(r.right))
        }
        _ => (i64::from(slot.width) - 1, 0),
    };
    let off = |idx: i64| if rl >= rr { idx - rr } else { rr - idx };
    let a = off(e.range_left()?.constant_value()?.as_i64()?);
    let b = off(e.range_right()?.constant_value()?.as_i64()?);
    let (lo, hi) = (a.min(b), a.max(b));
    (lo >= 0 && hi < i64::from(slot.width)).then_some((s, slot, lo as u32, (hi - lo + 1) as u32))
}

/// The slice of a width-`w` switch terminal that element `pos` of an
/// `n`-element primitive array connects to (LRM 28.3.5, 23.3.3.5): a
/// one-bit terminal reaches every element, a wider one is split into `n`
/// equal parts, the leftmost element taking the leftmost part. `lo` is the
/// terminal's lowest storage bit; `None` when the width fits neither rule.
fn array_slice(lo: u32, w: u32, n: u32, pos: u32) -> Option<(u32, u32)> {
    if n == 1 || w == 1 {
        return Some((lo, w));
    }
    if !w.is_multiple_of(n) {
        return None;
    }
    let k = w / n;
    Some((lo + (n - 1 - pos) * k, k))
}

/// `e` as a constant bit-select of a signal of this instance.
fn select_bit<'d>(
    e: Expression<'d>,
    own: &HashMap<SymbolId, SignalSlot>,
) -> Option<(Symbol<'d>, SignalSlot, u32)> {
    if e.kind() != ExpressionKind::ElementSelect {
        return None;
    }
    let base = e.select_value()?;
    let s = base.referenced_symbol()?;
    let slot = *own.get(&s.uid())?;
    let idx = e.selector()?.constant_value()?.as_i64()?;
    let (left, right) = match base.expr_type() {
        Some(t) if t.is_integral() => {
            let r = t.bit_vector_range();
            (i64::from(r.left), i64::from(r.right))
        }
        _ => (i64::from(slot.width) - 1, 0),
    };
    let off = if left >= right {
        idx - right
    } else {
        right - idx
    };
    (0..i64::from(slot.width))
        .contains(&off)
        .then_some((s, slot, off as u32))
}

/// `(elements, position)` of a primitive instance in its array, position 0
/// being the leftmost element; `(1, 0)` for a lone instance. Only
/// one-dimensional arrays are sliced.
fn switch_array_position(inst: &Symbol<'_>) -> Result<(u32, u32), String> {
    let path: Vec<u32> = inst.instance_array_path().collect();
    match path.as_slice() {
        [] => Ok((1, 0)),
        [pos] => {
            let n = inst
                .parent()
                .map_or(1, |p| p.instance_array_elements().count() as u32);
            Ok((n, *pos))
        }
        _ => Err("a multi-dimensional array of switches (LRM 28.3.5) is not supported".into()),
    }
}

/// A switch control terminal: a signal (its bit 0), a constant bit-select
/// of one, or a constant.
fn control_terminal(
    e: Expression<'_>,
    id: InstanceId,
    own: &HashMap<SymbolId, SignalSlot>,
    (arr_n, arr_pos): (u32, u32),
) -> Option<Control> {
    if let Some(c) = e.constant_value() {
        return Some(Control::Const(match c.as_i64() {
            Some(v) => (v & 1) as u8,
            None => 2,
        }));
    }
    let e = if e.kind() == ExpressionKind::Conversion {
        e.operand()?
    } else {
        e
    };
    // slang slices a control wider than one bit per element itself, with
    // `ctl[path]` -- the leftmost element on bit 0 -- where LRM 28.3.5 puts
    // the terminal's LSB on the element at the array range's RIGHT-hand
    // index. Such a synthesised select spans exactly its base's source
    // (a written `en[1]` spans more): undo it and slice the whole terminal.
    let e = match e.select_value() {
        Some(base)
            if arr_n > 1
                && e.kind() == ExpressionKind::ElementSelect
                && e.source_range() == base.source_range() =>
        {
            base
        }
        _ => e,
    };
    if vj_sim::symid::is_value_name(e.kind()) {
        let s = e.referenced_symbol()?;
        let slot = *own.get(&s.uid())?;
        let (lo, _) = array_slice(0, slot.width, arr_n, arr_pos)?;
        return Some(Control::Bit(id, slot, lo));
    }
    if e.kind() == ExpressionKind::RangeSelect {
        let (_, slot, lo, w) = select_range(e, own)?;
        let (lo, _) = array_slice(lo, w, arr_n, arr_pos)?;
        return Some(Control::Bit(id, slot, lo));
    }
    let (_, slot, bit) = select_bit(e, own)?;
    Some(Control::Bit(id, slot, bit))
}

#[cfg(test)]
mod tests {
    use sv_lang::{Compilation, Session};

    use super::{DriverKey, ElemPath, Resolution, paths_overlap};
    use vj_sim::netlist::InstanceId;
    use vj_sim::symid::SymbolUid;

    /// Two drivers of an unpacked-array net clash only when one element path
    /// is a prefix of the other (the same element, or a whole row against one
    /// of its sub-elements); sibling elements never do.
    #[test]
    fn element_paths_overlap_only_on_a_shared_prefix() {
        let p = |idx: &[i64], bits: Option<(i64, i64)>| ElemPath {
            idx: idx.to_vec(),
            bits,
        };
        assert!(paths_overlap(&p(&[1], None), &p(&[1], None)));
        assert!(paths_overlap(&p(&[1], None), &p(&[1, 0], None)));
        assert!(paths_overlap(&p(&[], None), &p(&[2, 3], None)));
        assert!(!paths_overlap(&p(&[0], None), &p(&[1], None)));
        assert!(!paths_overlap(&p(&[1, 0], None), &p(&[1, 1], None)));
        // Bits of one element: disjoint slices do not overlap.
        assert!(!paths_overlap(
            &p(&[1], Some((0, 1))),
            &p(&[1], Some((2, 5)))
        ));
        assert!(paths_overlap(
            &p(&[1], Some((0, 2))),
            &p(&[1], Some((2, 5)))
        ));
        assert!(paths_overlap(&p(&[1], Some((0, 1))), &p(&[1], None)));
        assert!(!paths_overlap(
            &p(&[0], Some((0, 1))),
            &p(&[1], Some((0, 1)))
        ));
    }

    /// Task 4a's own "unit test for `DriverKey::SpecifyPath` resolution":
    /// it round-trips through [`Resolution::slot`] exactly like
    /// [`DriverKey::Prim`] already does (a module path's own retimer, once
    /// a future task actually populates this entry, is looked up the SAME
    /// way a primitive's output terminal is), and two keys differing only
    /// by `InstanceId` are distinct entries, never aliased.
    #[test]
    fn specify_path_driver_key_round_trips_through_resolution_contrib() {
        let session = Session::new();
        let mut comp = Compilation::new(&session).expect("compilation created");
        comp.add_source("module m(input a, output q);\n  assign q = a;\nendmodule\n")
            .expect("source added");
        let design = comp.compile().expect("design compiled");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("top instance has a body");
        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("net q")
            .uid();

        let mut res = Resolution::default();
        res.bank_widths.push(1);
        let key = DriverKey::SpecifyPath(InstanceId(0), q_uid.clone());
        res.contrib.insert(key.clone(), 0);

        assert_eq!(res.slot(&key), Some(0));
        assert_eq!(
            res.slot(&DriverKey::SpecifyPath(InstanceId(1), q_uid)),
            None,
            "a different instance's otherwise-identical key is a distinct entry"
        );
    }
}