vj-sim 0.3.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
Documentation
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
//! Task 4 — layout-builder entry point, API surface discipline, member
//! filtering, exclusions (ledger ST-058, ST-060, ST-072, ST-125, ST-126).
//!
//! `build_template_layout` is the sole frontend entry point STATE's layout
//! builder exposes this wave (ST-125): it takes a `Symbol` already obtained
//! from `Compilation::compile() -> Design` by the caller (Task 5 wires the
//! `top_instances()` walk that calls this once per distinct template) and
//! never itself touches `Compilation`/`Session`. Its top-level per-member
//! walk calls `members`/`kind`/`value_type`/`initializer` on
//! `sv_lang::Symbol` (ST-126's hierarchy-walking API surface), plus
//! `port_type()`, `port_internal_symbol()`, and `port_is_null_port()` for
//! `Port`-kind members specifically (a deviation from the plan's literal
//! call list -- see the doc comment on `ty` below: a real ANSI `Port`
//! symbol's `value_type()` is `None`, so `value_type()` alone cannot
//! satisfy ST-060's "produces slots ... for the ... port" requirement),
//! filtering to `Variable`/`Net`/`Port` member kinds (ST-060); every other
//! kind (`Genvar`, `Parameter`, `TypeParameter`, `Subroutine`, ...) is
//! excluded by that filter alone, with no separate exclusion code path
//! (ST-072). Two further, narrower exclusions apply only within the
//! `Port`-kind slice of that filter, both because a value the filter would
//! otherwise accept carries no independent storage of its own: a port with
//! an internal symbol (already slotted on its own pass through this same
//! loop -- see the doc comment above the first `continue` below), and a
//! null port (an empty, dot-less port-list position -- ST-072's "not a
//! signal" reasoning applied to a `Port`-kind member that itself has
//! nothing to store; see the doc comment above the second `continue`
//! below). `SymbolKind` is `#[non_exhaustive]` in the pinned `sv-lang`, so
//! a filter (never a from-scratch exhaustive match) is the only way this
//! crate could even attempt to enumerate it.
//!
//! Per-member shape derivation beyond a single inline word sized by
//! `Type::bit_width()` (packed-struct flattening is already implied by
//! `bit_width()` returning the flattened width, but memory/wide routing,
//! dynamic-array rejection, sign-aware width proofs, and initial-value
//! threading) is Task 6's job, which edits this same function body in place
//! -- this task's own implementation is a deliberate stub: every slot it
//! emits is `SlotClass::Inline`, `initial: None`, `net_info: None`.

use super::arena::{Arena, BuildMode};
use super::{
    FourStateValue, NetLayout, SlotClass, SlotDescriptor, SlotOffset, StateLayout,
    four_state_of_constant, four_state_to_owned_svint, owned_svint_to_four_state,
};
use crate::netlist::SymbolKey;
use crate::symid::SymbolUid;
use sv_lang::kinds::SymbolKind;
use sv_lang::nodes::{
    CheckerDeclarationSyntax, ClockingDeclarationSyntax, DefaultClockingReferenceSyntax,
    DefaultDisableDeclarationSyntax, GenerateBlockSyntax, MemberSyntax, ModuleDeclarationSyntax,
};
use sv_lang::{AstNode, Node, Symbol, SyntaxTree};

/// The loud, typed error this and every later layout task returns instead of
/// silently skipping a member kind this plan claims to handle (ARCHITECTURE
/// §7 item 9 applied to `SymbolKind`).
///
/// **Deviation from the plan's literal `sym.` call-site restriction:** the
/// plan's Task 4 prose says `build_template_layout` touches no `Symbol`
/// method outside `{members, kind, value_type, initializer}`, but this
/// variant's own field is documented as "a hierarchical-ish name for
/// diagnosis", and ST-126's own ledger text lists `Symbol::name()` as part
/// of STATE's allowed hierarchy-walking API surface. `name()` is called only
/// on this (in practice unreachable this wave, since a real `Variable`/
/// `Net`/`Port` symbol always yields a `value_type()`) diagnostic path, never
/// on the per-member happy path.
#[derive(Debug)]
pub enum LayoutError {
    /// A member this builder's kind-filter *does* accept (`Variable`/`Net`/
    /// `Port`) but that itself failed to yield a queryable value -- e.g.
    /// `Symbol::value_type()` returning `None` for a symbol the filter
    /// otherwise believed was a value. Carries the offending kind and a
    /// hierarchical-ish name for diagnosis. Never constructed for a kind the
    /// filter excludes on purpose (ST-072's exclusion is not an error).
    UnsupportedMemberKind(SymbolKind, String),
    /// Task 6: a member whose `value_type()`/`port_type()` shape this builder
    /// cannot yet lay out -- a dynamic array, queue, or associative array
    /// (rejected by the explicit `Type::is_dynamically_sized_array()`
    /// predicate check, never inferred from another predicate being false);
    /// a class handle, `string`, `chandle`, `event`, virtual interface, a
    /// multi-dimensional fixed unpacked array (whose per-row element is
    /// itself another unpacked array), or a `real`/`shortreal`/`realtime`
    /// (review fix r1 rejected the first three via `bit_width() == 0`;
    /// review fix r3 replaced that with the more general `!is_integral()`
    /// gate -- `real`/`shortreal`/`realtime` have a NONZERO `bit_width()`
    /// (64/32/64, per `Type::getBitWidth`) despite having no floating-point
    /// representation implemented this wave, so the old zero-width test
    /// alone let them fall through into ordinary 4-state slot machinery
    /// with a silently dropped initializer; `is_integral()` is false for
    /// every one of these shapes and true for everything this wave does
    /// support, so one gate now gets both); or an otherwise-supported
    /// integral member whose bit width does not fit `u16` (review fix r3:
    /// previously silently clamped to `u16::MAX` instead of rejected, which
    /// for a Wide scalar also undersized the arena allocation itself, since
    /// `word_count` was derived from the clamped value). Carries a
    /// hierarchical-ish name for diagnosis. A loud `Err`, never a guessed
    /// slot or a panic reading a nonexistent fixed bound.
    UnsupportedType(String),
    /// A checker output formal whose initial value (`output int ctr = x;`,
    /// LRM 17.2) is not a constant: it is evaluated in the instantiation's
    /// context, and only a constant one is lowered -- rejected rather than
    /// left at the type's default.
    NonConstantCheckerOutputInitial(String),
}

/// Converts a real bit-width `u64` into the `u16` a [`SlotOffset`] field
/// requires, returning `Err(LayoutError::UnsupportedType)` instead of
/// silently clamping to `u16::MAX` when the value doesn't fit -- review fix
/// r3: `u16::try_from(x).unwrap_or(u16::MAX)` used to clamp here, which for
/// a real too-wide member (a legal SV construct, e.g. `logic [200000:0]
/// huge;`) both misreports the metadata a later consumer masks against
/// (state.md §3's `mask(bit_width)`) and, for a Wide scalar whose
/// `word_count` this function's caller derives from the same width,
/// would undersize the arena allocation itself relative to the member's
/// true width -- exactly the "guessed slot" `LayoutError::UnsupportedType`'s
/// own doc comment says must never happen.
fn checked_bit_width(bit_width: u64, member_name: &str) -> Result<u32, LayoutError> {
    u32::try_from(bit_width).map_err(|_| LayoutError::UnsupportedType(member_name.to_string()))
}

/// Walks `body.members()` and builds a [`StateLayout`] for one template
/// (ST-058: a read-only walk over the frozen `Design`, deterministic on
/// repeat calls -- no internal counter/cache outlives this call; ST-125: the
/// sole frontend entry point, taking an already-obtained `Symbol` rather
/// than a `Compilation`/`Session`).
/// A memory's declared initializer as its every row's value: a
/// `FourStateValue::Wide` whose planes are the rows' `words_per_row`-word
/// (aval, bval) values concatenated, lowest row first (the row order
/// `rollback::reset_to_initial` writes them in). The initializer must fold
/// to a constant (`'{1, 2, 3}`, `'{default: 0}`, a parameter, ...): a
/// module-level array initializer that reads another signal is rejected
/// rather than dropped.
fn memory_initial_rows(
    member: &Symbol,
    init: &sv_lang::Expression,
    ty: &sv_lang::Type,
    words_per_row: usize,
) -> Result<FourStateValue, LayoutError> {
    let unsupported = || LayoutError::UnsupportedType(member.name().to_string());
    // An array of virtual interfaces (LRM 1800-2023 25.9) starts from
    // interface instances and `null`, which are not constants: resolve
    // each pattern leaf to its instance id (`netlist::vif`).
    if ty.is_unpacked_array() && vif_array_elem(ty).is_some() {
        let mut ids = Vec::new();
        vif_pattern_rows(init, ty, &mut ids).ok_or_else(unsupported)?;
        let mut aval = Vec::new();
        for id in ids {
            aval.push(id);
            aval.resize(aval.len() + words_per_row - 1, 0);
        }
        let bval = vec![0; aval.len()];
        return Ok(FourStateValue::Wide { aval, bval });
    }
    let cv = init.constant_value().ok_or_else(unsupported)?;
    let mut aval = Vec::new();
    let mut bval = Vec::new();
    push_rows(&cv, ty, words_per_row, &mut aval, &mut bval).ok_or_else(unsupported)?;
    Ok(FourStateValue::Wide { aval, bval })
}

/// The virtual-interface or class-handle element type (a class array pattern takes only `null` leaves) of a fixed unpacked array (through
/// every dimension), `None` for any other array.
fn vif_array_elem<'d>(ty: &sv_lang::Type<'d>) -> Option<sv_lang::Type<'d>> {
    let mut t = *ty;
    while t.is_unpacked_array() && !super::storage::is_collection(&t) {
        t = t.element_type()?;
    }
    (t.is_virtual_interface() || t.is_class()).then_some(t)
}

/// Appends the instance id of every element of the array pattern `e` of
/// (array) type `ty`, lowest index first: an interface instance names its
/// id, `null` is 0, and a pattern nests per dimension.
fn vif_pattern_rows(
    e: &sv_lang::Expression<'_>,
    ty: &sv_lang::Type<'_>,
    out: &mut Vec<u64>,
) -> Option<()> {
    use sv_lang_kinds::ExpressionKind;
    let mut e = *e;
    while e.kind() == ExpressionKind::Conversion {
        e = e.conversion_operand()?;
    }
    if ty.is_unpacked_array() && !super::storage::is_collection(ty) {
        let range = ty.fixed_unpacked_array_range();
        let elem_ty = ty.element_type()?;
        // Any other initializer is rejected by name by the caller.
        let k = e.kind();
        let elems = if matches!(
            k,
            ExpressionKind::SimpleAssignmentPattern | ExpressionKind::StructuredAssignmentPattern
        ) {
            e.pattern_elements()
        } else if k == ExpressionKind::ReplicatedAssignmentPattern {
            let n = e.replicated_pattern_count()?.constant_value()?.as_i64()?;
            let one = e.pattern_elements();
            (0..n).flat_map(|_| one.iter().copied()).collect()
        } else {
            return None;
        };
        if elems.len() as u64 != u64::from(range.width()) {
            return None;
        }
        // Elements run left bound to right bound; rows are stored lowest
        // index first.
        let mut rows = Vec::new();
        for el in &elems {
            let mut r = Vec::new();
            vif_pattern_rows(el, &elem_ty, &mut r)?;
            rows.push(r);
        }
        if range.left > range.right {
            rows.reverse();
        }
        out.extend(rows.into_iter().flatten());
        return Some(());
    }
    out.push(vif_leaf(&e)?);
    Some(())
}

/// Appends the rows of the constant `cv` of (array) type `ty` to the planes;
/// `None` for a value this layout cannot store.
fn push_rows(
    cv: &sv_lang::ConstantValue,
    ty: &sv_lang::Type,
    words: usize,
    aval: &mut Vec<u64>,
    bval: &mut Vec<u64>,
) -> Option<()> {
    if ty.is_unpacked_array() {
        let elems = cv.as_array()?;
        let range = ty.fixed_unpacked_array_range();
        let elem_ty = ty.element_type()?;
        if elems.len() as u64 != u64::from(range.width()) {
            return None;
        }
        // Constant elements run left bound to right bound; rows are stored
        // lowest index first.
        if range.left > range.right {
            for e in elems.iter().rev() {
                push_rows(e, &elem_ty, words, aval, bval)?;
            }
        } else {
            for e in elems {
                push_rows(e, &elem_ty, words, aval, bval)?;
            }
        }
        return Some(());
    }
    if super::storage::is_unpacked_aggregate(ty) {
        let (mut a, mut b) =
            super::value::bits_to_aval_bval(&super::storage::constant_bits(cv, ty)?);
        a.resize(words, 0);
        b.resize(words, 0);
        aval.extend(a);
        bval.extend(b);
        return Some(());
    }
    let (mut a, mut b) = match cv {
        sv_lang::ConstantValue::Integer(i) => {
            super::value::bits_to_aval_bval(&super::value::svint_bits(i)?)
        }
        sv_lang::ConstantValue::Real(f) if ty.bit_width() == 32 => {
            (vec![u64::from((*f as f32).to_bits())], vec![0])
        }
        sv_lang::ConstantValue::Real(f) => (vec![f.to_bits()], vec![0]),
        sv_lang::ConstantValue::String(s) if ty.is_string() => {
            (vec![crate::strings::intern(s.as_bytes())], vec![0])
        }
        _ => return None,
    };
    a.resize(words, 0);
    b.resize(words, 0);
    aval.extend(a);
    bval.extend(b);
    Some(())
}

/// A queue or dynamic array's constant initializer (`int q[$] = {1, 2}`)
/// as a frozen collection handle (`crate::collections::frozen_from_words`),
/// every instance sharing it until its first change; an empty associative
/// array literal is the empty handle.
fn collection_initial(
    member: &Symbol,
    init: &sv_lang::Expression,
    ty: &sv_lang::Type,
) -> Result<u64, LayoutError> {
    let unsupported = || LayoutError::UnsupportedType(member.name().to_string());
    if ty.element_type().is_some_and(|e| e.is_virtual_interface()) {
        return vif_collection_initial(init, ty).ok_or_else(unsupported);
    }
    let cv = init.constant_value().ok_or_else(unsupported)?;
    let elem_ty = ty.element_type().ok_or_else(unsupported)?;
    let width = super::storage::storage_width(&elem_ty).ok_or_else(unsupported)?;
    let elem_words = (2 * width).div_ceil(64).max(1) as usize;
    let elem_words_of = |e: &sv_lang::ConstantValue| -> Result<Vec<u64>, LayoutError> {
        let mut w = super::value::packed_words(
            &super::storage::constant_bits(e, &elem_ty).ok_or_else(unsupported)?,
        );
        w.resize(elem_words, 0);
        Ok(w)
    };
    if ty.is_associative_array() {
        let mut pattern_probe = *init;
        while pattern_probe.kind() == sv_lang::kinds::ExpressionKind::Conversion {
            pattern_probe = pattern_probe.operand().ok_or_else(unsupported)?;
        }
        if matches!(cv, sv_lang::ConstantValue::Map(_, true))
            && pattern_probe.structured_pattern_default_setter().is_none()
        {
            return Ok(0);
        }
        // `'{key: value, ...}`: the pattern's index setters (the constant
        // value does not list its entries). A `default:` is not kept.
        let mut pattern = *init;
        while pattern.kind() == sv_lang::kinds::ExpressionKind::Conversion {
            pattern = pattern.operand().ok_or_else(unsupported)?;
        }
        let key_ty = ty.associative_index_type().ok_or_else(unsupported)?;
        let shape = crate::collections::Shape {
            elem_words,
            assoc: true,
            key: if key_ty.is_string() {
                crate::collections::KeyKind::Str
            } else {
                crate::collections::KeyKind::Int {
                    width: key_ty.bit_width() as u32,
                    signed: key_ty.is_signed(),
                }
            },
            obj: false,
            nested: crate::collections::Nested::NONE,
        };
        let mut entries = Vec::new();
        for setter in pattern.structured_pattern_index_setters() {
            let kcv = setter.index().constant_value().ok_or_else(unsupported)?;
            let vcv = setter.expr().constant_value().ok_or_else(unsupported)?;
            let kbits = super::storage::constant_bits(&kcv, &key_ty).ok_or_else(unsupported)?;
            let key = shape
                .key_from_bits(&super::value::packed_words(&kbits))
                .ok_or_else(unsupported)?;
            entries.push((key, elem_words_of(&vcv)?));
        }
        let default = match pattern.structured_pattern_default_setter() {
            // A bare string literal as the `default:` setter keeps its
            // integral type (no implicit conversion, unlike the index
            // setters), so a `string` element takes its text directly.
            Some(d)
                if elem_ty.is_string()
                    && d.kind() == sv_lang::kinds::ExpressionKind::StringLiteral =>
            {
                let text = d.string_literal_value().ok_or_else(unsupported)?;
                Some(elem_words_of(&sv_lang::ConstantValue::String(text))?)
            }
            Some(d) => Some(elem_words_of(&d.constant_value().ok_or_else(unsupported)?)?),
            None => None,
        };
        return Ok(crate::collections::frozen_map(entries, default));
    }
    let mut words = Vec::new();
    for e in cv.as_array().ok_or_else(unsupported)? {
        words.extend(elem_words_of(e)?);
    }
    if words.is_empty() {
        return Ok(0);
    }
    Ok(crate::collections::frozen_from_words(elem_words, &words))
}

/// A queue, dynamic array or associative array of virtual interfaces
/// (LRM 1800-2023 25.9) initialized from instances and `null`
/// (`virtual SBus q[$] = '{s0, s1}`): each element is a 64-bit instance id
/// (`netlist::vif`), stored as one 2-state element of two words.
fn vif_collection_initial(init: &sv_lang::Expression, ty: &sv_lang::Type) -> Option<u64> {
    use sv_lang_kinds::ExpressionKind;
    let mut pattern = *init;
    while pattern.kind() == ExpressionKind::Conversion {
        pattern = pattern.conversion_operand()?;
    }
    if ty.is_associative_array() {
        let key_ty = ty.associative_index_type()?;
        let shape = crate::collections::Shape {
            elem_words: 2,
            assoc: true,
            key: if key_ty.is_string() {
                crate::collections::KeyKind::Str
            } else {
                crate::collections::KeyKind::Int {
                    width: key_ty.bit_width() as u32,
                    signed: key_ty.is_signed(),
                }
            },
            obj: false,
            nested: crate::collections::Nested::NONE,
        };
        if pattern.kind() != ExpressionKind::StructuredAssignmentPattern {
            return None;
        }
        let mut entries = Vec::new();
        for setter in pattern.structured_pattern_index_setters() {
            let kcv = setter.index().constant_value()?;
            let kbits = super::storage::constant_bits(&kcv, &key_ty)?;
            let key = shape.key_from_bits(&super::value::packed_words(&kbits))?;
            entries.push((key, vec![vif_leaf(&setter.expr())?, 0]));
        }
        let default = match pattern.structured_pattern_default_setter() {
            Some(d) => Some(vec![vif_leaf(&d)?, 0]),
            None => None,
        };
        return Some(crate::collections::frozen_map(entries, default));
    }
    // Any other initializer is rejected by name by the caller.
    let k = pattern.kind();
    let elems = if matches!(
        k,
        ExpressionKind::SimpleAssignmentPattern | ExpressionKind::StructuredAssignmentPattern
    ) {
        pattern.pattern_elements()
    } else if k == ExpressionKind::Concatenation {
        pattern.operands()
    } else if k == ExpressionKind::ReplicatedAssignmentPattern {
        let n = pattern
            .replicated_pattern_count()?
            .constant_value()?
            .as_i64()?;
        let one = pattern.pattern_elements();
        (0..n).flat_map(|_| one.iter().copied()).collect()
    } else {
        return None;
    };
    let mut words = Vec::new();
    for el in &elems {
        words.push(vif_leaf(el)?);
        words.push(0);
    }
    if words.is_empty() {
        return Some(0);
    }
    Some(crate::collections::frozen_from_words(2, &words))
}

/// The id a virtual-interface-typed initializer leaf names: `null` is 0, an
/// interface instance its [`netlist::vif::instance_id`].
fn vif_leaf(e: &sv_lang::Expression<'_>) -> Option<u64> {
    use sv_lang_kinds::ExpressionKind;
    let mut e = *e;
    while e.kind() == ExpressionKind::Conversion {
        e = e.conversion_operand()?;
    }
    // Any other leaf is not an initializer a virtual interface array takes:
    // the caller rejects the declaration by name.
    if e.kind() == ExpressionKind::NullLiteral {
        Some(0)
    } else if e.kind() == ExpressionKind::ArbitrarySymbol {
        super::super::netlist::vif::instance_id(&e.referenced_symbol()?)
    } else {
        None
    }
}

/// A layout of one slot per entry of `widths` holding no declared signal --
/// the contribution cells of resolved nets' drivers (`vj`'s
/// `nets`): each Inline or Wide by width, starting all-`z` (not driving).
pub fn synthetic_z_layout(widths: &[u32]) -> StateLayout {
    synthetic_z_layout_rows(widths, &[], &[])
}

/// [`synthetic_z_layout`] where cell `k` with `rows[k] > 0` is a `Memory`
/// slot of that many rows of `widths[k]` bits, every row all-`z`: the
/// contribution cell of a driver of an unpacked array of nets, whose elements
/// are resolved one by one (`vj`'s `nets`). A row starts at
/// `fills[k]` (LSB first) when that is non-empty, else all-`z`: a user
/// nettype's driver has no `z` (its data type's default value instead); a
/// non-memory cell with a non-empty `fills[k]` starts at it too (a specify
/// path's staging cell starts `x`, LRM 30.5.1).
pub fn synthetic_z_layout_rows(
    widths: &[u32],
    rows: &[u32],
    fills: &[Vec<sv_lang::Bit>],
) -> StateLayout {
    let arena = Arena::new(BuildMode::FourState);
    let mut slots = Vec::with_capacity(widths.len());
    for (k, &w) in widths.iter().enumerate() {
        let w = w.clamp(1, u32::MAX);
        let words = w.div_ceil(64);
        let num_rows = rows.get(k).copied().unwrap_or(0);
        if num_rows > 0 {
            let total = words * num_rows;
            // SAFETY: `arena` is local and single-owned; sequential calls only.
            let offset = unsafe { arena.alloc_wide_words(total) };
            let fill = match fills.get(k) {
                Some(f) if !f.is_empty() => f.clone(),
                _ => vec![sv_lang::Bit::Z; w as usize],
            };
            let (a, b) = super::value::bits_to_aval_bval(&fill);
            slots.push(SlotDescriptor {
                key: SymbolKey(k as u32),
                offset: SlotOffset {
                    class: SlotClass::Memory,
                    word_offset: offset,
                    bit_width: w,
                    elem_word_count: words,
                    row_stride_words: words,
                    num_rows,
                },
                initial: Some(FourStateValue::Wide {
                    aval: a.repeat(num_rows as usize),
                    bval: b.repeat(num_rows as usize),
                }),
                net_info: None,
            });
            continue;
        }
        // SAFETY: `arena` is local and single-owned; sequential calls only.
        let (class, offset) = if words <= 1 {
            (SlotClass::Inline, unsafe { arena.alloc_inline_word() })
        } else {
            (SlotClass::Wide, unsafe { arena.alloc_wide_words(words) })
        };
        slots.push(SlotDescriptor {
            key: SymbolKey(k as u32),
            offset: SlotOffset {
                class,
                word_offset: offset,
                bit_width: w,
                elem_word_count: words,
                row_stride_words: 0,
                num_rows: 0,
            },
            initial: Some(match fills.get(k) {
                Some(f) if !f.is_empty() => super::value::bits_to_four_state(f),
                _ => super::value::bits_to_four_state(&vec![sv_lang::Bit::Z; w as usize]),
            }),
            net_info: None,
        });
    }
    StateLayout {
        inline_words: arena.inline().len() as u32,
        wide_words: arena.wide_aval().len() as u32,
        slots,
    }
}

/// `body`'s clocking blocks, each with its input (and inout) clock
/// variables, in declaration order -- the extra slots of a template, in the
/// order both the layout and the codegen signal map give them.
pub fn clocking_blocks<'d>(body: &Symbol<'d>) -> Vec<(Symbol<'d>, Vec<Symbol<'d>>)> {
    crate::netlist::module_items(body)
        .into_iter()
        .filter(|m| m.kind() == SymbolKind::ClockingBlock)
        .map(|cb| {
            let vars = cb
                .members()
                .filter(|v| {
                    v.kind() == SymbolKind::ClockVar
                        && matches!(
                            v.clock_var_direction(),
                            sv_lang::ArgumentDirection::In | sv_lang::ArgumentDirection::InOut
                        )
                })
                .collect();
            (cb, vars)
        })
        .collect()
}

/// Task 8 (sva T8, `docs/superpowers/plans/2026-10-03-sva.md`): LRM
/// 1800-2023 14.12's `default clocking` and 16.15's `default disable iff`
/// -- the *scoping* half only (which single declaration, if any, covers a
/// given scope): resolving the lexical-nesting/override rules both clauses
/// state almost verbatim ("valid only within the scope containing the
/// declaration ... as well as any nested module[s] ... It does not include
/// instantiated modules" -- 14.12; "provides a default ... to all
/// concurrent assertions in the scope and subscopes ... the default
/// extends to any nested module ... However, if a nested module ... has a
/// [its own] declaration, then that ... overrides any default ... from
/// outside" -- 16.15). The *resolution*-rule half of 16.15 (composing this
/// against an assertion's own explicit `disable iff` clause, rules
/// (a)/(b)/(c)) is T27's job, consuming [`default_disable_of`]'s result --
/// not reimplemented here.
///
/// ## Why a syntax walk, not a `sv-lang` semantic accessor
///
/// The vendored C++ slang already has exactly this query
/// (`slang::ast::Compilation::getDefaultClocking`/`getDefaultDisable`,
/// `include/slang/ast/Compilation.h`) -- but, unlike 16.13.3/16.16's clock
/// flow (T7) or 16.14.6's procedural clock inference (T6), `sv-lang` 0.1.9
/// exposes no FFI binding to either one at all (confirmed by grepping the
/// installed crate's own generated `ast.rs`/`sys` surface for
/// `default_clocking`/`default_disable` and finding nothing -- not
/// assumed). Per the same plan-wide posture T6/T7 already apply ("wrap
/// what's exposed, reimplement only what genuinely is not"), this task
/// reconstructs 14.12/16.15 directly from the syntax tree, exactly as the
/// plan's own Task 8 "Files"/"Steps" text asks: walking
/// `module_or_generate_item_declaration`'s `default clocking
/// clocking_identifier ;`/inline `[default] clocking ... endclocking`/
/// `default disable iff expr ;` forms (`DefaultClockingReferenceSyntax`/
/// `ClockingDeclarationSyntax`/`DefaultDisableDeclarationSyntax`).
///
/// ## Lexical nesting via `Symbol::parent()`, confirmed live
///
/// 14.12/16.15's "nested declaration inherits; mere instantiation does
/// not" distinction sounds like it needs a second, syntax-ancestry walk
/// independent of the elaborated instance tree -- but `sv_lang::Symbol::
/// parent()` (`slang_symbol_parent_scope`) turns out to already encode
/// exactly that distinction, confirmed live against both shapes before
/// writing this function (not assumed from the plan's prose): for a module
/// `m2` declared as a *nested* declaration textually inside `m1` and
/// instantiated there, `m2`'s elaborated `InstanceBody::parent()` is `m1`'s
/// own `InstanceBody`; for the identical textual declaration of `m2`
/// hoisted to the top level and merely *instantiated* inside `m1`, `m2`'s
/// `InstanceBody::parent()` is the design's `CompilationUnit` root --
/// never `m1` -- even though `m2` is instantiated in exactly the same
/// place in both cases. I.e. `parent()` already walks the *lexical*
/// declaration-site scope chain, not the elaborated instantiation
/// hierarchy, which is exactly what both clauses need told apart. The same
/// holds for a `GenerateBlock` symbol (its `parent()` is its lexically
/// enclosing module/generate scope). So [`each_lexical_scope`] below climbs
/// `Symbol::parent()` alone, never a second, independent `Node::parent()`
/// syntax-ancestry walk.
#[derive(Debug)]
pub enum DefaultScopeError {
    /// 14.12: "Specifying a default clocking more than once in the same
    /// module, interface, program, or checker shall result in a compiler
    /// error." Carries the offending scope's name.
    DuplicateDefaultClocking(String),
    /// 16.15: "More than one default disable iff declaration within the
    /// same module, interface, program declaration, or generate block
    /// shall be an error." Carries the offending scope's name.
    DuplicateDefaultDisable(String),
    /// A `default clocking clocking_identifier;` reference whose name does
    /// not resolve to any member of the scope it was declared in.
    /// Defensive -- 14.12's own "clocking_identifier shall be the name of a
    /// clocking block" is a semantic rule slang itself already enforces on
    /// a fatal-error-free `Design`, so this should be unreachable, but a
    /// loud named error is still required over a silent `None`/panic.
    UnresolvedDefaultClockingTarget(String),
    /// As above, but the name resolved to a real member that is not itself
    /// a clocking block.
    DefaultClockingTargetNotAClockingBlock(String),
}

/// The direct item list of one lexical, scope-introducing syntax node --
/// `None` for every other node kind, in which case [`each_lexical_scope`]
/// moves on to that `Symbol`'s own lexical parent instead of searching
/// here. 14.12/16.15's own grammar (`module_or_generate_item_declaration`/
/// `checker_or_generate_item_declaration`) only ever places a default
/// declaration directly inside one of these three container shapes --
/// never inside e.g. a bare `generate`/`endgenerate` region or an
/// `if`/`case`/`for` generate construct's own wrapper node, neither of
/// which carries an item list of its own (the region keyword pair has no
/// semantic effect on scoping at all; a conditional generate construct's
/// *branch* is what carries one, as a `GenerateBlockSyntax`, already
/// handled below) -- so this function is transparent to those by
/// construction, not by an omitted case.
fn items_of<'t>(node: Node<'t>) -> Option<Vec<MemberSyntax<'t>>> {
    if let Some(m) = ModuleDeclarationSyntax::cast(node) {
        return Some(m.members().into_iter().collect());
    }
    if let Some(c) = CheckerDeclarationSyntax::cast(node) {
        return Some(c.members().into_iter().collect());
    }
    if let Some(g) = GenerateBlockSyntax::cast(node) {
        return Some(g.members().into_iter().collect());
    }
    None
}

/// Climbs `scope`'s lexical scope chain (`scope` itself, then
/// `scope.parent()`, then *its* parent, ...), yielding `(scope_symbol,
/// its_own_direct_item_list)` for each ancestor that is itself a
/// scope-introducing declaration ([`items_of`] returns `Some`) -- silently
/// skipping (not erroring on) every ancestor that is not one, per
/// [`items_of`]'s own doc comment. Ends when the chain runs out
/// (`Symbol::parent()` returns `None`), yielding nothing further -- the
/// caller's own "found nothing in the whole chain" `Ok(None)` case (16.15
/// rule (c)/14.12's "otherwise no default clocking applies").
fn each_lexical_scope<'d, 't>(
    scope: Symbol<'d>,
    tree: &'t SyntaxTree,
) -> impl Iterator<Item = (Symbol<'d>, Vec<MemberSyntax<'t>>)> {
    let mut cur = Some(scope);
    std::iter::from_fn(move || {
        while let Some(s) = cur.take() {
            cur = s.parent();
            if let Some(items) = s.syntax(tree).and_then(items_of) {
                return Some((s, items));
            }
        }
        None
    })
}

/// Resolves `name` via ordinary (non-hierarchical) scoped lookup, climbing
/// `scope`'s own lexical parent chain (`Symbol::parent()`) when `name` is
/// not among `scope`'s own direct members. `Symbol::find` itself only ever
/// searches `scope`'s own members (`slang::ast::Scope::find`, a direct,
/// non-recursive lookup -- confirmed live, not assumed: 14.12 Example 2's
/// own `cpu`/`busA` shape -- a *nested* module's `default clocking busA;`
/// reference naming a clocking block declared in its *enclosing* module,
/// not its own -- fails `decl_scope.find("busA")` directly, and this
/// climbing wrapper is what actually resolves it, matching ordinary SV
/// unqualified-name resolution).
fn find_in_lexical_scope<'d>(scope: Symbol<'d>, name: &str) -> Option<Symbol<'d>> {
    let mut cur = Some(scope);
    while let Some(s) = cur {
        if let Some(found) = s.find(name) {
            return Some(found);
        }
        cur = s.parent();
    }
    None
}

/// LRM 14.12's resolved default clocking block for `scope`: the nearest
/// enclosing scope's `default clocking clocking_identifier;` reference or
/// inline `[default] clocking ... endclocking` declaration, as an actual
/// `ClockingBlock` [`Symbol`] -- `None` if no scope in the chain declares
/// one.
pub fn default_clocking_of<'d>(
    scope: &Symbol<'d>,
    tree: &SyntaxTree,
) -> Result<Option<Symbol<'d>>, DefaultScopeError> {
    for (decl_scope, items) in each_lexical_scope(*scope, tree) {
        let mut via_ref: Option<DefaultClockingReferenceSyntax> = None;
        let mut via_inline: Option<ClockingDeclarationSyntax> = None;
        let mut count = 0usize;
        for item in &items {
            match item {
                MemberSyntax::DefaultClockingReference(n) => {
                    count += 1;
                    via_ref = Some(*n);
                }
                // The inline `[default] clocking ...` form: only the
                // `default`-flagged keyword counts (never a plain
                // `clocking busA @(...); ...` with no `default`/`global`
                // keyword at all, and never `global clocking`, Clause
                // 16.18 -- T35's concern, a distinct concept this task
                // must not conflate with 14.12's default clocking).
                MemberSyntax::ClockingDeclaration(n)
                    if n.global_or_default().map(|t| t.text()) == Some("default") =>
                {
                    count += 1;
                    via_inline = Some(*n);
                }
                // Every other `MemberSyntax` variant (variable/net
                // declarations, procedural blocks, module instances, a
                // non-default clocking declaration, ...) is simply not a
                // 14.12 default-clocking declaration -- an ST-072-style
                // filter, not a narrowed match: nothing here is silently
                // dropped that this task claims to handle.
                _ => {}
            }
        }
        if count > 1 {
            return Err(DefaultScopeError::DuplicateDefaultClocking(
                decl_scope.name().to_string(),
            ));
        }
        if let Some(n) = via_ref {
            let name = n.name().map(|t| t.text()).unwrap_or("");
            let sym = find_in_lexical_scope(decl_scope, name).ok_or_else(|| {
                DefaultScopeError::UnresolvedDefaultClockingTarget(name.to_string())
            })?;
            if sym.kind() != SymbolKind::ClockingBlock {
                return Err(DefaultScopeError::DefaultClockingTargetNotAClockingBlock(
                    name.to_string(),
                ));
            }
            return Ok(Some(sym));
        }
        if let Some(n) = via_inline {
            // The inline form elaborates its own `ClockingBlock` member
            // directly in `decl_scope` (named or, per 14.12's grammar,
            // anonymous -- `default clocking @(posedge clk); endclocking`
            // is legal and elaborates with an empty name) -- recovered by
            // syntax-node identity rather than by name, which works for
            // both, confirmed live: the elaborated `ClockingBlock`
            // member's own `.syntax(tree)` is `==` the exact
            // `ClockingDeclarationSyntax` node found here.
            let decl_node = AstNode::syntax(&n);
            let sym = decl_scope.members().find(|m| {
                m.kind() == SymbolKind::ClockingBlock && m.syntax(tree) == Some(decl_node)
            });
            return match sym {
                Some(sym) => Ok(Some(sym)),
                // Unreachable on a fatal-error-free `Design` (see this
                // function's doc comment on `UnresolvedDefaultClockingTarget`).
                None => Err(DefaultScopeError::UnresolvedDefaultClockingTarget(
                    "<inline default clocking>".to_string(),
                )),
            };
        }
        // Neither form found directly in `decl_scope` -- 14.12's "extends
        // to nested ... declarations" means the search continues to the
        // next (lexically enclosing) scope `each_lexical_scope` yields.
    }
    Ok(None)
}

/// LRM 16.15's resolved default disable condition for `scope`: the nearest
/// enclosing scope's `default disable iff expr;` declaration, together
/// with the [`Symbol`] of the scope it was *declared* in -- "Any signals
/// referenced in the disable iff declaration that are resolved using
/// scopes will be resolved from the scope of the declaration" (16.15), so
/// a later compiling pass (T27) must bind `expr`'s names against that
/// scope, never against the querying assertion's own (potentially more
/// deeply nested) scope. `None` if no scope in the chain declares one
/// (16.15 rule (c), "no inference ... equivalent to ... a 1'b0 disable
/// condition").
pub fn default_disable_of<'d, 't>(
    scope: &Symbol<'d>,
    tree: &'t SyntaxTree,
) -> Result<Option<(Symbol<'d>, DefaultDisableDeclarationSyntax<'t>)>, DefaultScopeError> {
    for (decl_scope, items) in each_lexical_scope(*scope, tree) {
        let mut found: Option<DefaultDisableDeclarationSyntax> = None;
        let mut count = 0usize;
        for item in &items {
            if let MemberSyntax::DefaultDisableDeclaration(n) = item {
                count += 1;
                found = Some(*n);
            }
        }
        if count > 1 {
            return Err(DefaultScopeError::DuplicateDefaultDisable(
                decl_scope.name().to_string(),
            ));
        }
        if let Some(n) = found {
            return Ok(Some((decl_scope, n)));
        }
    }
    Ok(None)
}

pub fn build_template_layout(body: &Symbol) -> Result<StateLayout, LayoutError> {
    let arena = Arena::new(BuildMode::FourState);
    let mut slots = Vec::new();
    let mut next_key: u32 = 0;
    let mut slot_of_symbol: std::collections::HashMap<crate::symid::SymbolId, usize> =
        std::collections::HashMap::new();

    // Generate blocks' items belong to the module (`netlist::module_items`).
    //
    // Classes plan Task 4 (`docs/superpowers/plans/2026-10-03-classes.md`,
    // LRM 8.9): this same walk is also the entry point for a class
    // template's *static* properties -- `body` may be a `ClassType` symbol
    // (the caller mints a singleton segment for it, keyed by
    // `ClassTemplateId` rather than a real elaborated `InstanceId`; see
    // `state::instance::{class_static_instance,
    // StateEngine::allocate_class_static_singletons}`). A static
    // `ClassProperty` (8.9: one
    // copy for the whole simulation) is accepted below exactly like an
    // ordinary module `Variable` -- same `value_type()`/`initializer()`
    // shape, so every per-member branch further down needs no class-specific
    // case of its own. An *instance* (automatic-lifetime) `ClassProperty`
    // is deliberately excluded here: it lives in the object heap
    // (`vj-sim::objects`, Task 3/5), never in this arena. `state_items`'s
    // own `static_procedural_vars` half also already reaches a class's own
    // `Subroutine` (method/constructor) members for their static locals/
    // formals, giving those the identical one-copy-per-class-template
    // storage LRM 6.21 calls for ("one instance ... for all invocations",
    // which for a method is every object's call) with no extra code.
    for member in crate::netlist::state_items(body) {
        let kind = member.kind();
        let is_static_class_property = kind == SymbolKind::ClassProperty
            && member.variable_lifetime() == sv_lang::VariableLifetime::Static;
        if !matches!(
            kind,
            SymbolKind::Variable | SymbolKind::Net | SymbolKind::Port | SymbolKind::FormalArgument
        ) && !is_static_class_property
        {
            // ST-072: genvars/parameters/types/subroutine-locals (subroutine
            // bodies are never descended into by `members()` on a module
            // body in the first place), a class's instance (non-static)
            // properties/methods/constructor/nested classes/constraint and
            // covergroup blocks (Task 4's own `is_static_class_property`
            // exclusion above), and every other non-{Variable,Net,Port}
            // kind are excluded by this filter alone -- no separate
            // exclusion code path exists.
            continue;
        }

        // Deviation, found via real sv-lang=0.1.9 output (not stated in the
        // plan): an ANSI port backed by an implicit net/variable elaborates
        // into TWO sibling members of `body` with the *same* name -- the
        // `Port` boundary-descriptor symbol itself, and its separate
        // internal `Net`/`Variable` symbol
        // (`slang::ast::PortSymbol::internalSymbol`, exposed here as
        // `port_internal_symbol()`). Slotting both would double-allocate
        // storage for one physical signal. The internal symbol is itself a
        // direct member of `body`, so it already gets its own slot on its
        // own pass through this same loop; a `Port` with an internal symbol
        // is therefore skipped here entirely, never producing a second,
        // aliasing slot. A `Port` whose internal connection is an
        // expression rather than a plain symbol (e.g. a concatenation of
        // several internal signals) has nothing else to alias and falls
        // through to get its own slot below.
        if kind == SymbolKind::Port && member.port_internal_symbol().is_some() {
            continue;
        }

        // ST-072 applied to a null port: `module m(a, , c);`'s middle,
        // dot-less position elaborates as its own `Port`-kind member with
        // NO internal symbol and NO internal connection of any kind -- it
        // carries no value and is not "the variable/net/port" ST-060 means.
        // Without this check it would fall through past the
        // `port_internal_symbol()` skip above (which only catches a port
        // *with* something to alias) straight into `member.port_type()`
        // below, which -- verified against real sv-lang=0.1.9 output --
        // still returns `Some(Type)` (slang's `PortSymbol::getType()` is
        // unconditional) rather than `None`, so the old code manufactured a
        // real `SlotDescriptor` with `bit_width == 0` for a construct with
        // nothing to store: a phantom slot, not a loud error and not an
        // exclusion. `port_is_null_port()` is slang's own purpose-built
        // predicate for exactly this case (`PortSymbol::isNullPort`), so it
        // is used here directly rather than re-deriving "null port" from
        // `port_internal_symbol().is_none() && port_internal_expr().is_none()`.
        if kind == SymbolKind::Port && member.port_is_null_port() {
            continue;
        }

        // Deviation from the plan's literal "calls exactly value_type()"
        // text: verified against real sv-lang=0.1.9 output, `value_type()`
        // returns `None` for a real ANSI `Port`-kind symbol (its `is_value()`
        // is false; the port's type lives behind the separate
        // `port_type()` accessor `slang::ast::PortSymbol::getType` mirrors).
        // Using `value_type()` unconditionally would turn every ANSI port
        // into a spurious `UnsupportedMemberKind` error, which is exactly
        // ST-060's "produces slots only for the variable/net/port" -- a
        // *port* -- requirement failing in practice. `port_type()` is used
        // only for `Port`-kind members; `Variable`/`Net` still go through
        // `value_type()` exactly as the plan specifies.
        let ty = if kind == SymbolKind::Port {
            member.port_type()
        } else {
            member.value_type()
        }
        .ok_or_else(|| LayoutError::UnsupportedMemberKind(kind, member.name().to_string()))?;

        // Task 6 (ST-061/ST-127): `is_signed()`/`is_four_state()` are part of
        // this file's frozen per-member `Type` accessor call set, but neither
        // is persisted on `SlotOffset` (ST-144 froze that field list at Task
        // 3 -- sign/4-state-ness are operator-level concerns CODEGEN
        // re-derives from the same `Symbol` directly, never storage-shape
        // concerns). `is_signed`'s result IS threaded into the initial-value
        // conversion below (the one place signedness legitimately affects
        // this function's output, via `four_state_to_owned_svint`'s `signed`
        // parameter) -- it never affects the word/class/width math itself,
        // proven by `unsigned_and_signed_same_width_produce_identical_slot_shape`.
        let is_signed = ty.is_signed();
        let _is_four_state = ty.is_four_state();

        // ST-062: `fields()` is called on every member's `Type` -- empty for
        // any non-struct/union type per `sv_lang::Type::fields`'s own doc --
        // solely to assert a packed struct/union's `bit_width()` already
        // reflects the full flattened width; never to emit one slot per
        // field (no `SlotDescriptor` is ever constructed from this check).
        //
        // review fix r1: the two shapes have different flatten invariants
        // and must not share one check. A packed STRUCT concatenates its
        // fields, so their widths sum to the struct's own `bit_width()`. A
        // packed UNION does not: per IEEE 1800, every member of a packed
        // union shares one bit length, and the union's own `bit_width()`
        // *is* that shared length, not the sum of every member's width (a
        // 2-field, 8-bit-per-field packed union has `bit_width() == 8`, not
        // 16). Summing unconditionally made this `debug_assert_eq!` panic on
        // any ordinary packed union with 2+ fields. `is_packed_union()` is
        // added to this file's per-member `Type` accessor set for this one
        // call site (Task 6's Acceptance-section whitelist is updated to
        // match; see the plan's Task 6 section) -- no other accessor in the
        // frozen set can distinguish a union from a struct.
        //
        // review fix r2: `Type::fields()` is documented (and confirmed
        // against real sv-lang=0.1.9 output) to yield fields for a struct or
        // union type "packed or unpacked" -- not packed-only, despite this
        // block's name. An UNPACKED struct/union member (e.g. `struct {
        // logic a; logic b; } x;`, a plain `Variable`-kind member this
        // builder's own filter accepts) has a nonempty `field_syms` but a
        // `bit_width()` of 0 (unpacked struct/union is non-integral), so the
        // unconditional `debug_assert_eq!`/summed-width comparison below
        // would panic on it under any debug-profile build (`cargo
        // test`/`cargo build`; compiled out only in `--release`) instead of
        // falling through to this same function's own `bit_width() == 0 ->
        // Err(UnsupportedType)` rejection a few lines down -- exactly the
        // "loud Err, never ... a panic" contract this file's own
        // `LayoutError::UnsupportedType` doc comment promises. Gating this
        // whole block on `ty.is_integral()` ("true for a packed/integral
        // type", per `Type::is_integral`'s own doc) restricts the flatten
        // invariant to the packed shapes it was written for; an unpacked
        // struct/union instead falls through with an untouched
        // `bit_width() == 0` and is rejected by the existing check below,
        // never guessed at and never panicked on.
        let field_syms: Vec<_> = ty.fields().collect();
        if !field_syms.is_empty() && ty.is_integral() {
            if ty.is_tagged_union() {
                // LRM 7.3.2: a packed tagged union is `tag ++ payload`; a
                // member is right-justified and may be narrower than the
                // union (a `void` member has no payload), so the widths are
                // bounded by, not equal to, `bit_width()`.
                for f_ty in field_syms.iter().filter_map(|f| f.value_type()) {
                    debug_assert!(
                        f_ty.bit_width() <= ty.bit_width(),
                        "packed tagged-union flatten: a member is wider than \
                         the union for member {:?}",
                        member.name(),
                    );
                }
            } else if ty.is_packed_union() && ty.packed_union_is_soft() {
                // LRM 7.3.1: a soft packed union is as wide as its widest
                // member; narrower members are right-justified.
                for f_ty in field_syms.iter().filter_map(|f| f.value_type()) {
                    debug_assert!(
                        f_ty.bit_width() <= ty.bit_width(),
                        "soft packed-union flatten: a member is wider than \
                         the union for member {:?}",
                        member.name(),
                    );
                }
            } else if ty.is_packed_union() {
                for f_ty in field_syms.iter().filter_map(|f| f.value_type()) {
                    debug_assert_eq!(
                        f_ty.bit_width(),
                        ty.bit_width(),
                        "packed-union flatten: every field's width must equal \
                         Type::bit_width() for member {:?}",
                        member.name(),
                    );
                }
            } else {
                let summed_width: u64 = field_syms
                    .iter()
                    .filter_map(|f| f.value_type())
                    .map(|f_ty| f_ty.bit_width())
                    .sum();
                debug_assert_eq!(
                    summed_width,
                    ty.bit_width(),
                    "packed-struct flatten: fields() total width must equal \
                     Type::bit_width() for member {:?}",
                    member.name(),
                );
            }
        }

        // ST-061/ST-062 memory/dynamic-array routing, verified against
        // /opt/slang/source/ast/types/Type.cpp: `is_dynamically_sized_array()`
        // MUST be checked first and separately from `is_unpacked_array()`
        // below -- it is also `true` for `QueueType`/`DynamicArrayType`/
        // `AssociativeArrayType`, all three of which ALSO satisfy
        // `is_unpacked_array()`, so checking `is_unpacked_array()` first
        // would route a queue/dynamic/associative-array member straight into
        // the fixed-size memory branch below and either panic reading a
        // nonexistent bound or synthesize a bogus layout for it.
        let (class, word_offset, bit_width, elem_word_count, row_stride_words, num_rows, initial) =
            if kind == SymbolKind::Net && super::storage::interconnect_dims(&ty).is_some() {
                // An `interconnect` net or array of them (LRM 6.6.8): typeless,
                // it only expresses connections and never holds a value, so
                // the simulator keeps one inert 1-bit placeholder slot for
                // the whole declaration. The connection analysis
                // (`vj::nets`) merges it into the real nets it joins.
                // SAFETY: same as the `alloc_wide_words` call below.
                let offset = unsafe { arena.alloc_inline_word() };
                (
                    SlotClass::Inline,
                    offset,
                    1u32,
                    1u32,
                    0u32,
                    0u32,
                    Some(FourStateValue::Narrow(0)),
                )
            } else if super::storage::is_collection(&ty) {
                // A queue, dynamic array or associative array: a 2-state
                // 64-bit Inline cell holding a collection handle
                // (`crate::collections`), empty (0) or a constant
                // initializer's value.
                let handle = match crate::netlist::variable_initializer(&member) {
                    Some(init) => collection_initial(&member, &init, &ty)?,
                    None => 0,
                };
                // SAFETY: same as the `alloc_wide_words` call below.
                let offset = unsafe { arena.alloc_inline_word() };
                (
                    SlotClass::Inline,
                    offset,
                    64u32,
                    1u32,
                    0u32,
                    0u32,
                    Some(FourStateValue::Narrow(u128::from(handle))),
                )
            } else if ty.is_unpacked_array() {
                // A fixed-size unpacked array (memory): `element_type()`
                // gives the per-row `Type`, `fixed_unpacked_array_range()`
                // gives the declared row count (ST-061) -- the one call site
                // for both, per Task 6's review-corrected derivation rule.
                // A multi-dimensional array is flattened: its rows are every
                // element in row-major order, lowest index first per
                // dimension (codegen's `crate::arrays`).
                let mut rows: u32 = 1;
                let mut elem_ty = ty;
                // A queue / dynamic / associative array element is a handle
                // row (`crate::collections`).
                while elem_ty.is_unpacked_array() && !super::storage::is_collection(&elem_ty) {
                    rows = rows
                        .checked_mul(elem_ty.fixed_unpacked_array_range().width())
                        .ok_or_else(|| LayoutError::UnsupportedType(member.name().to_string()))?;
                    elem_ty = elem_ty
                        .element_type()
                        .ok_or_else(|| LayoutError::UnsupportedType(member.name().to_string()))?;
                }
                // Integral rows, and rows of the 2-state non-integral types
                // stored as bits: `real`/`shortreal` (IEEE bits),
                // `string` (interned id) and `chandle` (pointer), both 64.
                let elem_bit_width_u64 = if elem_ty.is_integral() || elem_ty.is_floating() {
                    elem_ty.bit_width()
                } else if elem_ty.is_string()
                    || elem_ty.is_chandle()
                    || elem_ty.is_covergroup()
                    || elem_ty.is_virtual_interface()
                    || elem_ty.is_class()
                    || super::storage::is_collection(&elem_ty)
                {
                    64
                } else if elem_ty.is_event() {
                    // An array of named events (LRM 1800-2023 15.5, 6.17):
                    // each row is one scalar event's cell, 128 bits
                    // (`EVENT_CELL_WIDTH`), 0 until triggered. An event has
                    // no constant value to initialize a row with.
                    if crate::netlist::variable_initializer(&member).is_some() {
                        return Err(LayoutError::UnsupportedType(member.name().to_string()));
                    }
                    super::EVENT_CELL_WIDTH as u64
                } else if super::storage::is_unpacked_aggregate(&elem_ty) {
                    // An unpacked struct/union row: its flat stored form.
                    super::storage::storage_width(&elem_ty)
                        .ok_or_else(|| LayoutError::UnsupportedType(member.name().to_string()))?
                } else {
                    return Err(LayoutError::UnsupportedType(member.name().to_string()));
                };
                // review fix r3: a too-wide row (e.g. `logic [200000:0] huge
                // [3:0];`) must be a loud `Err`, never silently clamped to
                // `u16::MAX` -- clamping here would misreport
                // `SlotOffset.bit_width` (used by RUNTIME's per-row
                // read/write masking, state.md §3's `mask(bit_width)`)
                // relative to the row's real width.
                let elem_bit_width = checked_bit_width(elem_bit_width_u64, member.name())?;
                // `words_per_row` is derived from the same, already-checked
                // `elem_bit_width_u64` (<= 65535, per the check just above),
                // so `.div_ceil(64).max(1)` is at most 1024 -- always
                // representable in `u16` -- and the cast below is total, not
                // a guess.
                let words_per_row = (elem_bit_width_u64.div_ceil(64).max(1)) as u32;
                let total_words = words_per_row * rows;
                // SAFETY: `arena` is a local, single-owned value for the
                // duration of this function; every call to it here is
                // sequential on one thread, so `alloc_wide_words`'s
                // single-logical-writer / no-concurrent-borrow obligation
                // (see its doc comment in `state::arena`) trivially holds.
                let offset = unsafe { arena.alloc_wide_words(total_words) };
                // A declared initializer (`int a[4] = '{1, 2, 3, 4}`) gives
                // every row its constant value (`memory_initial_rows`);
                // otherwise a 2-state element type's rows start at 0 (the
                // reset zeroes every row, `rollback::reset_to_initial`) and
                // a 4-state one's start all-X.
                //
                // A non-constant initializer (`int f[4] = {q, d};`,
                // `int a[3] = g();`; LRM 6.8) has no starting value here: the
                // rows take their defaults and the codegen's one-shot
                // variable-initializer kernel (`discover_variable_initializers`)
                // assigns them before time zero.
                let init_expr = crate::netlist::variable_initializer(&member).filter(|init| {
                    init.constant_value().is_some()
                        || vif_array_elem(&ty).is_some_and(|e| e.is_virtual_interface())
                });
                let initial = match init_expr {
                    Some(init) => Some(memory_initial_rows(
                        &member,
                        &init,
                        &ty,
                        words_per_row as usize,
                    )?),
                    // An unpacked struct/union row mixes 4-state (X) and
                    // 2-state (0) fields: every row gets its default bits.
                    None if super::storage::is_unpacked_aggregate(&elem_ty) => {
                        let bits = super::storage::default_bits(&elem_ty).ok_or_else(|| {
                            LayoutError::UnsupportedType(member.name().to_string())
                        })?;
                        let (mut a, mut b) = super::value::bits_to_aval_bval(&bits);
                        a.resize(words_per_row as usize, 0);
                        b.resize(words_per_row as usize, 0);
                        Some(FourStateValue::Wide {
                            aval: a.repeat(rows as usize),
                            bval: b.repeat(rows as usize),
                        })
                    }
                    None => (!elem_ty.is_four_state()).then_some(FourStateValue::Narrow(0)),
                };
                (
                    SlotClass::Memory,
                    offset,
                    elem_bit_width,
                    words_per_row,
                    words_per_row,
                    rows,
                    initial,
                )
            } else if super::storage::is_unpacked_aggregate(&ty) {
                // An unpacked struct/union: one flat vector of its fields'
                // stored bits (`storage`), Inline or Wide by width, starting
                // at its constant initializer or its per-field defaults
                // (X for 4-state fields, 0 for 2-state ones).
                let unsupported = || LayoutError::UnsupportedType(member.name().to_string());
                let width_u64 = super::storage::storage_width(&ty).ok_or_else(unsupported)?;
                let bit_width = checked_bit_width(width_u64, member.name())?;
                let bits = match crate::netlist::variable_initializer(&member) {
                    // A tagged union's constant has no encoded form
                    // (`ConstantValue::Union` is a string): the slot starts
                    // undefined and codegen's variable-initializer
                    // assignment sets it before time zero.
                    Some(_) if super::storage::contains_tagged_union(&ty) => {
                        super::storage::default_bits(&ty).ok_or_else(unsupported)?
                    }
                    Some(init) => {
                        let cv = init.constant_value().ok_or_else(unsupported)?;
                        super::storage::constant_bits(&cv, &ty).ok_or_else(unsupported)?
                    }
                    None => super::storage::default_bits(&ty).ok_or_else(unsupported)?,
                };
                let word_count = width_u64.div_ceil(64).max(1) as u32;
                // SAFETY: same as the `alloc_wide_words` call above.
                let (class, offset) = if word_count <= 1 {
                    (SlotClass::Inline, unsafe { arena.alloc_inline_word() })
                } else {
                    (SlotClass::Wide, unsafe {
                        arena.alloc_wide_words(word_count)
                    })
                };
                (
                    class,
                    offset,
                    bit_width,
                    word_count,
                    0u32,
                    0u32,
                    Some(super::value::bits_to_four_state(&bits)),
                )
            } else if ty.is_floating() {
                // `real`/`realtime` (64-bit) and `shortreal` (32-bit): a
                // 2-state Inline cell holding the IEEE-754 bits (codegen's
                // `real` module), 0.0 unless a constant initializer says
                // otherwise.
                let width = ty.bit_width() as u32;
                let bits: u64 = match crate::netlist::variable_initializer(&member)
                    .and_then(|init| init.constant_value())
                {
                    Some(sv_lang::ConstantValue::Real(f)) if width == 32 => {
                        u64::from((f as f32).to_bits())
                    }
                    Some(sv_lang::ConstantValue::Real(f)) => f.to_bits(),
                    _ => 0,
                };
                // SAFETY: same as the `alloc_wide_words` call above.
                let offset = unsafe { arena.alloc_inline_word() };
                (
                    SlotClass::Inline,
                    offset,
                    width,
                    1u32,
                    0u32,
                    0u32,
                    Some(FourStateValue::Narrow(u128::from(bits))),
                )
            } else if ty.is_string() {
                // A `string`: a 2-state 64-bit Inline cell holding the id of
                // an interned string (`crate::strings`), `""` (0) unless a
                // constant initializer says otherwise.
                let id = match crate::netlist::variable_initializer(&member)
                    .and_then(|init| init.constant_value())
                {
                    Some(sv_lang::ConstantValue::String(s)) => crate::strings::intern(s.as_bytes()),
                    _ => 0,
                };
                // SAFETY: same as the `alloc_wide_words` call above.
                let offset = unsafe { arena.alloc_inline_word() };
                (
                    SlotClass::Inline,
                    offset,
                    64u32,
                    1u32,
                    0u32,
                    0u32,
                    Some(FourStateValue::Narrow(u128::from(id))),
                )
            } else if ty.is_chandle()
                || ty.is_virtual_interface()
                || ty.is_class()
                || ty.is_covergroup()
            {
                // A `chandle` (a C pointer from DPI), a virtual interface
                // (an interface instance's id, `netlist::vif`), or a class
                // handle (classes plan Task 5, LRM 1800-2023 §8.4: a class
                // variable's own storage is just the OBJECT HANDLE -- the
                // referenced object's fields live in the object heap,
                // `vj_sim::objects`, never here): a 2-state 64-bit
                // Inline cell, `null` (0) initially -- a class variable's
                // default initial value absent an explicit `new`
                // initializer (8.5: "a class variable shall be initialized
                // to the value null").

                // SAFETY: same as the `alloc_wide_words` call above.
                let offset = unsafe { arena.alloc_inline_word() };
                (
                    SlotClass::Inline,
                    offset,
                    64u32,
                    1u32,
                    0u32,
                    0u32,
                    Some(FourStateValue::Narrow(0)),
                )
            } else if ty.is_event() {
                // A named `event` is a 2-state Wide cell starting at 0 (see
                // `EVENT_CELL_WIDTH`): `-> e` rewrites it and `@e` is an
                // any-change wait on it.
                let words = super::EVENT_CELL_WIDTH.div_ceil(64);
                // SAFETY: same as the `alloc_wide_words` call above.
                let offset = unsafe { arena.alloc_wide_words(words) };
                (
                    SlotClass::Wide,
                    offset,
                    super::EVENT_CELL_WIDTH,
                    words,
                    0u32,
                    0u32,
                    Some(FourStateValue::Wide {
                        aval: vec![0; words as usize],
                        bval: vec![0; words as usize],
                    }),
                )
            } else {
                // review fix r1: the plan's own Task 6 text promises
                // `LayoutError::UnsupportedType` rejects "a dynamic array,
                // queue, associative array, or class handle" (and, more
                // generally, any shape this builder cannot yet lay out), but
                // only the dynamically-sized-array predicate above was ever
                // checked -- a class-handle, `string`, `chandle`, `event`,
                // or virtual-interface member fell through to here and
                // called `ty.bit_width()`, which (vendored source,
                // `Type.cpp::getBitWidth`) returns 0 for exactly these kinds
                // (neither integral nor floating), silently manufacturing a
                // phantom `SlotClass::Inline`/`bit_width == 0` slot instead
                // of the loud error this file's own doc comments call for.
                //
                // review fix r3: `bit_width_u64 == 0` was not a complete
                // rejection, though -- a `real`/`shortreal`/`realtime`
                // member (e.g. `real r;`) is neither a class handle nor any
                // of the other zero-width shapes above, but has a NONZERO
                // `bit_width()` (64/32/64, per the same vendored
                // `getBitWidth`) despite this wave implementing no
                // floating-point representation, read/write path, or
                // initial-value threading at all (state.md's storage model
                // and the `SlotClass` enum define none), so it too fell
                // through into ordinary 4-state Inline/Wide slot machinery
                // with its initializer silently dropped (`four_state_of_
                // constant`'s `ConstantValue::as_integer()` returns `None`
                // for a real constant). `is_integral()` ("true for a
                // packed/integral type") is the correct, single gate for
                // both problems: false for every shape this branch must
                // reject (class handle, string, chandle, event, virtual
                // interface, or real/shortreal/realtime), true for every
                // packed integral scalar this wave DOES support (including
                // a packed struct/union, whose flattened `bit_width()` is
                // then always nonzero) -- so it replaces the old
                // `bit_width_u64 == 0` test rather than supplementing it
                // (leaving that test in place would make it a check that
                // can never fire, since every shape it caught is already
                // non-integral).
                if !ty.is_integral() {
                    return Err(LayoutError::UnsupportedType(member.name().to_string()));
                }
                let bit_width_u64 = ty.bit_width();
                // review fix r3: reject (never clamp) a member wider than
                // `u16::MAX` bits, and derive `word_count` from the real,
                // untruncated `bit_width_u64` -- not from an already-clamped
                // `bit_width` -- so a Wide slot's arena allocation below is
                // never undersized relative to the member's true width (the
                // old `(bit_width as u32).div_ceil(64)` computed word count
                // from the post-clamp value, so bits above the 65535-bit
                // clamp point were silently unbacked by any storage at all,
                // not merely mis-reported).
                let bit_width = checked_bit_width(bit_width_u64, member.name())?;
                let word_count_u64 = bit_width_u64.div_ceil(64).max(1);
                // `word_count_u64` is derived from the same, already-checked
                // `bit_width_u64` (<= 65535), so it is at most 1024 --
                // always representable in `u32` -- and this cast is total.
                let word_count = word_count_u64 as u32;
                // SAFETY: same as the `alloc_wide_words` call above -- one
                // local, single-owned `arena`, sequential calls only.
                let (class, offset) = if word_count <= 1 {
                    (SlotClass::Inline, unsafe { arena.alloc_inline_word() })
                } else {
                    (SlotClass::Wide, unsafe {
                        arena.alloc_wide_words(word_count)
                    })
                };
                // ST-063/ST-127: the elaborated initial value, obtained by
                // constant-folding `initializer()` (the prefold cache --
                // `Compilation::compile()` already runs with prefolding on,
                // so this is a pure read) through Task 1's
                // `four_state_of_constant`/`four_state_to_owned_svint`, never
                // a locally re-derived evaluator. Absence (no initializer, or
                // a non-integer-constant-foldable one) stays `None`, never a
                // fabricated zero.
                //
                // CONTRACTS D4: `SlotDescriptor.initial` is the sv-lang-free
                // `FourStateValue`, so the constant is resized to the declared
                // width/signedness through `OwnedSVInt` (unchanged semantics)
                // and converted back here, once. `None` from the back
                // conversion (`owned_svint_to_four_state`) resets to all-X,
                // exactly as instance creation did before.
                //
                // A checker's output formal (`output int ctr = 0`, LRM
                // 17.2) takes its initial value from the instantiation's
                // connection, with a variable's initialization semantics
                // (6.8); a non-constant one is rejected, never dropped.
                let checker_initial = crate::netlist::checker_output_of(&member)
                    .and_then(|o| o.initial)
                    .map(|init| {
                        if init.constant_value().is_some() {
                            Ok(init)
                        } else {
                            Err(LayoutError::NonConstantCheckerOutputInitial(
                                member.name().to_string(),
                            ))
                        }
                    })
                    .transpose()?;
                let initial = crate::netlist::variable_initializer(&member)
                    .or(checker_initial)
                    .and_then(|expr| expr.constant_value())
                    .and_then(|cv| four_state_of_constant(&cv))
                    .and_then(|fv| {
                        owned_svint_to_four_state(&four_state_to_owned_svint(
                            &fv, bit_width, is_signed,
                        ))
                    });
                // 17.7.2: a free checker variable with no initializer starts at
                // an unconstrained random value (of its own, deterministic
                // stream: the same run gives the same values).
                let initial = initial.or_else(|| {
                    crate::netlist::free_var_kind(&member).map(|_| {
                        let mut state = crate::netlist::free_var_seed(&member);
                        let mut words: Vec<u64> = (0..word_count.max(1))
                            .map(|_| crate::sched::process_rng::splitmix64_next(&mut state))
                            .collect();
                        if bit_width % 64 != 0
                            && let Some(last) = words.get_mut(((bit_width - 1) / 64) as usize)
                        {
                            *last &= (1u64 << (bit_width % 64)) - 1;
                        }
                        if class == SlotClass::Inline {
                            FourStateValue::Narrow(u128::from(words[0]))
                        } else {
                            FourStateValue::Wide {
                                bval: vec![0; words.len()],
                                aval: words,
                            }
                        }
                    })
                });
                // A net with no driver is Z (LRM 1800-2023 §6.6.1); its
                // drivers overwrite that from time 0, and the bits nothing
                // drives keep it. A `trireg` starts at X instead (§6.6.4.1:
                // its initial charge is unknown); `tri0`/`tri1`/`supply*`
                // pull through net resolution (`vj`'s `nets`).
                let initial = initial.or_else(|| {
                    (member.kind() == sv_lang::kinds::SymbolKind::Net
                        && ty.is_four_state()
                        && member.net_charge_strength().is_none())
                    .then(|| {
                        super::value::bits_to_four_state(&vec![sv_lang::Bit::Z; bit_width as usize])
                    })
                });
                // A 2-state variable with no initializer starts at 0 (LRM
                // 1800-2023 §6.8, Table 6-7), not X.
                let initial = initial.or_else(|| {
                    // ... except a tagged union (or an aggregate of one),
                    // which is undefined, tag included (7.3.2): X.
                    (!ty.is_four_state() && !super::storage::contains_tagged_union(&ty)).then(
                        || {
                            if class == SlotClass::Inline {
                                FourStateValue::Narrow(0)
                            } else {
                                FourStateValue::Wide {
                                    aval: vec![0; word_count as usize],
                                    bval: vec![0; word_count as usize],
                                }
                            }
                        },
                    )
                });
                // review fix r1: `word_count` was already computed above and
                // correctly used to call `arena.alloc_wide_words(word_count)`
                // for the Wide class, but the tuple's `elem_word_count`
                // position was left hardcoded at `0u32` instead of threading
                // it through -- a real bug, since design.md's Wide
                // read/write contract slices `[word_offset,
                // word_offset+elem_word_count)` into `wide_aval`/`wide_bval`,
                // so a Wide slot with `elem_word_count == 0` addresses a
                // zero-length window into its own storage. `elem_word_count`
                // is documented as unused by Inline's addressing (state.md
                // §"Inline read/write" never references it), so a nonzero,
                // correctly-derived value here is harmless for Inline and
                // correct for Wide.
                // `word_count` is the same, already-bounded (<= 1024) value
                // computed above, so this cast is total, not a guess --
                // see the comment on `word_count_u64`'s derivation.
                let elem_word_count = word_count;
                (
                    class,
                    offset,
                    bit_width,
                    elem_word_count,
                    0u32,
                    0u32,
                    initial,
                )
            };

        let key = SymbolKey(next_key);
        next_key += 1;

        // The hidden sampled-value cells below clone this slot's shape.
        slot_of_symbol.insert(member.uid(), slots.len());
        slots.push(SlotDescriptor {
            key,
            offset: SlotOffset {
                class,
                word_offset,
                bit_width,
                elem_word_count,
                row_stride_words,
                num_rows,
            },
            initial,
            net_info: None::<NetLayout>,
        });
    }

    // A clocking block (LRM 1800-2023 §14): a 32-bit counter its sampler
    // bumps on each clocking event (what `@(cb)` and `##N` wait on), then
    // one sample cell per input clock variable. After every other slot, in
    // the order `vj-codegen::module::signal_slots_of` lists them.
    for (cb, vars) in clocking_blocks(body) {
        let _ = cb;
        // SAFETY: as for the slots above.
        let offset = unsafe { arena.alloc_inline_word() };
        slots.push(SlotDescriptor {
            key: SymbolKey(next_key),
            offset: SlotOffset {
                class: SlotClass::Inline,
                word_offset: offset,
                bit_width: 32,
                elem_word_count: 1,
                row_stride_words: 0,
                num_rows: 0,
            },
            initial: Some(FourStateValue::Narrow(0)),
            net_info: None,
        });
        next_key += 1;
        for v in vars {
            let ty = v
                .value_type()
                .filter(|t| t.is_integral())
                .ok_or_else(|| LayoutError::UnsupportedType(v.name().to_string()))?;
            let width = checked_bit_width(ty.bit_width(), v.name())?;
            let words = width.div_ceil(64).max(1);
            // SAFETY: as for the slots above.
            let (class, offset) = if words <= 1 {
                (SlotClass::Inline, unsafe { arena.alloc_inline_word() })
            } else {
                (SlotClass::Wide, unsafe { arena.alloc_wide_words(words) })
            };
            slots.push(SlotDescriptor {
                key: SymbolKey(next_key),
                offset: SlotOffset {
                    class,
                    word_offset: offset,
                    bit_width: width,
                    elem_word_count: words,
                    row_stride_words: 0,
                    num_rows: 0,
                },
                initial: (!ty.is_four_state()).then(|| {
                    super::value::bits_to_four_state(&vec![sv_lang::Bit::Zero; width as usize])
                }),
                net_info: None,
            });
            next_key += 1;
        }
    }

    // The sampled value functions' hidden cells (`crate::sva::sampled`): one
    // clone of the source signal's slot per P/S cell, after everything else,
    // in the order `vj-codegen::module::signal_slots_of` lists them. A
    // cell starts at its source's initial value, which is the default
    // sampled value (LRM 16.5.1) the first ticks read.
    let hidden = crate::sva::sampled::hidden_slots(body)
        .map_err(|e| LayoutError::UnsupportedType(format!("sampled value function: {e}")))?;
    for cell in hidden.slots() {
        let (class, words, bit_width, initial) = if let Some(shape) = &cell.foreign {
            // The history of an enclosing instance's signal (a global
            // clocking's event, LRM 14.14): no local slot to clone.
            let words = shape.width.div_ceil(64).max(1);
            let class = if words > 1 {
                SlotClass::Wide
            } else {
                SlotClass::Inline
            };
            (class, words, shape.width, shape.initial.clone())
        } else {
            let src = slot_of_symbol.get(&cell.source).ok_or_else(|| {
                LayoutError::UnsupportedType(format!(
                    "sampled value function over `{}`, which has no state slot",
                    cell.source
                ))
            })?;
            let s = &slots[*src];
            (
                s.offset.class,
                s.offset.elem_word_count,
                s.offset.bit_width,
                s.initial.clone(),
            )
        };
        // SAFETY: as for the slots above.
        let word_offset = match class {
            SlotClass::Inline => unsafe { arena.alloc_inline_word() },
            SlotClass::Wide => unsafe { arena.alloc_wide_words(words) },
            other => {
                return Err(LayoutError::UnsupportedType(format!(
                    "sampled value function over `{}`, a {other:?} slot",
                    cell.source
                )));
            }
        };
        slots.push(SlotDescriptor {
            key: SymbolKey(next_key),
            offset: SlotOffset {
                class,
                word_offset,
                bit_width,
                elem_word_count: words,
                row_stride_words: 0,
                num_rows: 0,
            },
            initial,
            net_info: None,
        });
        next_key += 1;
    }

    // The end-point watcher cells (`crate::sva::endpoint`): one event-shaped,
    // 2-state cell per instance a procedure reads `.triggered`/`@(s)` of, after
    // the hidden cells, in the order `vj-codegen::module::signal_slots_of`
    // lists them.
    for _ in crate::sva::endpoint::watchers(body) {
        let words = super::EVENT_CELL_WIDTH.div_ceil(64);
        // SAFETY: as for the slots above.
        let word_offset = unsafe { arena.alloc_wide_words(words) };
        slots.push(SlotDescriptor {
            key: SymbolKey(next_key),
            offset: SlotOffset {
                class: SlotClass::Wide,
                word_offset,
                bit_width: super::EVENT_CELL_WIDTH,
                elem_word_count: words,
                row_stride_words: 0,
                num_rows: 0,
            },
            initial: Some(FourStateValue::Wide {
                aval: vec![0; words as usize],
                bval: vec![0; words as usize],
            }),
            net_info: None,
        });
        next_key += 1;
    }

    // The event pool (`super::event_pool`): one hidden memory of event cells
    // after everything else, when the body needs event handles, mirrored
    // last in `vj-codegen::module::signal_slots_of`.
    if let Some(pool) = super::event_pool::event_pool(body) {
        let words_per_row = super::EVENT_CELL_WIDTH.div_ceil(64);
        let rows = pool.total_rows();
        // SAFETY: as for the slots above.
        let word_offset = unsafe { arena.alloc_wide_words(words_per_row * rows) };
        slots.push(SlotDescriptor {
            key: SymbolKey(next_key),
            offset: SlotOffset {
                class: SlotClass::Memory,
                word_offset,
                bit_width: super::EVENT_CELL_WIDTH,
                elem_word_count: words_per_row,
                row_stride_words: words_per_row,
                num_rows: rows,
            },
            initial: Some(FourStateValue::Narrow(0)),
            net_info: None,
        });
    }

    Ok(StateLayout {
        inline_words: arena.inline().len() as u32,
        // Task 6 is this file's first user of `Arena::alloc_wide_words`
        // (Wide/Memory-class slots) -- Task 4's stub hardcoded `0` here
        // because it never allocated a wide word; now that wide allocation
        // is real, this must reflect it, or Task 7's `template_size`
        // (ST-135) would under-report every template with a >64-bit or
        // memory member.
        wide_words: arena.wide_aval().len() as u32,
        slots,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::FourStateValue;
    use crate::state::value::compile_source;

    /// ST-058: calling the layout builder twice on the *same* `Symbol` must
    /// produce structurally equal `StateLayout`s (slot count, offsets, key
    /// order) and must not mutate anything shared between the calls. Fails
    /// if any internal counter/cache leaked across calls instead of being
    /// function-local.
    #[test]
    fn layout_builder_is_read_only_and_deterministic_on_repeat_calls() {
        let design = compile_source("module m; logic [7:0] x; wire w; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let first = build_template_layout(&body).expect("layout builds");
        let second = build_template_layout(&body).expect("layout builds again");

        assert_eq!(first.slots.len(), second.slots.len());
        assert_eq!(first.inline_words, second.inline_words);
        assert_eq!(first.wide_words, second.wide_words);
        for (a, b) in first.slots.iter().zip(second.slots.iter()) {
            assert_eq!(a.key, b.key);
            assert_eq!(a.offset.class, b.offset.class);
            assert_eq!(a.offset.word_offset, b.offset.word_offset);
            assert_eq!(a.offset.bit_width, b.offset.bit_width);
        }
    }

    /// Sampled value functions append one hidden slot per P/S cell, cloning
    /// the source's shape and initial value (the default sampled value,
    /// LRM 16.5.1), after every ordinary slot.
    #[test]
    fn sampled_value_calls_append_cloned_hidden_slots() {
        let src = "module top; logic clk; logic [69:0] w; int n;\n\
                   always @(posedge clk) begin n <= $past(n, 2); if ($rose(w)) n <= 0; end\n\
                   endmodule\n";
        let plain = compile_source("module top; logic clk; logic [69:0] w; int n; endmodule\n")
            .expect("compiles");
        let design = compile_source(src).expect("compiles");
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let base = build_template_layout(
            &plain
                .top_instances()
                .next()
                .unwrap()
                .instance_body()
                .unwrap(),
        )
        .expect("base layout");
        let hidden = crate::sva::sampled::hidden_slots(&body).expect("hidden");
        let layout = build_template_layout(&body).expect("layout");
        assert_eq!(
            layout.slots.len(),
            base.slots.len() + hidden.slots().count()
        );
        // `n` is a 2-state int: slot 2; its P cell is initialised to 0, and a
        // 4-state `w` clone is a Wide slot of the same width.
        let n_slots: Vec<_> = layout.slots[base.slots.len()..]
            .iter()
            .filter(|s| s.offset.bit_width == 32)
            .collect();
        assert_eq!(n_slots.len(), 3, "P + two S cells of n");
        for s in n_slots {
            assert!(
                matches!(s.initial, Some(FourStateValue::Narrow(0))),
                "{:?}",
                s.initial
            );
        }
        let w_slots: Vec<_> = layout.slots[base.slots.len()..]
            .iter()
            .filter(|s| s.offset.bit_width == 70)
            .collect();
        assert_eq!(w_slots.len(), 2, "P + S_0 of w");
        assert!(w_slots.iter().all(|s| s.offset.class == SlotClass::Wide));
        // Offsets are distinct from every other slot's.
        let mut seen = std::collections::HashSet::new();
        for s in &layout.slots {
            assert!(seen.insert((s.offset.class as u8, s.offset.word_offset)));
        }
    }

    /// ST-060: a module containing a genvar, a parameter, a variable, a net,
    /// and a port must produce slots only for the variable/net/port. Fails
    /// if the filter accepts `Parameter`/`Genvar` too (over-inclusion) or
    /// drops `Port` (under-inclusion).
    ///
    /// **Deviation from the plan's literal fixture text:** the plan's source
    /// text (`input logic p_in;` re-declared with no matching entry in the
    /// module's port list) does not actually create a `Port`-kind symbol --
    /// verified against real `sv-lang=0.1.9` output, it produces a
    /// diagnostic ("port declaration 'p_in' does not match any port in the
    /// module's port list") and `p_in` elaborates as a plain `Variable`
    /// instead, so the original text would only ever exercise 2 filtered
    /// members even from a correct implementation. `p_in` is declared here
    /// as a genuine ANSI port (in the module's own port list) instead, which
    /// does produce a real `Port`-kind member while keeping every other part
    /// of the fixture (a genvar, a parameter, a variable, a net) unchanged.
    #[test]
    fn only_variable_net_port_kinds_produce_slots() {
        let design = compile_source(
            "module m #(parameter int P = 1) (input logic p_in); genvar i; logic x; wire w; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 3);
    }

    /// Classes plan Task 4 (`docs/superpowers/plans/2026-10-03-classes.md`,
    /// LRM 8.9): a class's `static` `ClassProperty` member gets a slot
    /// exactly like a module `Variable`; its *instance* (automatic-lifetime)
    /// property and its method are both excluded -- they belong to the
    /// object heap (Task 3/5), never this arena.
    #[test]
    fn only_static_class_properties_produce_slots() {
        let design = compile_source(
            "class Counter; static int count; int id; \
             function void bump(); id = id + 1; endfunction endclass\n\
             module m; Counter c; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let class_sym = body
            .find("c")
            .expect("c declared")
            .value_type()
            .expect("c has a type")
            .as_symbol();

        let layout = build_template_layout(&class_sym).expect("layout builds");
        assert_eq!(
            layout.slots.len(),
            1,
            "only the static property `count` gets a slot -- not `id` (an \
             instance field) and not `bump` (a method)"
        );
        assert_eq!(layout.slots[0].offset.bit_width, 32);
    }

    /// A `static const` class property's constant initializer is baked
    /// directly into the slot's own `initial` value at layout-build time --
    /// "evaluated once before the start of simulation" (8.9) is satisfied by
    /// construction, never by re-running an initializer expression on every
    /// read (there is no such expression-evaluation path in this builder at
    /// all, for a class property any more than for a module variable).
    #[test]
    fn static_const_initializer_is_baked_into_the_slot() {
        let design = compile_source(
            "class Counter; static const int FIVE = 5; endclass\n\
             module m; Counter c; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let class_sym = body
            .find("c")
            .expect("c declared")
            .value_type()
            .expect("c has a type")
            .as_symbol();

        let layout = build_template_layout(&class_sym).expect("layout builds");
        assert_eq!(layout.slots.len(), 1);
        match &layout.slots[0].initial {
            Some(FourStateValue::Narrow(v)) => assert_eq!(*v, 5),
            other => panic!("expected a baked-in Narrow(5) initial value, got {other:?}"),
        }
    }

    /// ST-072: genvars, parameters, and subroutine-local automatic variables
    /// must never become slots -- only the one real signal in the module
    /// does. `local_v` is never even visited: `members()` on the module body
    /// does not descend into a subroutine's own body.
    #[test]
    fn genvars_params_and_subroutine_locals_never_become_slots() {
        let design = compile_source(
            "module m; parameter int P = 1; genvar i; \
             function automatic int f(int a); int local_v; return a; endfunction; \
             logic only_real_signal; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 1);

        // Test-local lookup (SlotDescriptor deliberately carries no name --
        // ST-153): replicate the production {Variable,Net,Port} filter here
        // to identify the one real member independently and confirm it is
        // `only_real_signal`, not `P`/`i`/`local_v`.
        let members: Vec<_> = body
            .members()
            .filter(|s| {
                matches!(
                    s.kind(),
                    SymbolKind::Variable | SymbolKind::Net | SymbolKind::Port
                )
            })
            .collect();
        assert_eq!(members.len(), 1);
        assert_eq!(members[0].name(), "only_real_signal");
    }

    /// A `Subroutine` member (a kind this function's filter does not accept
    /// among `{Variable,Net,Port}`) is silently -- and correctly -- excluded
    /// by the filter itself, never a `LayoutError`: subroutines aren't
    /// state. `LayoutError::UnsupportedMemberKind` is reserved for a kind
    /// the filter *does* accept but that fails to yield a queryable shape;
    /// this test proves that variant is constructible and carries the
    /// offending kind + name (a compile-level proof, mirroring Task 3's
    /// `state_layout_has_exactly_the_three_contracted_fields` -- the runtime
    /// half below proves the filter's exclusion is real, not merely that the
    /// error type happens to compile).
    #[test]
    fn unsupported_member_kind_is_a_loud_typed_error_not_a_silent_skip() {
        let design = compile_source(
            "module m; function automatic int f(int a); return a; endfunction; \
             logic ok_signal; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        // The subroutine is excluded by the filter -- no panic, no error,
        // no slot for it -- and the one real signal still gets a slot.
        let layout = build_template_layout(&body).expect("no unsupported member kind reached");
        assert_eq!(layout.slots.len(), 1);

        let members: Vec<_> = body
            .members()
            .filter(|s| s.kind() == SymbolKind::Subroutine)
            .collect();
        assert_eq!(
            members.len(),
            1,
            "expected exactly one Subroutine-kind member for this fixture"
        );

        // LayoutError::UnsupportedMemberKind is constructible and carries
        // the offending kind + name -- the loud, typed error this task and
        // every later layout task return instead of a silent skip or a
        // panic, for a kind the filter accepts but that fails to yield a
        // queryable shape.
        let err = LayoutError::UnsupportedMemberKind(SymbolKind::Variable, "x".to_string());
        match err {
            LayoutError::UnsupportedMemberKind(kind, name) => {
                assert_eq!(kind, SymbolKind::Variable);
                assert_eq!(name, "x");
            }
            LayoutError::UnsupportedType(name)
            | LayoutError::NonConstantCheckerOutputInitial(name) => {
                panic!("unexpected {name} error for this constructed value")
            }
        }
    }

    /// ST-072 applied to a null port: the middle, dot-less position of
    /// `module m(a, , c);` elaborates as a real `Port`-kind member of
    /// `body` (`port_internal_symbol()` and `port_internal_expr()` both
    /// `None`, `port_is_null_port()` true) but carries no value at all --
    /// it must never become a slot. Before the fix, this member fell
    /// through the `port_internal_symbol().is_some()` skip (which only
    /// catches a port *with* something to alias) straight into
    /// `member.port_type()`, which -- verified against real
    /// `sv-lang=0.1.9` output -- still returns `Some(Type)` for a null
    /// port rather than `None`, so the old code emitted a phantom
    /// `SlotDescriptor` with `bit_width == 0` for it: 3 slots instead of
    /// 2, with one carrying no real signal. This is also the only test
    /// in this file that reaches the `port_type()` branch through a
    /// `Port`-kind member that is *not* immediately skipped by the
    /// internal-symbol check -- every other fixture's ports all have
    /// plain internal symbols and are skipped before that call.
    #[test]
    fn null_ports_never_become_slots() {
        let design = compile_source("module m(a, , c); input a; input c; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        // Sanity: the middle port position is a real Port-kind member with
        // no internal symbol, confirming this fixture actually exercises
        // the null-port path rather than silently degenerating to 2 ports.
        let ports: Vec<_> = body
            .members()
            .filter(|s| s.kind() == SymbolKind::Port)
            .collect();
        assert_eq!(ports.len(), 3, "expected 3 Port-kind members (a, null, c)");
        assert_eq!(
            ports.iter().filter(|p| p.port_is_null_port()).count(),
            1,
            "expected exactly one null port"
        );

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(
            layout.slots.len(),
            2,
            "only the two real ports (a, c) should produce slots -- the null port must not"
        );
        for slot in &layout.slots {
            assert!(
                slot.offset.bit_width > 0,
                "no slot may be a phantom zero-width slot for the null port"
            );
        }
    }

    // -- Task 6: per-member shape derivation, packed-struct flatten, initial
    // value (ledger ST-061, ST-062, ST-063, ST-127). --

    /// ST-061: a signed 17-bit variable must get `bit_width == 17` exactly,
    /// not 18/32/64 -- the concrete regression a buggy sign-aware width
    /// calculation would introduce.
    #[test]
    fn signed_17bit_variable_gets_correct_width_not_sign_extended_into_18bits() {
        let design = compile_source("module m; logic signed [16:0] x; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 1);
        assert_eq!(layout.slots[0].offset.class, SlotClass::Inline);
        assert_eq!(layout.slots[0].offset.bit_width, 17);
    }

    /// ST-061: an 8-deep memory of 32-bit rows must get `SlotClass::Memory`
    /// with `elem_word_count == 1`, `row_stride_words == 1`, and
    /// `num_rows == 8` -- the `8` is the concrete proof `num_rows` was
    /// actually derived from `fixed_unpacked_array_range()`'s
    /// `{left:0,right:7}` (`|0-7|+1`), not left at a placeholder/zero.
    ///
    /// (Rust identifiers cannot start with a digit -- the plan's literal test
    /// name `8deep_memory_...` is adapted to `eight_deep_memory_...`, a
    /// mechanical syntax accommodation, not a behavioral deviation.)
    #[test]
    fn eight_deep_memory_of_32bit_rows_gets_memory_class_with_correct_stride_and_rows() {
        let design = compile_source("module m; logic [31:0] mem [0:7]; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 1);
        let offset = layout.slots[0].offset;
        assert_eq!(offset.class, SlotClass::Memory);
        assert_eq!(offset.elem_word_count, 1);
        assert_eq!(offset.row_stride_words, 1);
        assert_eq!(offset.num_rows, 8);
    }

    /// LRM 1800-2023 15.5 / 6.17: an unpacked array of named events is a
    /// Memory slot whose rows are the 128-bit event cell (two words), one row
    /// per element across every dimension.
    #[test]
    fn event_array_lays_out_as_memory_of_event_cells() {
        let design = compile_source("module m; event ea [0:2]; event e2 [1:2][0:1]; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 2);
        let (flat, multi) = (&layout.slots[0].offset, &layout.slots[1].offset);
        for (offset, rows) in [(flat, 3), (multi, 4)] {
            assert_eq!(offset.class, SlotClass::Memory);
            assert_eq!(offset.bit_width, super::super::EVENT_CELL_WIDTH);
            assert_eq!(offset.elem_word_count, 2);
            assert_eq!(offset.row_stride_words, 2);
            assert_eq!(offset.num_rows, rows);
        }
    }

    /// ST-062: a packed struct with 3 fields totaling 40 bits must flatten to
    /// exactly one slot of width 40, not three. Fails if the builder recurses
    /// into `fields()` and emits one `SlotDescriptor` per field instead of
    /// flattening.
    #[test]
    fn packed_struct_flattens_to_exactly_one_slot_of_total_width() {
        let design = compile_source(
            "module m; typedef struct packed { logic [7:0] a; logic [15:0] b; \
             logic [15:0] c; } s_t; s_t x; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(
            layout.slots.len(),
            1,
            "expected one flattened slot, not one per field"
        );
        assert_eq!(layout.slots[0].offset.bit_width, 40);
        assert_eq!(layout.slots[0].offset.class, SlotClass::Inline);
    }

    /// ST-063/ST-127: a variable declared with an initializer must have its
    /// constant-folded value threaded into `SlotDescriptor.initial`; a
    /// variable with no initializer must stay `None`, never a fabricated
    /// zero -- proving the absence-vs-present distinction is preserved.
    #[test]
    fn initializer_constant_folds_into_slot_initial_value() {
        let design = compile_source("module m; logic [7:0] x = 8'hAA; logic [7:0] y; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 2);

        let x_initial = layout.slots[0]
            .initial
            .as_ref()
            .expect("x has an initializer and must have Some(initial)");
        assert!(
            matches!(x_initial, FourStateValue::Narrow(0xAA)),
            "x's initializer must fold to 8'hAA with no unknown bits, got {x_initial:?}"
        );

        assert!(
            layout.slots[1].initial.is_none(),
            "y has no initializer and must stay None, never a fabricated zero"
        );
    }

    /// Closes the interpretation question left open by this task's public
    /// names note: sign is genuinely not a storage-shape input.
    /// `logic [7:0] u;` and `logic signed [7:0] s;` must produce identical
    /// `bit_width`/`class` shape.
    #[test]
    fn unsigned_and_signed_same_width_produce_identical_slot_shape() {
        let design = compile_source("module m; logic [7:0] u; logic signed [7:0] s; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 2);
        assert_eq!(
            layout.slots[0].offset.bit_width,
            layout.slots[1].offset.bit_width
        );
        assert_eq!(layout.slots[0].offset.class, layout.slots[1].offset.class);
    }

    /// A queue, dynamic array or associative array member is a 2-state
    /// 64-bit Inline slot holding a collection handle (`crate::
    /// collections`), empty (0) initially; the ordinary signal beside it
    /// keeps its own shape.
    #[test]
    fn a_collection_member_is_a_64_bit_handle_slot_starting_empty() {
        for src in [
            "module m; int q[$]; logic [7:0] ok_signal; endmodule\n",
            "module m; int d[]; logic [7:0] ok_signal; endmodule\n",
            "module m; int aa[string]; logic [7:0] ok_signal; endmodule\n",
        ] {
            let design = compile_source(src).expect("valid SV source compiles");
            let body = design
                .top_instances()
                .next()
                .expect("one top instance")
                .instance_body()
                .expect("instance has a body");
            let layout = build_template_layout(&body).expect("a collection member lays out");
            assert_eq!(layout.slots.len(), 2, "{src}");
            assert_eq!(layout.slots[0].offset.class, SlotClass::Inline);
            assert_eq!(layout.slots[0].offset.bit_width, 64);
            assert!(matches!(
                layout.slots[0].initial,
                Some(FourStateValue::Narrow(0))
            ));
            assert_eq!(layout.slots[1].offset.bit_width, 8);
        }
    }

    /// A queue's constant initializer is a frozen collection holding its
    /// elements, shared by every instance until one changes it.
    #[test]
    fn a_queue_initializer_is_a_frozen_collection_of_its_elements() {
        let design = compile_source("module m; int q[$] = {4, 5, 6}; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout = build_template_layout(&body).expect("lays out");
        let Some(FourStateValue::Narrow(h)) = layout.slots[0].initial else {
            panic!("expected a handle initial value");
        };
        let h = h as u64;
        assert_eq!(crate::collections::size(h), 3);
        let mut out = [0u64];
        assert!(crate::collections::get(h, 2, &mut out));
        assert_eq!(out[0], 6);
    }

    // -- Task 6 review fixes r1 --

    /// review fix r1: a >64-bit non-array (Wide-class) member must get a
    /// correctly-derived `elem_word_count`, not the hardcoded `0` the
    /// tuple's Wide arm previously returned. A 128-bit variable needs
    /// exactly 2 words; before the fix this was `0`, which -- per
    /// design.md's Wide addressing contract -- slices a zero-length window
    /// `[word_offset, word_offset)` into `wide_aval`/`wide_bval`, so
    /// `sv_get_wide`/`sv_set_wide` would never touch any real storage for
    /// this signal.
    #[test]
    fn wide_128bit_scalar_gets_correct_elem_word_count_not_hardcoded_zero() {
        let design = compile_source("module m; logic [127:0] w; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds");
        assert_eq!(layout.slots.len(), 1);
        let offset = layout.slots[0].offset;
        assert_eq!(offset.class, SlotClass::Wide);
        assert_eq!(offset.bit_width, 128);
        assert_eq!(
            offset.elem_word_count, 2,
            "a 128-bit Wide slot must span exactly 2 wide words, not 0"
        );
    }

    /// review fix r1: a packed union with 2+ fields must not panic the
    /// packed-struct/union flatten invariant. Per IEEE 1800, a packed
    /// union's own `bit_width()` equals one (shared) field width, not the
    /// sum of every field's width -- before the fix, the sum-based
    /// `debug_assert_eq!` fired on this exact, ordinary construct in any
    /// debug build (including `cargo test`).
    #[test]
    fn packed_union_with_multiple_fields_does_not_panic_the_flatten_invariant() {
        let design = compile_source(
            "module m; typedef union packed { logic [7:0] a; logic [7:0] b; } u_t; u_t x; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("layout builds, does not panic");
        assert_eq!(layout.slots.len(), 1);
        assert_eq!(layout.slots[0].offset.bit_width, 8);
        assert_eq!(layout.slots[0].offset.class, SlotClass::Inline);
    }

    /// A multi-dimensional fixed-size unpacked array (e.g.
    /// `logic [7:0] mem2d [3:0][1:0]`) is one Memory slot of the innermost
    /// element's width with every dimension flattened into its rows -- never
    /// the zero-width slot an `element_type()` that is itself an unpacked
    /// array would give (review fix r1's original concern).
    #[test]
    fn multi_dimensional_unpacked_array_flattens_into_rows_of_the_innermost_element() {
        let design = compile_source("module m; logic [7:0] mem2d [3:0][1:0]; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("lays out");
        let offset = &layout.slots[0].offset;
        assert_eq!(offset.class, SlotClass::Memory);
        assert_eq!(offset.bit_width, 8);
        assert_eq!(offset.num_rows, 8, "4 x 2 rows");
    }

    /// review fix r1 (classes plan Task 5 superseding update, see this
    /// test's own rename below): a `string` member must be loudly rejected
    /// via `LayoutError::UnsupportedType`... no -- a `string` member is a
    /// real 2-state 64-bit cell (see the second half of this test), never
    /// a phantom `SlotClass::Inline`/`bit_width == 0` slot.
    ///
    /// Classes plan Task 5 superseding update: a class-HANDLE-typed
    /// member is likewise no longer rejected -- LRM 1800-2023 §8.4: a
    /// class variable's own stored representation is just the OBJECT
    /// HANDLE (never the object's contents, which live in the object
    /// heap, `vj_sim::objects`), exactly like a `chandle`'s. This test
    /// was renamed from `class_handles_are_rejected_and_strings_are_id_
    /// cells_not_phantom_slots` (the test's own ORIGINAL claim, true before
    /// this plan) to `class_handles_are_64_bit_cells_and_strings_are_id_
    /// cells_not_phantom_slots` to assert the new, positive behavior
    /// instead of deleting the regression coverage outright.
    #[test]
    fn class_handles_are_64_bit_cells_and_strings_are_id_cells_not_phantom_slots() {
        let design = compile_source(
            "module m; class C; endclass C c; string s; logic [7:0] ok_signal; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body)
            .expect("a class-handle member must now lay out, not be rejected");
        // `c` is `m`'s first slot-producing member (the `class C; endclass`
        // declaration itself contributes no slot at all -- it is filtered
        // out the same way a port/net/variable-less construct always is).
        let c_slot = &layout.slots[0];
        assert_eq!(c_slot.offset.class, SlotClass::Inline);
        assert_eq!(
            c_slot.offset.bit_width, 64,
            "a class handle is a plain 64-bit reference, exactly like a chandle's"
        );
        assert!(
            matches!(c_slot.initial, Some(FourStateValue::Narrow(0))),
            "a class variable's default initial value, absent an explicit `new`, is null (0)"
        );

        // A string member is not a phantom zero-width slot either: it is a
        // 64-bit 2-state cell holding its interned id (`crate::strings`),
        // initialized to its declaration's value.
        let design2 = compile_source("module m2; string s; string t = \"hi\"; endmodule\n")
            .expect("valid SV source compiles");
        let body2 = design2
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout2 = build_template_layout(&body2).expect("string members lay out");
        assert_eq!(layout2.slots.len(), 2);
        for slot in &layout2.slots {
            assert_eq!(slot.offset.class, SlotClass::Inline);
            assert_eq!(slot.offset.bit_width, 64);
        }
        assert!(matches!(
            layout2.slots[0].initial,
            Some(FourStateValue::Narrow(0))
        ));
        let hi = u128::from(crate::strings::intern(b"hi"));
        assert!(matches!(layout2.slots[1].initial, Some(FourStateValue::Narrow(v)) if v == hi));

        // Isolated compile of the ordinary signal alone: still Ok, proving
        // the rejection above is real, not a vacuously-true Err.
        let design3 = compile_source("module m3; logic [7:0] ok_signal; endmodule\n")
            .expect("valid SV source compiles");
        let body3 = design3
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout3 =
            build_template_layout(&body3).expect("the ordinary signal alone must still build Ok");
        assert_eq!(layout3.slots.len(), 1);
        assert_eq!(layout3.slots[0].offset.bit_width, 8);
    }

    // -- Task 6 review fixes r2 --

    /// An unpacked struct or union member is one flat vector of its
    /// fields' stored bits (`storage`): no panic on the packed-struct
    /// flatten invariant (review fix r2's original concern, since an
    /// unpacked aggregate's `bit_width()` is 0), the stored width, and
    /// per-field initial bits -- X for a 4-state field, 0 for a 2-state one
    /// (the `int`) and for a `real`.
    #[test]
    fn unpacked_struct_and_union_members_are_flat_stored_vectors() {
        let design = compile_source(
            "module m; struct { logic a; logic b; } x; \
             struct { logic [3:0] l; int i; real r; } y; \
             union { logic [7:0] a; logic [7:0] b; } u; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout = build_template_layout(&body).expect("unpacked aggregates lay out");
        assert_eq!(layout.slots.len(), 3);
        let widths: Vec<u32> = layout.slots.iter().map(|s| s.offset.bit_width).collect();
        assert_eq!(widths, [2, 4 + 32 + 64, 8]);
        let classes: Vec<SlotClass> = layout.slots.iter().map(|s| s.offset.class).collect();
        assert_eq!(
            classes,
            [SlotClass::Inline, SlotClass::Wide, SlotClass::Inline]
        );
        // y, LSB first: r (64 zeros), i (32 zeros), l (4 X).
        let mut y_bits = vec![sv_lang::Bit::Zero; 96];
        y_bits.extend([sv_lang::Bit::X; 4]);
        let expect = [vec![sv_lang::Bit::X; 2], y_bits, vec![sv_lang::Bit::X; 8]];
        for (slot, bits) in layout.slots.iter().zip(expect) {
            assert_eq!(
                format!("{:?}", slot.initial),
                format!("{:?}", Some(crate::state::value::bits_to_four_state(&bits))),
            );
        }
    }

    // -- Task 6 review fixes r3 --

    /// review fix r3, revised for real support: a `real`/`shortreal`/
    /// `realtime` member is a 2-state `Inline` cell of its IEEE width
    /// (64/32/64) holding the IEEE-754 bits of its initial value -- 0.0
    /// when there is no initializer (LRM 6.12: reals default to 0.0, never
    /// X), and a `shortreal` initializer rounded to single precision.
    #[test]
    fn real_members_are_inline_ieee_bit_cells_with_real_initial_values() {
        let design = compile_source(
            "module m; real r; shortreal sr = 1.0/3.0; realtime rt = 2.5; endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout = build_template_layout(&body).expect("real members lay out");
        assert_eq!(layout.slots.len(), 3);
        let expect = [
            (64u32, 0u64),
            (32, u64::from((1.0f32 / 3.0).to_bits())),
            (64, 2.5f64.to_bits()),
        ];
        for (slot, (width, bits)) in layout.slots.iter().zip(expect) {
            assert_eq!(slot.offset.class, SlotClass::Inline);
            assert_eq!(slot.offset.bit_width, width);
            assert!(
                matches!(slot.initial, Some(FourStateValue::Narrow(v)) if v == u128::from(bits)),
                "expected IEEE bits {bits:#x}, got {:?}",
                slot.initial
            );
        }
    }

    /// A fixed-size unpacked array of a 2-state non-integral type is a
    /// Memory slot of its stored bits -- 64-bit rows for `real`, `string`
    /// and `chandle`, 32-bit for `shortreal` -- whose rows start at 0
    /// (`initial` is `Some`, applied to every row by `reset_to_initial`); a
    /// 4-state integral array's rows start all-X (`initial: None`), and a
    /// multi-dimensional 2-state one starts at 0 too.
    #[test]
    fn non_integral_memory_rows_are_their_stored_bits_and_start_at_zero() {
        let design = compile_source(
            "module m; real r [3:0]; shortreal s [2]; string t [2]; logic [3:0] l [2];\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout = build_template_layout(&body).expect("lays out");
        let widths: Vec<u32> = layout.slots.iter().map(|s| s.offset.bit_width).collect();
        assert_eq!(widths, [64, 32, 64, 4]);
        for slot in &layout.slots[..3] {
            assert_eq!(slot.offset.class, SlotClass::Memory);
            assert!(slot.initial.is_some(), "2-state rows start at 0");
        }
        assert!(
            layout.slots[3].initial.is_none(),
            "4-state rows start all-X"
        );

        let nested = compile_source("module n; int a [2][3]; endmodule\n").expect("compiles");
        let body = nested
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout = build_template_layout(&body).expect("lays out");
        assert_eq!(layout.slots[0].offset.num_rows, 6);
        assert!(layout.slots[0].initial.is_some(), "2-state rows start at 0");
    }

    /// A memory's constant initializer becomes every row's initial value,
    /// lowest index first (`d[3:0] = '{1, 2, 3, 4}` puts 4 in row 0), and a
    /// non-constant one is rejected rather than dropped.
    #[test]
    fn memory_initializer_gives_every_row_its_value_lowest_index_first() {
        let design = compile_source(
            "module m; int d [3:0] = '{1, 2, 3, 4}; logic [3:0] x [2] = '{4'b10x1, 4'h5};\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout = build_template_layout(&body).expect("lays out");
        match &layout.slots[0].initial {
            Some(FourStateValue::Wide { aval, bval }) => {
                assert_eq!(aval, &[4, 3, 2, 1]);
                assert_eq!(bval, &[0, 0, 0, 0]);
            }
            other => panic!("expected per-row initial values, got {other:?}"),
        }
        match &layout.slots[1].initial {
            // 4'b10x1: aval 1011 (X has aval=1), bval 0010.
            Some(FourStateValue::Wide { aval, bval }) => {
                assert_eq!(aval, &[0b1011, 0x5]);
                assert_eq!(bval, &[0b0010, 0]);
            }
            other => panic!("expected per-row initial values, got {other:?}"),
        }

        let dynamic =
            compile_source("module n; int v; int a [2] = '{v, 1}; endmodule\n").expect("compiles");
        let body = dynamic
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        // A non-constant initializer lays out with default rows; the time-zero
        // var-init kernel assigns the real values (arrq12 step 2).
        build_template_layout(&body).expect("lays out with default rows");
    }

    /// A member wider than 65535 bits (LRM 1800-2023 6.9.1: an
    /// implementation's vector-length limit "shall be at least 65 536 (2^16)
    /// bits") builds with its true width and word count, never a clamped one.
    #[test]
    fn member_wider_than_65535_bits_keeps_its_true_width() {
        let design = compile_source("module m; logic [70000:0] huge; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("a 70001-bit member builds");
        assert_eq!(layout.slots.len(), 1);
        let offset = layout.slots[0].offset;
        assert_eq!(offset.bit_width, 70001);
        assert_eq!(offset.class, SlotClass::Wide);
        assert_eq!(offset.elem_word_count, 70001u32.div_ceil(64));
    }

    /// The same for a memory row's per-element width.
    #[test]
    fn memory_row_wider_than_65535_bits_keeps_its_true_width() {
        let design = compile_source("module m; logic [70000:0] huge_row [3:0]; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("rows of 70001 bits build");
        let offset = layout.slots[0].offset;
        assert_eq!(offset.bit_width, 70001);
        assert_eq!(offset.num_rows, 4);
        assert!(offset.row_stride_words >= 70001u32.div_ceil(64));
    }

    /// A member at the former 65535-bit boundary still builds with the
    /// exact word count.
    #[test]
    fn member_of_65535_bits_builds_with_correct_word_count() {
        let design = compile_source("module m; logic [65534:0] w; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");

        let layout = build_template_layout(&body).expect("a 65535-bit member must still build Ok");
        assert_eq!(layout.slots.len(), 1);
        let offset = layout.slots[0].offset;
        assert_eq!(offset.bit_width, 65535);
        assert_eq!(offset.class, SlotClass::Wide);
        assert_eq!(
            offset.elem_word_count,
            65535u32.div_ceil(64),
            "elem_word_count must be derived from the true 65535-bit width, not a clamped value"
        );
    }

    // -- sva T8: default clocking / default disable iff scoping --------

    /// The resolved default disable iff's referenced identifier's plain
    /// name, with no leading trivia (`Token::text()`, not `Node::text()`).
    fn disable_name(d: DefaultDisableDeclarationSyntax) -> String {
        d.expr()
            .syntax()
            .first_token()
            .expect("a disable iff expression has at least one token")
            .text()
            .to_string()
    }

    /// `u2`, the sole module instance directly inside `body`, as its own
    /// `InstanceBody` -- the shared scaffolding every nested-module test
    /// below uses to reach the nested scope.
    fn nested_instance_body<'d>(body: &Symbol<'d>) -> Symbol<'d> {
        body.members()
            .find(|m| m.kind() == SymbolKind::Instance)
            .expect("fixture has exactly one nested module instance")
            .instance_body()
            .expect("instance has a body")
    }

    /// 16.15's own `examples_with_default` module (quoted verbatim, minus
    /// the `property`/`assert property` statements T8 does not need: this
    /// task resolves `default_disable_of` at the *scope* level, never at a
    /// per-assertion level -- composing it against an assertion's own
    /// explicit `disable iff` clause, rules (a)/(b)/(c), is T27's job).
    /// `rst` is the module-level default; there is nothing nested here, so
    /// every scope in the module sees the same single default.
    #[test]
    fn examples_with_default_module_level_default_disable_resolves() {
        let design = compile_source(
            "module examples_with_default (input logic a, b, clk, rst, rst1);\n\
             default disable iff rst;\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();

        let (decl_scope, found) = default_disable_of(&body, &tree)
            .expect("no scoping error")
            .expect("examples_with_default declares a module-level default");
        assert_eq!(disable_name(found), "rst");
        assert_eq!(decl_scope.name(), "examples_with_default");
    }

    /// A module with no `default disable iff` anywhere resolves to `None`
    /// (16.15 rule (c): "no inference is performed").
    #[test]
    fn no_default_disable_declaration_resolves_to_none() {
        let design = compile_source("module m; bit clk, rst; endmodule\n")
            .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();

        assert!(
            default_disable_of(&body, &tree)
                .expect("no scoping error")
                .is_none()
        );
    }

    /// 16.15's first `m1`/`m2` nesting example (quoted verbatim): `m2` is a
    /// *nested* module declaration with no `default disable iff` of its
    /// own, instantiated inside `m1`. "The default disable condition rst1
    /// applies throughout the declaration of m1 and the nested declaration
    /// of m2" -- `m2`'s own scope must resolve to `m1`'s `rst1`, not `None`.
    #[test]
    fn nested_module_with_no_own_default_inherits_enclosing_default() {
        let design = compile_source(
            "module m1;\n\
             bit clk, rst1;\n\
             default disable iff rst1;\n\
             m2 u2();\n\
             module m2;\n\
                bit rst2;\n\
             endmodule\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let m1 = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let m2 = nested_instance_body(&m1);

        let (m1_scope, m1_found) = default_disable_of(&m1, &tree)
            .expect("no scoping error")
            .expect("m1 declares its own default");
        assert_eq!(disable_name(m1_found), "rst1");
        assert_eq!(m1_scope.name(), "m1");

        let (m2_scope, m2_found) = default_disable_of(&m2, &tree)
            .expect("no scoping error")
            .expect("m2 inherits m1's default -- it must not resolve to None");
        assert_eq!(disable_name(m2_found), "rst1");
        assert_eq!(
            m2_scope.name(),
            "m1",
            "the inherited default's signals resolve from ITS OWN declaring scope (m1), not m2's"
        );
    }

    /// 16.15's second `m1`/`m2` nesting example (quoted verbatim): `m2` now
    /// declares its *own* `default disable iff rst2`, which "overrides the
    /// default disable condition declared in m1" within `m2`'s own scope,
    /// while `m1`'s own assertions are unaffected.
    #[test]
    fn nested_module_with_own_default_overrides_enclosing_default() {
        let design = compile_source(
            "module m1;\n\
             bit clk, rst1;\n\
             default disable iff rst1;\n\
             m2 u2();\n\
             module m2;\n\
                bit rst2;\n\
                default disable iff rst2;\n\
             endmodule\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let m1 = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let m2 = nested_instance_body(&m1);

        let (_, m1_found) = default_disable_of(&m1, &tree)
            .expect("no scoping error")
            .expect("m1 declares its own default");
        assert_eq!(disable_name(m1_found), "rst1");

        let (m2_scope, m2_found) = default_disable_of(&m2, &tree)
            .expect("no scoping error")
            .expect("m2 declares its own, overriding default");
        assert_eq!(disable_name(m2_found), "rst2");
        assert_eq!(m2_scope.name(), "m2");
    }

    /// 16.15: "The scope does not extend into any instances of modules" --
    /// when `m2` is declared SEPARATELY at the top level (not nested inside
    /// `m1`) and merely instantiated there, `m1`'s default must not leak
    /// into `m2`'s own scope, even though the instantiation site is
    /// identical to the nested case above.
    #[test]
    fn instantiated_but_not_nested_module_does_not_inherit_default() {
        let design = compile_source(
            "module m2;\n\
                bit rst2;\n\
             endmodule\n\
             module m1;\n\
                bit clk, rst1;\n\
                default disable iff rst1;\n\
                m2 u2();\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let m1 = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let m2 = nested_instance_body(&m1);

        assert!(
            default_disable_of(&m2, &tree)
                .expect("no scoping error")
                .is_none(),
            "a separately top-level-declared module must not inherit the instantiating \
             module's default -- only textual nesting inherits"
        );
    }

    /// 16.15: "More than one default disable iff declaration within the
    /// same module ... shall be an error."
    #[test]
    fn duplicate_default_disable_in_same_scope_is_an_error() {
        let design = compile_source(
            "module m;\n\
             bit rst1, rst2;\n\
             default disable iff rst1;\n\
             default disable iff rst2;\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();

        let err = default_disable_of(&body, &tree).expect_err("duplicate must be rejected");
        assert!(matches!(err, DefaultScopeError::DuplicateDefaultDisable(name) if name == "m"));
    }

    /// 14.12 Example 2 ("Assigning an existing clocking to be the
    /// default"), adapted to a nested module (the construct 14.12 itself
    /// requires for inheritance to mean anything): `cpu` is a *nested*
    /// module with its own `default clocking busA;` reference form,
    /// pointing at a clocking block declared in the *enclosing* module --
    /// resolved by name in `cpu`'s own declaring scope.
    #[test]
    fn default_clocking_reference_form_resolves_named_block_in_declaring_scope() {
        let design = compile_source(
            "module processor;\n\
             bit clk1, clk2;\n\
             clocking busA @(posedge clk1); endclocking\n\
             clocking busB @(negedge clk2); endclocking\n\
             cpu u_cpu();\n\
             module cpu;\n\
                default clocking busA;\n\
             endmodule\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let processor = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let cpu = nested_instance_body(&processor);

        let cb = default_clocking_of(&cpu, &tree)
            .expect("no scoping error")
            .expect("cpu declares its own default clocking reference");
        assert_eq!(cb.name(), "busA");
        assert_eq!(cb.kind(), SymbolKind::ClockingBlock);
    }

    /// A module with no `default clocking` anywhere, nested or otherwise,
    /// resolves to `None`.
    #[test]
    fn no_default_clocking_declaration_resolves_to_none() {
        let design = compile_source(
            "module m; bit clk; clocking cb @(posedge clk); endclocking endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();

        assert!(
            default_clocking_of(&body, &tree)
                .expect("no scoping error")
                .is_none(),
            "a plain, non-default clocking block must not itself count as a default"
        );
    }

    /// A nested module with no `default clocking` of its own inherits the
    /// enclosing module's inline `default clocking cb @(...); endclocking`
    /// declaration (the inline form, not the reference form -- exercises
    /// the syntax-node-identity symbol recovery, not name lookup).
    #[test]
    fn nested_module_inherits_enclosing_inline_default_clocking() {
        let design = compile_source(
            "module m1;\n\
             bit clk;\n\
             default clocking cb @(posedge clk); endclocking\n\
             m2 u2();\n\
             module m2;\n\
             endmodule\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let m1 = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let m2 = nested_instance_body(&m1);

        let cb = default_clocking_of(&m2, &tree)
            .expect("no scoping error")
            .expect("m2 inherits m1's inline default clocking block");
        assert_eq!(cb.name(), "cb");
        assert_eq!(cb.kind(), SymbolKind::ClockingBlock);
    }

    /// 14.12 also permits an *anonymous* inline default clocking block
    /// (`default clocking @(posedge clk); endclocking`, no
    /// `clocking_identifier` at all -- used throughout 16.14.7's own
    /// worked examples). Its elaborated `ClockingBlock` member has an
    /// empty name, so name-based lookup cannot recover it -- this is the
    /// syntax-node-identity path's whole reason to exist.
    #[test]
    fn anonymous_inline_default_clocking_resolves_via_syntax_identity() {
        let design = compile_source(
            "module m1;\n\
             bit clk;\n\
             default clocking @(posedge clk); endclocking\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();

        let cb = default_clocking_of(&body, &tree)
            .expect("no scoping error")
            .expect("m1 declares its own anonymous default clocking block");
        assert_eq!(cb.name(), "");
        assert_eq!(cb.kind(), SymbolKind::ClockingBlock);
    }

    /// 14.12: "Specifying a default clocking more than once in the same
    /// module ... shall result in a compiler error."
    #[test]
    fn duplicate_default_clocking_in_same_scope_is_an_error() {
        let design = compile_source(
            "module m;\n\
             bit clk1, clk2;\n\
             clocking a @(posedge clk1); endclocking\n\
             clocking b @(posedge clk2); endclocking\n\
             default clocking a;\n\
             default clocking b;\n\
             endmodule\n",
        )
        .expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let tree = design.syntax_trees().into_iter().next().unwrap();

        let err = default_clocking_of(&body, &tree).expect_err("duplicate must be rejected");
        assert!(matches!(err, DefaultScopeError::DuplicateDefaultClocking(name) if name == "m"));
    }
}