vj-codegen 0.1.0

LLVM code generator of the vj SystemVerilog simulator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
//! Classes plan (`docs/superpowers/plans/2026-10-03-classes.md`), Task 1
//! (§0, D2): identifies the four `std`-package compiler intrinsics
//! (`process`, `semaphore`, `mailbox#(type T)`, `weak_reference#(type T)`)
//! slang builds unconditionally into every `Compilation`'s built-in `std`
//! package, before any user source is even parsed
//! (`rust/sv-lang-sys/vendor/source/ast/builtins/StdPackage.cpp`). None of
//! their methods have an SV-written body, so this crate treats all five as
//! compiler intrinsics dispatched through dedicated `sv_rt_process_*`/
//! `sv_rt_semaphore_*`/`sv_rt_mailbox_*`/`sv_rt_weakref_*` ABI calls instead
//! of the ordinary vtable path a user class's methods get -- later tasks
//! (13, 17, 18, 16) consume [`is_builtin_std_class`] at the call-site
//! resolution point this plan's §1.4 describes; this module exists now so
//! that identity check has one, single, independently-testable home from
//! the start.
use sv_lang::Symbol;
use sv_lang::kinds::{ExpressionKind, SymbolKind};

// --- Classes plan Task 5 (§1.3-1.4): flat classes -- object layout, `new`,
// fields, plain methods, `this`. Everything below this point is new in
// Task 5; the identity check above is Task 1's.
use std::cell::RefCell;
use std::collections::HashMap;

use inkwell::context::Context;
use inkwell::module::{Linkage, Module};
use inkwell::types::FunctionType;
use inkwell::values::{BasicMetadataValueEnum, FunctionValue, IntValue, PointerValue};
use inkwell::{AddressSpace, IntPredicate};

use sv_sim_runtime::objects_rt::{ObjOp, SV_RT_OBJ_SYMBOL};
use sv_sim_sim::netlist::ClassTemplateId;
use sv_sim_sim::objects::FieldSlot;
use sv_sim_sim::symid::{SymbolId, SymbolUid};

use crate::error::LoweringError;
use crate::expr::{LowerCtx, LoweredValue, entry_alloca, lower_expr};
use crate::func::CopyBack;
use crate::ops::OpBuilder;
use crate::types::TypeWidth;
use crate::value::{PackedValue, RealValue, ValueRepr};

/// One of the four `std`-package compiler intrinsics this crate special-
/// cases, as identified by [`is_builtin_std_class`]. `randomize()` (a bare
/// `std::randomize()` free function, not a class at all) is deliberately
/// not a variant here -- §0 notes it only so nothing double-implements it,
/// and it is not a class symbol `is_builtin_std_class` could ever be asked
/// about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StdIntrinsic {
    Process,
    Semaphore,
    Mailbox,
    WeakReference,
}

/// `Some(intrinsic)` iff `sym` is the real `ClassType`/`GenericClassDef`
/// `std`-package symbol itself -- walking `sym.parent()` repeatedly until a
/// `Package` named `"std"` is found (or the chain runs out), exactly as §0
/// specifies: a user's own same-named class declared at top level, inside a
/// different package, or even inside a package the user happens to call
/// `std` is never mistaken for the built-in, because it has no `std`-
/// `Package` ANCESTOR in its own scope chain -- this is scope identity, not
/// a string match on the class's name alone (the name match below is only a
/// cheap pre-filter: a hit still has to walk the chain and find the real
/// `std` package before this returns `Some`).
pub fn is_builtin_std_class(sym: &Symbol) -> Option<StdIntrinsic> {
    if !matches!(
        sym.kind(),
        SymbolKind::ClassType | SymbolKind::GenericClassDef
    ) {
        return None;
    }
    let intrinsic = match sym.name() {
        "process" => StdIntrinsic::Process,
        "semaphore" => StdIntrinsic::Semaphore,
        "mailbox" => StdIntrinsic::Mailbox,
        "weak_reference" => StdIntrinsic::WeakReference,
        _ => return None,
    };
    let mut scope = sym.parent();
    while let Some(s) = scope {
        if s.kind() == SymbolKind::Package && s.name() == "std" {
            return Some(intrinsic);
        }
        scope = s.parent();
    }
    None
}

fn elab_to_lowering(e: sv_sim_sim::netlist::ElabError, at: &sv_lang::Symbol) -> LoweringError {
    LoweringError::unsupported_at(&format!("{e}"), at)
}

/// One non-static property's location in [`ObjectLayout`]'s flat,
/// word-addressed field buffer (`sv_sim_sim::objects::alloc`'s own shape).
#[derive(Clone, Copy, Debug)]
pub struct ObjectField<'d> {
    pub sym: sv_lang::Symbol<'d>,
    pub slot: FieldSlot,
}

/// Task 5 (§1.3, Step 1), grown by Task 6 Step 1: one class template's
/// non-static-property layout -- the base-class chain's own declared
/// properties first (root/outermost base first, `netlist::classes::
/// base_chain`'s own ordering), THEN `class_sym`'s own declared properties,
/// in declaration order within each level. Every field gets a word offset
/// into the flat buffer [`sv_sim_sim::objects::alloc`]'s `field_words`
/// sizes, packed exactly like every other value this crate lowers (4-state
/// `(unk<<W)|val` under `cx.repr == FourState`, `sv-sim run`'s only
/// representation).
///
/// This base-first ordering is what makes [`read_field`]/[`write_field`]
/// correct for an INHERITED field with no further change to either: calling
/// `ObjectLayout::for_template(member.parent())` (the field's OWN declaring
/// class, read off the `Symbol` itself -- e.g. `base` for a field declared
/// in `base` but read through a `derived`-typed handle) walks the IDENTICAL
/// base-chain-then-own-fields recursion `ObjectLayout::for_template(derived)`
/// itself ran to place that same field, so both computations agree on its
/// `FieldSlot` -- self-consistent by construction, not by caching or by
/// threading a shared layout between the two call sites.
#[derive(Debug)]
pub struct ObjectLayout<'d> {
    fields: Vec<ObjectField<'d>>,
    /// Covergroup properties that share an inherited property's slot
    /// (19.4.1 `covergroup extends`): looked up by [`Self::slot_of`] but not
    /// storage of their own, so never initialized or walked.
    aliases: Vec<ObjectField<'d>>,
    total_words: usize,
}

/// A field's packed-word count under `repr` -- the exact shape
/// `store_packed_words`/`load_packed_words` below marshal through the
/// `sv_rt_obj` ABI's `*mut u64` buffer.
fn field_words(width: u32, repr: ValueRepr) -> usize {
    let bits = if repr == ValueRepr::FourState {
        width * 2
    } else {
        width
    };
    (bits as usize).div_ceil(64).max(1)
}

/// `f`'s word count in an object's flat field buffer, or a named, loud
/// [`LoweringError`] when its type is one this crate cannot yet store there
/// (see [`ObjectLayout::for_template`]'s doc comment). Shared by instance
/// fields and by `static` properties ([`ObjectLayout::for_statics`]), so the
/// two can never disagree on what is storable.
///
/// A queue, dynamic array or associative array property (constraints plan
/// C14, ledger XC-059) is one 64-bit collection handle word, registered with
/// the object heap ([`ObjectLayout::collection_field_slots`]) so it is freed
/// with the object and cloned by a shallow `new obj` copy through a two-phase
/// protocol that keeps the collections -> objects lock order.
///
/// A fixed-size unpacked array or an unpacked struct/union property (LRM
/// 1800-2023 7.4, 7.2; ledger XC-059) is one flat value of
/// `state::storage::storage_width` bits (the packed-struct order for a struct,
/// the lowest index least significant for an array), stored like any other
/// wide property. A class handle or collection nested in it is registered
/// with the object heap at its bit offset
/// ([`ObjectLayout::nested_handle_slots`]), so the heap releases it when the
/// object dies and a shallow `new obj` copy retains or clones it. An unpacked
/// union holding a handle has no storable form (`storage_width`) and is
/// refused by name.
fn property_words(f: &sv_lang::Symbol<'_>) -> Result<usize, LoweringError> {
    let ty = f
        .value_type()
        .ok_or_else(|| LoweringError::unsupported_at("class property has no type", f))?;
    if sv_sim_sim::state::storage::is_collection(&ty) {
        // A 64-bit handle, packed like every 64-bit value (class handles too):
        // the handle is word 0.
        return Ok(field_words(64, ValueRepr::FourState));
    }
    if sv_sim_sim::state::storage::is_unpacked_aggregate(&ty) || ty.is_unpacked_array() {
        let Some(width) = sv_sim_sim::state::storage::storage_width(&ty) else {
            return Err(LoweringError::unsupported_at(
                "a class property of an unpacked array, struct or union type with no \
                 fixed-width stored form is not supported (an unpacked union holding a \
                 class handle or collection, or an element of an unsupported type)",
                f,
            ));
        };
        let width = u32::try_from(width).map_err(|_| {
            LoweringError::unsupported_at("a class property wider than 2^32 bits", f)
        })?;
        return Ok(field_words(width, ValueRepr::FourState));
    }
    if !(ty.is_integral()
        || ty.is_floating()
        || ty.is_chandle()
        || ty.is_covergroup()
        || ty.is_virtual_interface()
        || ty.is_string()
        || ty.is_event()
        || ty.is_class())
    {
        return Err(LoweringError::unsupported_at(
            "class property of an unsupported type",
            f,
        ));
    }
    if ty.is_event() {
        // An event property is the 64-bit id of a runtime event object
        // (`class_events`).
        return Ok(field_words(64, ValueRepr::FourState));
    }
    Ok(field_words(ty.value_width(), ValueRepr::FourState))
}

/// The slot of the inherited covergroup instance that `f` (a covergroup
/// property declared by `covergroup extends`, LRM 19.4.1) replaces: the
/// earlier-level covergroup property of the same name.
fn extended_covergroup_slot<'d>(
    f: &sv_lang::Symbol<'d>,
    earlier: &[ObjectField<'d>],
) -> Option<FieldSlot> {
    let ty = f.value_type()?.canonical();
    if !ty.is_covergroup() || ty.covergroup_base_group().is_none() {
        return None;
    }
    earlier
        .iter()
        .rev()
        .find(|o| o.sym.name() == f.name() && o.sym.value_type().is_some_and(|t| t.is_covergroup()))
        .map(|o| o.slot)
}

impl<'d> ObjectLayout<'d> {
    /// Classifies `class_sym`'s own members, then every ancestor's own
    /// members (`netlist::classes::base_chain(class_sym)`, root/outermost
    /// first), and assigns each level's non-static properties a
    /// [`FieldSlot`] in that order (Task 6 Step 1: base-class fields first,
    /// so a derived object's prefix is bit-identical to its base's own
    /// layout, per 8.13/8.16). A property whose type this crate cannot yet
    /// store in the object heap (see [`property_words`]) is a named, loud
    /// [`LoweringError`], never a silently-dropped field, at whichever level
    /// in the chain declares it.
    pub fn for_template(class_sym: sv_lang::Symbol<'d>) -> Result<Self, LoweringError> {
        let base_ty = class_sym
            .as_type()
            .ok_or_else(|| LoweringError::unsupported_at("class symbol has no type", &class_sym))?;
        let mut levels: Vec<sv_lang::Symbol<'d>> = sv_sim_sim::netlist::base_chain(base_ty)
            .into_iter()
            .map(|t| t.as_symbol())
            .collect();
        levels.push(class_sym);

        let mut fields = Vec::new();
        let mut aliases = Vec::new();
        let mut offset = 0usize;
        for level_sym in levels {
            let members = sv_sim_sim::netlist::classify_members(level_sym)
                .map_err(|e| elab_to_lowering(e, &level_sym))?;
            for f in members.fields {
                let words = property_words(&f)?;
                // 19.4.1: `covergroup extends g1` redeclares the inherited
                // instance `g1` (slang gives it its own property); both
                // names are the one instance, so it shares the base's slot.
                if let Some(base_slot) = extended_covergroup_slot(&f, &fields) {
                    aliases.push(ObjectField {
                        sym: f,
                        slot: base_slot,
                    });
                    continue;
                }
                fields.push(ObjectField {
                    sym: f,
                    slot: FieldSlot { offset, words },
                });
                offset += words;
            }
        }
        Ok(Self {
            fields,
            aliases,
            total_words: offset,
        })
    }

    /// Classes plan Task 9 (8.9, 8.25): `class_sym`'s OWN `static`
    /// properties only (a static is not inherited storage: `Derived::n` and
    /// `Base::n` are two distinct statics only if each class declares its own,
    /// and one declared in `Base` lives in `Base`'s singleton) laid out
    /// exactly like [`Self::for_template`] lays out instance fields, so the
    /// same `FieldGet`/`FieldSet` marshaling serves both. The result is the
    /// shape of the one heap object [`static_singleton_handle`] allocates per
    /// class specialization.
    pub fn for_statics(class_sym: sv_lang::Symbol<'d>) -> Result<Self, LoweringError> {
        let members = sv_sim_sim::netlist::classify_members(class_sym)
            .map_err(|e| elab_to_lowering(e, &class_sym))?;
        let mut fields = Vec::new();
        let mut offset = 0usize;
        for f in members.statics {
            let words = property_words(&f)?;
            fields.push(ObjectField {
                sym: f,
                slot: FieldSlot { offset, words },
            });
            offset += words;
        }
        Ok(Self {
            fields,
            aliases: Vec::new(),
            total_words: offset,
        })
    }

    /// The `field_words` [`sv_sim_sim::objects::alloc`] needs for one object
    /// of this template.
    pub fn total_words(&self) -> usize {
        self.total_words
    }

    /// Every declared property, in declaration order -- [`lower_new_class`]'s
    /// own property-initialization loop (8.7).
    pub fn fields(&self) -> &[ObjectField<'d>] {
        &self.fields
    }

    /// Whether `member` is an alias property (see the `aliases` field).
    pub fn is_alias(&self, member: &sv_lang::Symbol<'_>) -> bool {
        let uid = member.uid();
        self.aliases.iter().any(|f| f.sym.uid() == uid)
    }

    /// `member`'s own [`FieldSlot`], by [`SymbolUid`] (never by position --
    /// a caller may hold a member `Symbol` discovered independently of this
    /// layout's own `for_template` walk, e.g. `expr.rs`'s `MemberAccess`
    /// arm).
    pub fn slot_of(&self, member: &sv_lang::Symbol<'_>) -> Option<FieldSlot> {
        let uid = member.uid();
        self.fields
            .iter()
            .chain(&self.aliases)
            .find(|f| f.sym.uid() == uid)
            .map(|f| f.slot)
    }

    /// Every field whose type is itself a class handle -- [`sv_sim_sim::
    /// objects::release`]'s recursive free walk (Task 3's stub parameter,
    /// wired to the real computation here, per this task's own Step 6).
    pub fn handle_field_slots(&self) -> Vec<FieldSlot> {
        self.fields
            .iter()
            .filter(|f| f.sym.value_type().is_some_and(|t| t.is_class()))
            .map(|f| f.slot)
            .collect()
    }

    /// Every field that is a queue / dynamic array / associative array
    /// (ledger XC-059) -- [`sv_sim_sim::objects::register_collection_fields`].
    pub fn collection_field_slots(&self) -> Vec<FieldSlot> {
        self.fields
            .iter()
            .filter(|f| {
                f.sym
                    .value_type()
                    .is_some_and(|t| sv_sim_sim::state::storage::is_collection(&t))
            })
            .map(|f| f.slot)
            .collect()
    }

    /// Every class handle and collection handle held inside a struct or
    /// fixed-array property, at its bit offset of the property's value
    /// (ledger XC-059) -- [`sv_sim_sim::objects::register_nested_handles`].
    pub fn nested_handle_slots(&self) -> Vec<sv_sim_sim::objects::NestedHandle> {
        use crate::collections::{HandleKind, handle_offsets};
        let mut out = Vec::new();
        for f in &self.fields {
            let Some(ty) = f.sym.value_type() else {
                continue;
            };
            // A bare handle property has its own whole-field registration.
            if ty.is_class() || sv_sim_sim::state::storage::is_collection(&ty) {
                continue;
            }
            // The registered slots are unconditional; a tag-guarded handle
            // (a tagged union member) has no sound registration.
            let slots = handle_offsets(&ty);
            assert!(
                slots.iter().all(|s| s.guards.is_empty()),
                "a class property holding a tagged union with a class or collection member"
            );
            out.extend(
                slots
                    .into_iter()
                    .map(|s| sv_sim_sim::objects::NestedHandle {
                        slot: f.slot,
                        bit: s.off,
                        coll: s.kind == HandleKind::Coll,
                    }),
            );
        }
        out
    }

    /// Every `rand`/`randc` property (LRM 18.4), in layout order (base-class
    /// properties first) -- what [`sv_sim_sim::objects::register_rand_props`]
    /// stores per template, and the index space of each object's
    /// `rand_mode` bits.
    pub fn rand_props(&self) -> Vec<sv_sim_sim::objects::RandProp> {
        use sv_sim_sim::objects::{RandKind, RandProp};
        self.fields
            .iter()
            .filter_map(|f| {
                // A struct with a `rand` member is a random property whatever
                // its own qualifier (LRM 18.4); its `randc` members keep their
                // per-leaf cycles (`constraints::registry`).
                let kind = match f.sym.class_property_rand_mode() {
                    sv_lang::RandMode::None => {
                        if !sv_sim_sim::constraints::build::property_is_random(f.sym) {
                            return None;
                        }
                        RandKind::Rand
                    }
                    sv_lang::RandMode::Rand => RandKind::Rand,
                    sv_lang::RandMode::RandC => RandKind::RandC,
                };
                Some(RandProp { slot: f.slot, kind })
            })
            .collect()
    }
}

// --- Classes plan Task 7 (§1.3 "Vtables", §1.4 step 2, LRM 8.14/8.20-8.22):
// virtual-method slot assignment. [`VtableLayout`] mirrors [`ObjectLayout`]'s
// own "recomputed fresh from the base chain every time, never cached or
// threaded through a shared map" shape, for the identical reason that type
// documents: a caller may hold a member `Symbol` discovered independently of
// any one class's own walk (a call site's statically-resolved callee, which
// may be declared several levels up an entirely different `Symbol` than the
// one `register_virtual_impls` last walked).

/// One method member's virtual-dispatch shape, classified by
/// [`classify_virtual_member`] -- shared by [`VtableLayout::for_template`]'s
/// own slot-assignment walk and [`is_virtual_method`]'s call-site check, so
/// the two can never disagree on what counts as virtual.
struct VirtualMember<'d> {
    /// The symbol this member overrides, ONE level up the chain
    /// (`Symbol::subroutine_override`/`method_prototype_override`) -- `None`
    /// at the level that first introduces this virtual method (whether a
    /// genuine hierarchy root or a derived class adding a brand-new virtual
    /// method of its own).
    overrides: Option<sv_lang::Symbol<'d>>,
    /// The real, bodied `Subroutine` this LEVEL contributes for the method --
    /// `None` only for a still-unimplemented `pure virtual` prototype (8.21):
    /// [`VtableLayout::for_template`]'s own per-slot bookkeeping leaves such
    /// a slot for a later (more-derived) level to fill in, and a class
    /// template actually reachable via a `new()` site can never have one
    /// still `None` once every level up to it has been walked (the frontend
    /// already rejects instantiating an abstract class, D9).
    implementation: Option<sv_lang::Symbol<'d>>,
}

/// Classifies one `classify_members(..).methods` entry (either a plain
/// `Subroutine` or, for an `extern`/pure-virtual in-class declaration, the
/// raw `MethodPrototype`) for virtual dispatch. `Ok(None)` for a member that
/// is not virtual at all (an ordinary non-virtual method, or a `static`
/// method -- 8.10's methods never have a receiver to dispatch on, so they
/// are never virtual regardless of any flag) -- not this function's concern,
/// the caller's own direct-call path handles it unchanged. Every other
/// `SymbolKind` `classify_members` could hand back (there are exactly two:
/// `Subroutine`, `MethodPrototype`) falls to a named, loud [`LoweringError`]
/// -- never a silent default -- since `classify_members`'s own contract
/// guarantees `methods` contains only these two kinds.
///
/// Deviation (found running this task's own `abstract_pure_virtual.sv`
/// fixture, not in the preflight corrections): a `Subroutine`-kind `m`'s own
/// `subroutine_this_var()` is deceptively `None` NOT ONLY for a genuine
/// `static` method, but ALSO for the synthesized STUB slang builds for a
/// still-pure `pure virtual` prototype (`Symbol::method_prototype_
/// subroutine()`'s own doc comment: "a synthesized stub for an
/// unimplemented pure method") -- confirmed live, a dot-call through a
/// base-typed handle to a pure-virtual method resolves `call_subroutine()`
/// to EXACTLY this stub (`Subroutine`-kind, `this_var() == None`), the
/// SAME shape a genuinely static method has, yet the stub is unambiguously
/// virtual (its own `MethodPrototype`, reachable via `Symbol::subroutine_
/// prototype()`, reports `method_prototype_is_virtual() == true`). So a
/// `Subroutine`'s own `this_var` alone can never distinguish "static" from
/// "pure-virtual stub" -- `subroutine_prototype()` is checked FIRST, before
/// any `this_var` check, and takes over classification via the SAME
/// `MethodPrototype`-flags logic the raw-prototype arm already uses,
/// whichever shape `m` itself arrived as.
fn classify_virtual_member<'d>(
    m: sv_lang::Symbol<'d>,
) -> Result<Option<VirtualMember<'d>>, LoweringError> {
    use sv_lang::MethodFlags;
    let proto = match m.kind() {
        SymbolKind::MethodPrototype => Some(m),
        SymbolKind::Subroutine => m.subroutine_prototype(),
        other => {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "internal: {other:?} is not one of the two SymbolKinds \
                     (Subroutine/MethodPrototype) classify_members's own contract guarantees \
                     for a class's `methods` list"
                ),
                &m,
            ));
        }
    };
    if let Some(proto) = proto {
        if !proto.method_prototype_is_virtual() {
            return Ok(None);
        }
        let overrides = proto.method_prototype_override();
        let implementation = if proto.method_prototype_flags().contains(MethodFlags::PURE) {
            None
        } else if m.kind() == SymbolKind::Subroutine && m.subroutine_this_var().is_some() {
            // `m` itself is the real, bodied implementation (an `extern`
            // method's own out-of-block body, reached directly through an
            // ordinary dot call that "resolves all the way through" --
            // `VtableLayout`'s own doc comment) -- no need to re-derive it
            // via `proto.method_prototype_subroutine()`.
            Some(m)
        } else {
            Some(proto.method_prototype_subroutine().ok_or_else(|| {
                LoweringError::unsupported_at(
                    "internal: a non-pure virtual method prototype has no resolved \
                     out-of-block implementation -- slang's own frontend should never leave \
                     this unresolved once the design compiles at all",
                    &m,
                )
            })?)
        };
        return Ok(Some(VirtualMember {
            overrides,
            implementation,
        }));
    }
    // No associated prototype at all: an ordinary in-body method, or (8.10)
    // a genuine `static` method -- the latter has no implicit receiver at
    // all, so it can never be virtual even if some stray flag combination
    // claimed otherwise.
    if m.subroutine_this_var().is_none() {
        return Ok(None);
    }
    let overrides = m.subroutine_override();
    // 8.14: a method with the SAME name/signature as a virtual base method
    // is automatically virtual whether or not it repeats the `virtual`
    // keyword -- `subroutine_override().is_some()` alone already proves
    // that (slang only sets it once the override relationship is
    // confirmed), so this check does not need (and must not require)
    // `MethodFlags::VIRTUAL` to also be set.
    let is_virtual = m.subroutine_flags().contains(MethodFlags::VIRTUAL) || overrides.is_some();
    if !is_virtual {
        return Ok(None);
    }
    Ok(Some(VirtualMember {
        overrides,
        implementation: Some(m),
    }))
}

/// Classes plan Task 7 (§1.3 "Vtables"): one class template's virtual-method
/// slot table, built by walking the base-class chain root-first then
/// `class_sym`'s own level (the identical traversal [`ObjectLayout::
/// for_template`] uses for fields) -- a virtual method keeps the SAME slot
/// number at every level of the hierarchy that sees it (the level that
/// FIRST introduces it, whether that is a genuine root or a derived class
/// adding a new virtual method of its own, fixes the number; every override
/// found at a later level reuses it), so two different concrete descendants
/// of one common ancestor always agree on that ancestor's own methods'
/// slot numbers -- computed independently by each one's own walk, never by
/// sharing one hierarchy-wide table (the same "recomputed, not cached"
/// design [`ObjectLayout`] already documents, for the identical reason: a
/// caller may hold a `Symbol` declared at any level, not just `class_sym`'s
/// own).
///
/// Classes plan Task 8 (§1.3's own "that complexity is confined to
/// interface-class method resolution, Task 8", LRM 8.26/8.26.3/8.26.5):
/// `for_template`'s walk, after the base-chain-then-own-level pass above,
/// ALSO aliases every INTERFACE method `class_sym` (transitively) implements
/// into the SAME slot its own matching-by-NAME virtual method already
/// occupies -- an interface class contributes no storage/vtable slot of its
/// own (8.26.1: it declares only pure virtual method PROTOTYPES, never a
/// body, and 8.26.5's "casting and object reference assignment" is
/// representation-free, so there is nothing for an interface class to own
/// at the object-layout/vtable level in the first place), only a NAME an
/// implementing hierarchy's own slot is also reachable under. This is keyed
/// by name identity, deliberately NOT by `Symbol::subroutine_override()`/
/// `method_prototype_override()` the way an ordinary base-class override
/// is: verified live against `ClassSymbols.cpp::ClassType::handleImplements`
/// (the non-interface, "a class implements an interface" branch) that it
/// never calls `setOverride`/`MethodPrototypeSymbol::setOverride` for this
/// relationship at all (unlike the sibling `isInterface` branch, used for
/// one interface class `extends`ing another, which DOES) -- so the override
/// chain [`classify_virtual_member`] already walks for ordinary inheritance
/// has nothing to find here, and name (SV classes never overload a method
/// name within one scope, so this is unambiguous) is the only signal slang
/// itself uses too (`handleImplements`'s own `find(method.name)`).
pub struct VtableLayout<'d> {
    /// Slot `i`'s most-derived implementation VISIBLE AT `class_sym`'s OWN
    /// level -- `None` only when `class_sym` itself is abstract and has not
    /// (yet, at this level) implemented a pure virtual method it inherited;
    /// never `None` once `class_sym` is a template actually reachable via a
    /// `new()` site (see [`VirtualMember::implementation`]'s own doc
    /// comment).
    slots: Vec<Option<sv_lang::Symbol<'d>>>,
    /// Every virtual method symbol anywhere in the walked chain -- BOTH an
    /// in-class raw member (a plain `Subroutine`, or an `extern`/pure
    /// `MethodPrototype`) AND, when that member is a `MethodPrototype`, its
    /// own resolved out-of-block `Subroutine` too (an ordinary dot call
    /// through an object handle, e.g. `obj.sum()`, resolves ALL the way
    /// through to that real `Subroutine` even for an `extern`-declared
    /// method -- `MemberAccessExpression` binding's own documented
    /// difference from a `super.`/bare/`Class::`-style colon lookup, see
    /// [`resolve_implicit_this_instance_method`]'s doc comment -- so a call
    /// site's own `callee` may be either shape depending on how it was
    /// written, and both must resolve to the identical slot) -- keyed by
    /// [`SymbolUid::uid`], mapped to its slot number.
    by_uid: HashMap<SymbolId, usize>,
    /// Classes plan Task 9 (8.25): every `by_uid` key's DECLARING class's
    /// specialization key ([`sv_sim_sim::netlist::class_specialization_key`]).
    /// Every specialization of one generic class shares one `uid` for each of
    /// its members (`SymbolUid::uid` is the hierarchical position, not the
    /// specialization), so `Base#(int)::get` and `Base#(string)::get` are
    /// ONE `by_uid` key in the process-wide [`VIRTUAL_IMPLS`] registry unless
    /// it also carries which specialization the member belongs to --
    /// `(uid, declared_in[uid])` is that registry's key.
    declared_in: HashMap<SymbolId, String>,
}

impl<'d> VtableLayout<'d> {
    /// Walks `class_sym`'s base chain (root first, [`sv_sim_sim::netlist::
    /// base_chain`]) then `class_sym`'s own level, assigning/reusing slot
    /// numbers exactly as this type's own doc comment describes. Never
    /// itself enforces "every slot is implemented" -- `class_sym` may be a
    /// genuinely abstract ancestor (reachable only because some concrete
    /// descendant's own base chain includes it, `run.rs`'s own `ancestor_
    /// types` extension), for which a still-`None` slot is correct, not a
    /// bug; [`register_virtual_impls`] is the one place that walks a
    /// template actually meant to be instantiated and consumes
    /// [`Self::impls`] trusting every slot is filled.
    pub fn for_template(class_sym: sv_lang::Symbol<'d>) -> Result<Self, LoweringError> {
        let base_ty = class_sym
            .as_type()
            .ok_or_else(|| LoweringError::unsupported_at("class symbol has no type", &class_sym))?;
        let mut levels: Vec<sv_lang::Symbol<'d>> = sv_sim_sim::netlist::base_chain(base_ty)
            .into_iter()
            .map(|t| t.as_symbol())
            .collect();
        levels.push(class_sym);

        let mut slots: Vec<Option<sv_lang::Symbol<'d>>> = Vec::new();
        let mut by_uid: HashMap<SymbolId, usize> = HashMap::new();
        let mut declared_in: HashMap<SymbolId, String> = HashMap::new();
        // Classes plan Task 8: `name -> slot`, built alongside `by_uid` below
        // (never a second walk) -- the one additional index the interface-
        // aliasing pass after this loop needs, see this type's own doc
        // comment. Overwritten, never merged, as a later (more derived)
        // level's own member of the SAME name is walked -- SV never
        // overloads a method name within one class scope, so "the slot the
        // LAST write left here" is always the single, unambiguous answer by
        // the time this loop finishes.
        let mut name_to_slot: HashMap<&'d str, usize> = HashMap::new();
        for &level_sym in &levels {
            let members = sv_sim_sim::netlist::classify_members(level_sym)
                .map_err(|e| elab_to_lowering(e, &level_sym))?;
            let level_key = specialization_key_of_symbol(&level_sym)?;
            for m in members.methods {
                let Some(vm) = classify_virtual_member(m)? else {
                    continue;
                };
                let slot = match vm.overrides {
                    Some(base_m) => *by_uid.get(&base_m.uid()).ok_or_else(|| {
                        LoweringError::unsupported_at(
                            "internal: an overriding virtual method's own base method has no \
                             vtable slot yet -- the base class's own level must be walked \
                             before this one, and VtableLayout::for_template's own base-chain \
                             walk guarantees that ordering",
                            &m,
                        )
                    })?,
                    None => {
                        let s = slots.len();
                        slots.push(None);
                        s
                    }
                };
                by_uid.insert(m.uid(), slot);
                declared_in.insert(m.uid(), level_key.clone());
                if m.kind() == SymbolKind::MethodPrototype
                    && let Some(real) = m.method_prototype_subroutine()
                {
                    by_uid.insert(real.uid(), slot);
                    declared_in.insert(real.uid(), level_key.clone());
                }
                // Recorded regardless of whether `vm.implementation` is
                // filled YET -- deliberately not nested inside the `if let
                // Some(impl_sym)` below. LRM 8.26's own worked shape (a
                // `virtual class Base implements IFoo; pure virtual
                // function ... get_val(); endclass` that defers the actual
                // body to a later-processed DESCENDANT level, verified live
                // against Verilator 5.032 to be legal SV, not merely an
                // academic case) means `VtableLayout::for_template(Base)`,
                // called on ITS OWN (one-level) walk by `register_virtual_
                // impls` the same way every ancestor template is, must
                // still be able to find THIS slot by name for the
                // interface-aliasing pass below even though `slots[slot]`
                // stays `None` here -- `register_virtual_impls`'s own
                // `let Some(impl_sym) = layout.slots[slot] else { continue
                // }` guard already handles "found the slot, but this
                // LEVEL'S OWN layout has no implementation for it yet"
                // correctly (contributes nothing from THIS walk, which is
                // right: the real implementation is contributed by whatever
                // concrete descendant's own, separate `for_template` walk
                // fills it in).
                name_to_slot.insert(m.name(), slot);
                if let Some(impl_sym) = vm.implementation {
                    slots[slot] = Some(impl_sym);
                }
            }
        }
        // Classes plan Task 8 (LRM 8.26, 8.26.3, 8.26.5): every interface
        // `class_sym` (transitively, through its own `implements` clause,
        // through a base class's, or through another implemented
        // interface's own `extends`) implements joins the same slot space
        // by NAME (this type's own doc comment explains why name, not an
        // override-chain walk, is correct here).
        //
        // Deviation from `netlist::flattened_interfaces`'s own doc comment
        // (found running THIS task's own deferred-to-a-descendant fixture,
        // not assumed): `Type::class_implemented_interfaces()` flattens
        // through another implemented interface's own `extends` chain
        // (confirmed live: `ic2 extends ic1; class x implements ic2;`
        // gives `x`'s own call `class_implemented_interfaces()` BOTH
        // `ic2` AND `ic1`), but it does NOT also walk a BASE CLASS's own
        // `implements` clause -- `ClassType::implementsIfaces` is
        // populated once, only from `handleImplements`, which runs only
        // when `class_sym` ITSELF has an `implements` clause; a
        // `Derived extends Base` with no `implements` clause of its own,
        // whose `Base` directly `implements IFoo`, has an EMPTY
        // `class_implemented_interfaces()` on `Derived`'s own type
        // (confirmed live: `for_template(Derived)` saw `[]`, `for_
        // template(Base)` saw `["IFoo"]`) even though 8.26's own text
        // ("A subclass implicitly implements all of the interface
        // classes implemented by its superclass") makes `Derived` an
        // `IFoo` too. So this walks EVERY level already collected into
        // `levels` above (base chain + `class_sym` itself) and unions
        // each one's own `flattened_interfaces`, deduplicated by `Symbol`
        // identity (`PartialEq`, pointer-equal per `Type::class_
        // implemented_interfaces`'s own doc comment) -- never relying on
        // a single leaf-level call to already include a base's own.
        let mut ifaces: Vec<sv_lang::Type<'d>> = Vec::new();
        for &level_sym in &levels {
            let level_ty = level_sym.as_type().ok_or_else(|| {
                LoweringError::unsupported_at("class symbol has no type", &level_sym)
            })?;
            for iface_ty in sv_sim_sim::netlist::flattened_interfaces(level_ty) {
                if !ifaces
                    .iter()
                    .any(|seen| seen.as_symbol() == iface_ty.as_symbol())
                {
                    ifaces.push(iface_ty);
                }
            }
        }
        for iface_ty in ifaces {
            let iface_sym = iface_ty.as_symbol();
            let iface_key = specialization_key_of_symbol(&iface_sym)?;
            let members = sv_sim_sim::netlist::classify_members(iface_sym)
                .map_err(|e| elab_to_lowering(e, &iface_sym))?;
            for p in members.methods {
                // 8.26.1: "An interface class shall only contain pure
                // virtual methods" -- every one of `classify_members`'s
                // `methods` for a genuine interface class symbol is
                // therefore always a `MethodPrototype` (never a bodied
                // in-class `Subroutine`, which only an ordinary ClassType
                // can declare at all); a `Subroutine` reaching this arm
                // would mean `iface_ty.as_symbol()` was not actually the
                // interface-class symbol this function assumed -- an
                // internal inconsistency, never a reachable SV-source
                // outcome for a design that compiled at all, so this is a
                // loud, named error rather than a silent skip or a panic.
                if p.kind() != SymbolKind::MethodPrototype {
                    return Err(LoweringError::unsupported_at(
                        &format!(
                            "internal: {:?} is not the MethodPrototype kind every member of an \
                             interface class's own `methods` (classify_members) must be (LRM \
                             8.26.1: an interface class contains only pure virtual methods)",
                            p.kind()
                        ),
                        &p,
                    ));
                }
                let Some(&slot) = name_to_slot.get(p.name()) else {
                    return Err(LoweringError::unsupported_at(
                        &format!(
                            "internal: interface class method `{}` has no matching virtual \
                             method of the same name anywhere in this class's own hierarchy \
                             (base chain + own level) -- `name_to_slot` above records a slot \
                             for EVERY virtual method name walked, pure or implemented (LRM \
                             8.26's own \"a virtual class shall define or inherit a pure \
                             virtual method prototype OR virtual method implementation\" -- \
                             verified live against Verilator 5.032 that the deferred-to-a-\
                             descendant shape is legal SV, not merely an implemented-immediately \
                             one), so a design whose `implements` clause slang itself accepted \
                             should never reach this",
                            p.name()
                        ),
                        &p,
                    ));
                };
                by_uid.insert(p.uid(), slot);
                declared_in.insert(p.uid(), iface_key.clone());
                if let Some(stub) = p.method_prototype_subroutine() {
                    by_uid.insert(stub.uid(), slot);
                    declared_in.insert(stub.uid(), iface_key.clone());
                }
            }
        }
        Ok(Self {
            slots,
            by_uid,
            declared_in,
        })
    }

    /// The number of virtual-method slots in this hierarchy (0 for a class
    /// hierarchy with no virtual methods at all).
    pub fn len(&self) -> usize {
        self.slots.len()
    }

    pub fn is_empty(&self) -> bool {
        self.slots.is_empty()
    }

    /// `member`'s own slot number, if `member` (an in-class raw member or
    /// its resolved out-of-block `Subroutine`) is anywhere in this walk's
    /// chain -- `None` for a method from an unrelated hierarchy, or a
    /// non-virtual method.
    pub fn slot_of(&self, member: &sv_lang::Symbol<'_>) -> Option<usize> {
        self.by_uid.get(&member.uid()).copied()
    }

    /// Slot `i`'s implementation at `class_sym`'s OWN level, in slot order.
    pub fn impls(&self) -> &[Option<sv_lang::Symbol<'d>>] {
        &self.slots
    }
}

/// Classes plan Task 7: whether `callee` (a call site's own statically-
/// resolved callee symbol, as `call_subroutine()` gives it -- a plain
/// `Subroutine`, or, for a `super.`/bare/`Class::`-style colon lookup, the
/// raw in-class `MethodPrototype`) is virtual at all (8.20/8.14) --
/// [`virtual_call_arms`]'s own first check, and `func.rs`'s/`expr.rs`'s
/// shared entry point for "is this a method call AT ALL" never needs this:
/// a non-virtual callee simply takes the existing direct-call path
/// unchanged.
fn is_virtual_method(callee: &sv_lang::Symbol<'_>) -> Result<bool, LoweringError> {
    Ok(classify_virtual_member(*callee)?.is_some())
}

// --- Whole-design `ClassTemplateId` lookup (§1.4's call-site resolution
// needs the SAME id `pipeline::build_pipeline`'s own one-shot class
// discovery/registration pass -- `register_template` below -- already
// assigned via `netlist::assign_class_template_ids`, without threading a
// shared map through every `LowerCtx` construction site in `func.rs`/
// `process_lower.rs`/`dpi.rs`). A thread-local, not a process-wide global:
// mirrors `sv_sim_sim::process::cfg::set_source_session`'s own established
// "whole-compile-scoped thread-local, set once at the pipeline's own entry
// point" shape -- and, unlike a process-wide global, never lets two
// `cargo test` tests running on different threads (sv-lang's own `SymbolId`
// is hierarchical-PATH TEXT, per `symid.rs`'s own module doc, so two
// unrelated compiles of structurally identical source would otherwise
// collide) cross-contaminate each other's class-template ids.
//
// Classes plan Task 9 (8.25): keyed by [`sv_sim_sim::netlist::
// class_specialization_key`], NOT by [`SymbolUid::uid`] -- every
// specialization of one generic class (and every `Inner` of a differently-
// specialized `Outer#(...)`) shares one `uid`, so a uid-keyed map silently
// merged `Box#(int)` and `Box#(string)` into one id.
#[derive(Default)]
struct ClassIdRegistry {
    ids: HashMap<String, ClassTemplateId>,
    /// Ids handed out by [`static_singleton_template_id`] after registration.
    next_light: u32,
}

/// Where [`static_singleton_template_id`]'s ids start: far above any dense
/// id `assign_class_template_ids` hands out (one per distinct `new()`-
/// reachable class), so the two ranges can never meet.
const LIGHT_TEMPLATE_ID_BASE: u32 = 0x4000_0000;

thread_local! {
    static CLASS_TEMPLATE_IDS: RefCell<ClassIdRegistry> = RefCell::new(ClassIdRegistry::default());
}

/// Clears every class registry this module keeps ([`CLASS_TEMPLATE_IDS`],
/// [`VIRTUAL_IMPLS`]). `pipeline::build_pipeline` calls it before its class
/// sub-pass: both are thread-local, and a thread that compiles twice (every
/// `cargo test` worker does) must not carry the first compile's
/// specializations into the second.
pub fn reset_class_registries() {
    CLASS_TEMPLATE_IDS.with(|c| *c.borrow_mut() = ClassIdRegistry::default());
    VIRTUAL_IMPLS.with(|c| c.borrow_mut().clear());
    sv_sim_sim::process::cfg::reset_aborting_virtuals();
    crate::classes_randomize::reset_failed_programs();
}

/// `class_sym`'s [`sv_sim_sim::netlist::class_specialization_key`].
fn specialization_key_of_symbol(sym: &sv_lang::Symbol<'_>) -> Result<String, LoweringError> {
    let ty = sym
        .as_type()
        .ok_or_else(|| LoweringError::unsupported_at("class symbol has no type", sym))?;
    Ok(sv_sim_sim::netlist::class_specialization_key(ty))
}

/// `pipeline::build_pipeline`'s own class sub-pass calls this once per
/// discovered class template, right after computing its [`ObjectLayout`] --
/// see [`register_template`], the one caller. A loud error if `key` was
/// already registered under a DIFFERENT id: two distinct specializations
/// whose keys print identically (`class_specialization_key`'s own residual
/// ambiguity) must never be silently merged into one set of object layouts.
fn note_class_template_id(
    key: String,
    id: ClassTemplateId,
    at: &sv_lang::Symbol<'_>,
) -> Result<(), LoweringError> {
    CLASS_TEMPLATE_IDS.with(|c| {
        let mut c = c.borrow_mut();
        match c.ids.get(&key) {
            Some(&prev) if prev != id => Err(LoweringError::unsupported_at(
                &format!(
                    "two distinct class specializations (ClassTemplateId {} and {}) have the \
                     identical specialization key `{key}` -- they cannot be told apart by \
                     name and parameter binding, so they would silently share one object \
                     layout and method set",
                    prev.0, id.0
                ),
                at,
            )),
            _ => {
                c.ids.insert(key, id);
                Ok(())
            }
        }
    })
}

/// The [`ClassTemplateId`] [`register_template`] assigned `class_sym`, for
/// any later call site on the SAME thread (`lower_new_class`, a method's
/// own mangling) to consult. A named, loud [`LoweringError`] -- never a
/// panic, never a fabricated id -- if nothing registered it: this is always
/// an internal pipeline-ordering bug (the whole-design class sub-pass must
/// run, for every class reachable via a `new()` site, before any body that
/// `new()`s one is ever lowered), not a reachable SV-source-level failure.
pub fn class_template_id_of(sym: &sv_lang::Symbol<'_>) -> Result<ClassTemplateId, LoweringError> {
    let key = specialization_key_of_symbol(sym)?;
    CLASS_TEMPLATE_IDS
        .with(|c| c.borrow().ids.get(&key).copied())
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                "internal: this class's ClassTemplateId was never registered before codegen \
                 reached a `new()` site for it -- `pipeline::build_pipeline`'s own whole-design \
                 class discovery/registration pass must run first",
                sym,
            )
        })
}

/// The heap [`ClassTemplateId`] of `class_sym`'s static-property singleton
/// object ([`static_singleton_handle`]). Always a "light" id, in a range no
/// `new()`-reachable class's dense id can reach, and under its own registry
/// key (`static|<specialization key>`) -- never the class's own id: the
/// singleton's field layout ([`ObjectLayout::for_statics`]) is a different
/// shape from an instance's, and a class that is never `new()`'d (legal SV:
/// `Reg#(32)::n` needs no object, LRM 8.10/8.25) has no dense id at all.
pub(crate) fn static_singleton_template_id(
    class_sym: &sv_lang::Symbol<'_>,
) -> Result<ClassTemplateId, LoweringError> {
    let key = format!("static|{}", specialization_key_of_symbol(class_sym)?);
    Ok(CLASS_TEMPLATE_IDS.with(|c| {
        let mut c = c.borrow_mut();
        if let Some(&id) = c.ids.get(&key) {
            return id;
        }
        let id = ClassTemplateId(LIGHT_TEMPLATE_ID_BASE + c.next_light);
        c.next_light += 1;
        sv_sim_sim::objects::register_static_singleton_key(key.trim_start_matches("static|"), id);
        c.ids.insert(key, id);
        id
    }))
}

/// `pipeline::build_pipeline`'s class sub-pass, one call per
/// `(ClassTemplateId, representative Symbol)` pair its own whole-design
/// `netlist::assign_class_template_ids` discovery produced: computes
/// `class_sym`'s [`ObjectLayout`], registers its handle-typed fields with
/// [`sv_sim_sim::objects::register_handle_fields`] (Task 3's stub parameter,
/// now wired to the real computation -- this task's own Step 6), and notes
/// `id` for [`class_template_id_of`]. Returns the computed layout so the
/// caller can also size/declare/lower the class's methods without
/// recomputing it.
pub fn register_template<'d>(
    id: ClassTemplateId,
    class_sym: sv_lang::Symbol<'d>,
) -> Result<ObjectLayout<'d>, LoweringError> {
    register_template_in(id, class_sym, &[])
}

/// [`register_template`] with `universe`, every `(id, class)` of the design
/// (the classes an object can be an instance of), so a constraint's call of a
/// virtual function through a handle can offer each class's implementation.
pub fn register_template_in<'d>(
    id: ClassTemplateId,
    class_sym: sv_lang::Symbol<'d>,
    universe: &[(ClassTemplateId, sv_lang::Symbol<'d>)],
) -> Result<ObjectLayout<'d>, LoweringError> {
    let layout = ObjectLayout::for_template(class_sym)?;
    sv_sim_sim::objects::register_handle_fields(id, layout.handle_field_slots());
    sv_sim_sim::objects::register_collection_fields(id, layout.collection_field_slots());
    sv_sim_sim::objects::register_nested_handles(id, layout.nested_handle_slots());
    sv_sim_sim::objects::register_rand_props(id, layout.rand_props());
    note_class_template_id(specialization_key_of_symbol(&class_sym)?, id, &class_sym)?;
    // Constraints plan C3.5: this template's `randomize()` program. A class
    // whose constraints cannot be built yet is not an error here -- only a
    // `randomize()` call that could reach it is (`classes_randomize`).
    if is_builtin_std_class(&class_sym).is_none() {
        crate::classes_randomize::register_class_program(id, class_sym, &layout, universe);
    }
    Ok(layout)
}

/// The [`ClassTemplateId`] `$cast` and the ancestor closures ([`register_
/// ancestor_closures`]) use for the class or interface class `ty`: its dense
/// id when it has one (a `new()`-reachable class or one of its bases), else a
/// "light" id under its own registry key (`cast|<specialization key>`) in the
/// same range as [`static_singleton_template_id`]'s. Interface classes never
/// have a dense id (no object is ever one), and a class that is never
/// constructed has none either -- but both are legal `$cast` destinations
/// (LRM 6.24.2, 8.26), a cast to the latter simply never succeeds for a non-
/// null source, and the closure of an implementing class names the former by
/// the very same id. Pure get-or-create, so the closure registered at
/// pipeline time and the id a later cast site asks for always agree.
pub(crate) fn cast_template_id(ty: sv_lang::Type<'_>) -> ClassTemplateId {
    let key = sv_sim_sim::netlist::class_specialization_key(ty);
    CLASS_TEMPLATE_IDS.with(|c| {
        let mut c = c.borrow_mut();
        if let Some(&id) = c.ids.get(&key) {
            return id;
        }
        let light_key = format!("cast|{key}");
        if let Some(&id) = c.ids.get(&light_key) {
            return id;
        }
        let id = ClassTemplateId(LIGHT_TEMPLATE_ID_BASE + c.next_light);
        c.next_light += 1;
        c.ids.insert(light_key, id);
        id
    })
}

/// Classes plan Task 11 (LRM 1800-2023 6.24.2, 8.16, 8.26): registers, for
/// every `(id, class_sym)` pair `pipeline::build_pipeline`'s class sub-pass
/// handles, the ancestor-or-self closure [`sv_sim_sim::objects::is_a`]
/// consults -- every base class up the `extends` chain and every interface
/// class implemented by the class or by any of its bases (a subclass
/// implicitly implements what its superclass implements, 8.26;
/// `netlist::flattened_interfaces` already follows an interface class's own
/// `extends`). Run after every dense id is noted ([`register_template`]), so
/// a base class is named by its own dense id.
pub fn register_ancestor_closures(classes: &[(ClassTemplateId, sv_lang::Symbol<'_>)]) {
    for &(id, class_sym) in classes {
        let Some(ty) = class_sym.as_type() else {
            continue;
        };
        let mut closure = std::collections::HashSet::new();
        let bases = sv_sim_sim::netlist::base_chain(ty);
        for level in bases.iter().copied().chain(std::iter::once(ty)) {
            closure.insert(cast_template_id(level));
            for iface in sv_sim_sim::netlist::flattened_interfaces(level) {
                closure.insert(cast_template_id(iface));
            }
        }
        sv_sim_sim::objects::register_ancestors(id, closure);
    }
}

/// `sv_rt_obj(IsA, h, {dest, ..})` as an `i1`: whether the object `h` names
/// is an instance of the class (or interface class) `dest` -- false for a
/// null or stale `h`, so a caller decides the null-source case itself.
pub(crate) fn is_a_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    h: IntValue<'ctx>,
    dest: sv_lang::Type<'_>,
) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let null = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    let id = cast_template_id(dest);
    let r = obj_call(
        cx,
        ObjOp::IsA,
        h,
        i64t.const_int(u64::from(id.0), false),
        i64t.const_zero(),
        null,
    );
    cx.b.build_int_compare(inkwell::IntPredicate::NE, r, i64t.const_zero(), "is_a")
        .unwrap()
}

// --- `sv_rt_obj` ABI call building (mirrors `collections.rs`'s own
// `sv_rt_coll` call-building shape -- see that file's module doc).

fn obj_fn<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> FunctionValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let ptr = cx.ctx.ptr_type(AddressSpace::default());
    cx.module.get_function(SV_RT_OBJ_SYMBOL).unwrap_or_else(|| {
        cx.module.add_function(
            SV_RT_OBJ_SYMBOL,
            i64t.fn_type(&[i32t.into(), i64t.into(), ptr.into()], false),
            Some(Linkage::External),
        )
    })
}

/// `sv_rt_obj(op, h, &{index, index2, val})`.
pub(crate) fn obj_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    op: ObjOp,
    h: IntValue<'ctx>,
    index: IntValue<'ctx>,
    index2: IntValue<'ctx>,
    val: PointerValue<'ctx>,
) -> IntValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let ptr = cx.ctx.ptr_type(AddressSpace::default());
    let st = cx
        .ctx
        .struct_type(&[i64t.into(), i64t.into(), ptr.into()], false);
    let buf = entry_alloca(cx, st, "obj_args");
    let fields: [inkwell::values::BasicValueEnum<'ctx>; 3] =
        [index.into(), index2.into(), val.into()];
    for (i, v) in fields.into_iter().enumerate() {
        let p = cx.b.build_struct_gep(st, buf, i as u32, "obj_arg").unwrap();
        cx.b.build_store(p, v).unwrap();
    }
    let f = obj_fn(cx);
    cx.b.build_call(
        f,
        &[
            i32t.const_int(op as u32 as u64, false).into(),
            h.into(),
            buf.into(),
        ],
        "obj_call",
    )
    .unwrap()
    .try_as_basic_value()
    .basic()
    .expect("sv_rt_obj returns a value")
    .into_int_value()
}

fn alloc_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    id: ClassTemplateId,
    words: usize,
) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let null = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    obj_call(
        cx,
        ObjOp::Alloc,
        i64t.const_zero(),
        i64t.const_int(u64::from(id.0), false),
        i64t.const_int(words as u64, false),
        null,
    )
}

/// `+1` reference on the object `h` names (a null or stale handle is a
/// no-op at runtime).
pub(crate) fn retain_handle<'ctx>(cx: &LowerCtx<'ctx, '_, '_>, h: IntValue<'ctx>) {
    let i64t = cx.ctx.i64_type();
    let null = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    obj_call(
        cx,
        ObjOp::Retain,
        h,
        i64t.const_zero(),
        i64t.const_zero(),
        null,
    );
}

/// `-1` reference on the object `h` names; the last one frees it and
/// releases the objects its handle fields name.
pub(crate) fn release_handle<'ctx>(cx: &LowerCtx<'ctx, '_, '_>, h: IntValue<'ctx>) {
    let i64t = cx.ctx.i64_type();
    let null = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    obj_call(
        cx,
        ObjOp::Release,
        h,
        i64t.const_zero(),
        i64t.const_zero(),
        null,
    );
}

/// Fields of at least this many `u64` words move to and from the marshaling
/// buffer as one wide integer load/store instead of a per-word shift/or chain.
const WIDE_MARSHAL_WORDS: u32 = 3;

/// One word address of a `words`-element `i64` array `buf` -- the 2-index
/// GEP shape `ops.rs::wide_alloca`'s own `wide_limb_ptr` already uses for
/// exactly this "element of an array alloca" case.
pub(crate) fn word_ptr<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    buf: PointerValue<'ctx>,
    words: u32,
    idx: u32,
) -> PointerValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let arr_ty = i64t.array_type(words);
    let idx0 = cx.ctx.i32_type().const_zero();
    let idxn = cx.ctx.i32_type().const_int(u64::from(idx), false);
    // SAFETY: `buf` was just `entry_alloca`d as exactly `[i64; words]`, and
    // `idx < words` is always true at every call site below (each loops
    // `0..words`), so `[0, idx]` is an in-bounds GEP into that allocation.
    unsafe {
        cx.b.build_gep(arr_ty, buf, &[idx0, idxn], "word_ptr")
            .unwrap()
    }
}

/// Packs `pv` (a value already at its field's own declared width, under
/// `pv.repr`) into `words` little-endian `u64` words of `buf` -- the write
/// half of the `sv_rt_obj` `FieldSet`/`FieldGet` marshaling this module uses
/// uniformly for every field shape (integral, real, string, chandle,
/// virtual-interface or class-handle: every one of them is, by this point,
/// just `pv.width` raw bits under `pv.repr`).
pub(crate) fn store_packed_words<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    buf: PointerValue<'ctx>,
    pv: PackedValue<'ctx>,
    words: u32,
) {
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let i64t = cx.ctx.i64_type();
    let wide_ty = op.i_n(words * 64);
    // `words = ceil(packed_bits / 64)`, so `words * 64 >= packed_bits`
    // always -- this zext (or, when they're equal, bitcast) is always the
    // same-or-widening direction, never a truncation.
    let wide =
        cx.b.build_int_z_extend_or_bit_cast(pv.llvm, wide_ty, "fld_wide")
            .unwrap();
    if words >= WIDE_MARSHAL_WORDS {
        // One store of the whole integer: the host is little-endian, so
        // `[words x i64]` and `i(words*64)` share a memory image. The
        // per-word shift chain is quadratic in LLVM's APInt work (a 65536-bit
        // field cost uvm_pkg ~minutes of backend time).
        let st = cx.b.build_store(buf, wide).unwrap();
        st.set_alignment(8).unwrap();
        return;
    }
    for w in 0..words {
        let shifted = if w == 0 {
            wide
        } else {
            cx.b.build_right_shift(
                wide,
                wide_ty.const_int(u64::from(w) * 64, false),
                false,
                "fld_shift",
            )
            .unwrap()
        };
        let word =
            cx.b.build_int_truncate_or_bit_cast(shifted, i64t, "fld_word")
                .unwrap();
        cx.b.build_store(word_ptr(cx, buf, words, w), word).unwrap();
    }
}

/// The read half of [`store_packed_words`]: reassembles `words` little-
/// endian `u64` words of `buf` back into a `width`-bit [`PackedValue`] under
/// `repr`.
pub(crate) fn load_packed_words<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    buf: PointerValue<'ctx>,
    width: u32,
    repr: ValueRepr,
    words: u32,
    signed: bool,
) -> PackedValue<'ctx> {
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let i64t = cx.ctx.i64_type();
    let wide_ty = op.i_n(words * 64);
    let mut acc = wide_ty.const_zero();
    if words >= WIDE_MARSHAL_WORDS {
        // One load of the whole integer (see `store_packed_words`).
        let ld = cx.b.build_load(wide_ty, buf, "fld_wide_ld").unwrap();
        inkwell::values::BasicValue::as_instruction_value(&ld)
            .expect("a load")
            .set_alignment(8)
            .unwrap();
        acc = ld.into_int_value();
    }
    for w in 0..words {
        if words >= WIDE_MARSHAL_WORDS {
            break;
        }
        let word =
            cx.b.build_load(i64t, word_ptr(cx, buf, words, w), "fld_word_ld")
                .unwrap()
                .into_int_value();
        let ext =
            cx.b.build_int_z_extend_or_bit_cast(word, wide_ty, "fld_word_ext")
                .unwrap();
        let shifted = if w == 0 {
            ext
        } else {
            cx.b.build_left_shift(
                ext,
                wide_ty.const_int(u64::from(w) * 64, false),
                "fld_word_shl",
            )
            .unwrap()
        };
        acc = cx.b.build_or(acc, shifted, "fld_word_or").unwrap();
    }
    let target_ty = op.packed_type(width, repr);
    let llvm =
        cx.b.build_int_truncate_or_bit_cast(acc, target_ty, "fld_val")
            .unwrap();
    PackedValue {
        llvm,
        width,
        repr,
        signed,
    }
}

/// Stores `pv` into `h`'s field at `slot`; the `i1` result is whether `h` was
/// live (a null or stale handle stores nothing).
pub(crate) fn field_set_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    pv: PackedValue<'ctx>,
) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let words = slot.words as u32;
    let buf = entry_alloca(cx, i64t.array_type(words), "fld_set_buf");
    store_packed_words(cx, buf, pv, words);
    let live = obj_call(
        cx,
        ObjOp::FieldSet,
        h,
        i64t.const_int(slot.offset as u64, false),
        i64t.const_int(slot.words as u64, false),
        buf,
    );
    cx.b.build_int_compare(IntPredicate::NE, live, i64t.const_zero(), "fld_set_live")
        .unwrap()
}

/// Reads `h`'s field at `slot`; the `i1` is whether `h` was live. The runtime
/// zero-fills the buffer for a null or stale handle (`sv_rt_obj`'s `FieldGet`),
/// so the value is defined (all-zero) either way.
pub(crate) fn field_get_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    width: u32,
    signed: bool,
) -> (PackedValue<'ctx>, IntValue<'ctx>) {
    let i64t = cx.ctx.i64_type();
    let words = slot.words as u32;
    let buf = entry_alloca(cx, i64t.array_type(words), "fld_get_buf");
    let live = obj_call(
        cx,
        ObjOp::FieldGet,
        h,
        i64t.const_int(slot.offset as u64, false),
        i64t.const_int(slot.words as u64, false),
        buf,
    );
    let live =
        cx.b.build_int_compare(IntPredicate::NE, live, i64t.const_zero(), "fld_get_live")
            .unwrap();
    (
        load_packed_words(cx, buf, width, cx.repr, words, signed),
        live,
    )
}

/// The report for an access of a member through a null or stale handle
/// (`live` false): LRM 1800-2023 8.5 calls it illegal with an indeterminate
/// result and lets an implementation issue an error -- this one reports it
/// like `$error` and yields all-zero (a defined value) for a read, a no-op
/// for a write, then carries on.
pub(crate) fn report_dead_handle_access<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    live: IntValue<'ctx>,
    at: sv_lang::SourceLoc,
    member: &str,
    what: &str,
) -> Result<(), LoweringError> {
    let dead = cx.b.build_not(live, "dead_handle").unwrap();
    crate::stmt_shared::error_if(
        cx,
        dead,
        at,
        &format!("null object handle: {what} of member {member}"),
    )
}

/// `h` (a plain `i64` handle value) as the 64-bit, never-X [`PackedValue`]
/// a class-typed expression's value is -- the `LoweredValue::Packed` every
/// `lower_expr` caller already expects (§1.3's own "a class handle is a
/// plain 64-bit reference" framing, `types.rs::TypeWidth`).
fn handle_as_packed<'ctx>(cx: &LowerCtx<'ctx, '_, '_>, h: IntValue<'ctx>) -> PackedValue<'ctx> {
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    op.pack(h, cx.ctx.i64_type().const_zero(), 64, cx.repr, false)
}

/// The plain `i64` handle value of an already-lowered class-typed
/// expression's [`LoweredValue`] -- `OpBuilder::lane_val` extracts the
/// value lane regardless of `cx.repr` (2-state: the value as is; 4-state:
/// the low 64 bits of its `(unk<<64)|val` packing, which is always `0` for
/// a handle -- a class handle is never X/Z).
pub(crate) fn receiver_handle<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    recv: sv_lang::Expression<'d>,
) -> Result<IntValue<'ctx>, LoweringError> {
    let pv = lower_expr(cx, recv)?.into_packed(
        "a class method/field receiver is not a plain handle value",
        &cx.fn_sym,
    )?;
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    Ok(op.lane_val(pv))
}

// --- Field read/write (§1.4 Step 4: `obj.field` and, inside a method
// body, a bare `field` -- implicit `this.field`).

/// Whether `member` is a non-static (automatic-lifetime) class property --
/// the one shared classification [`read_field`]/[`write_field`]/`expr.rs`'s
/// `NamedValue` arm/`expr.rs::store_to`'s class-field intercept all use. A
/// `static` property is [`is_static_field`]'s concern ([`read_static`]/
/// [`write_static`]); a method/constructor/nested-class member is never a
/// property at all.
pub fn is_instance_field(member: &sv_lang::Symbol<'_>) -> bool {
    member.kind() == SymbolKind::ClassProperty
        && member.variable_lifetime() == sv_lang::VariableLifetime::Automatic
}

/// Whether `member` is a `static` (one-copy-per-specialization, LRM 8.9)
/// class property -- the complement of [`is_instance_field`] over
/// `ClassProperty` members.
pub fn is_static_field(member: &sv_lang::Symbol<'_>) -> bool {
    member.kind() == SymbolKind::ClassProperty
        && member.variable_lifetime() == sv_lang::VariableLifetime::Static
}

/// Writes `value` into `h`'s field at `slot` of declared type `ty`, coercing
/// it to `ty`'s own width via [`crate::real::to_storage`] -- exactly like
/// every other assignment target in this crate (`expr.rs::store_to`):
/// slang's own assignment-conversion `Conversion` nodes are trusted to have
/// already equalized width/kind before `value` ever reaches here.
///
/// Ownership (classes Task 10): a field holding class handles owns one
/// reference to each, so `value` must be an owned value
/// (`collections::owned`: it carries its own reference) and the objects the
/// field named before are released after the store. Collections in the field
/// are not released here (see `collections::release_handles_of`) unless
/// `assign` says this is a whole-collection assignment (`obj.q = other`),
/// as opposed to a method's store-back of the (possibly same) handle.
fn store_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    ty: &sv_lang::Type<'d>,
    value: LoweredValue<'ctx>,
    assign: bool,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    store_field_live(cx, h, slot, ty, value, assign).map(|(v, _)| v)
}

/// [`store_field`], also returning the `i1` "`h` was live" of the store.
fn store_field_live<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    ty: &sv_lang::Type<'d>,
    value: LoweredValue<'ctx>,
    assign: bool,
) -> Result<(LoweredValue<'ctx>, IntValue<'ctx>), LoweringError> {
    let width = ty.value_width();
    let pv = crate::real::to_storage(cx, value, width, "class property assignment")?;
    if pv.width != width {
        return Err(LoweringError::unsupported_at(
            &format!(
                "class property assignment is {} bits for a {width}-bit property",
                pv.width
            ),
            &cx.fn_sym,
        ));
    }
    let holds_objects = crate::collections::handle_offsets(ty)
        .iter()
        .any(|s| s.kind == crate::collections::HandleKind::Obj);
    let frees_colls = assign && sv_sim_sim::state::storage::is_collection(ty);
    let old = (holds_objects || frees_colls).then(|| load_field(cx, h, slot, ty));
    let live = field_set_call(cx, h, slot, pv);
    if let Some(old) = old {
        crate::collections::release_handles_of(cx, ty, old, !frees_colls);
    }
    Ok((value, live))
}

/// Reads `h`'s field at `slot` of declared type `ty` back as a
/// [`LoweredValue`] -- mirrors the unpacked-struct-field read arm in
/// `expr.rs`'s `MemberAccess` case exactly (a real's bits become a float, a
/// string's bits become its interned id, everything else stays packed).
fn load_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    ty: &sv_lang::Type<'d>,
) -> LoweredValue<'ctx> {
    load_field_live(cx, h, slot, ty).0
}

/// [`load_field`], also returning the `i1` "`h` was live" of the read (a
/// null or stale handle reads all-zero).
fn load_field_live<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    ty: &sv_lang::Type<'d>,
) -> (LoweredValue<'ctx>, IntValue<'ctx>) {
    let (pv, live) = field_get_call(cx, h, slot, ty.value_width(), ty.is_signed());
    let v = if ty.is_floating() {
        LoweredValue::Real(crate::real::bits_to_real(cx, pv))
    } else if ty.is_string() {
        LoweredValue::Str(crate::strings::from_storage(cx, pv))
    } else {
        LoweredValue::Packed(pv)
    };
    (v, live)
}

/// `obj.field` (or, through [`current_this_var`], a bare `field`): resolves
/// `member`'s own class/[`ObjectLayout`]/[`FieldSlot`] fresh from `member`
/// itself (never a shared, caller-supplied layout -- see [`ObjectLayout`]'s
/// own "recomputed, not cached" design note) and reads it off `h`.
pub fn read_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    member: &sv_lang::Symbol<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let class_sym = member.parent().ok_or_else(|| {
        LoweringError::unsupported_at("class property has no enclosing class", member)
    })?;
    let layout = ObjectLayout::for_template(class_sym)?;
    let slot = layout.slot_of(member).ok_or_else(|| {
        LoweringError::unsupported_at(
            "internal: class property missing from its own class's layout",
            member,
        )
    })?;
    let ty = member
        .value_type()
        .ok_or_else(|| LoweringError::unsupported_at("class property has no type", member))?;
    Ok(load_field(cx, h, slot, &ty))
}

/// [`read_field`] for an explicit `obj.field` read at `at`: a null or stale
/// `obj` is reported ([`report_dead_handle_access`]) and the read yields
/// all-zero -- never whatever the read's scratch buffer last held.
pub fn read_field_checked<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    member: &sv_lang::Symbol<'d>,
    at: sv_lang::SourceLoc,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let (slot, ty) = member_slot_and_type(member)?;
    let (v, live) = load_field_live(cx, h, slot, &ty);
    report_dead_handle_access(cx, live, at, member.name(), "read")?;
    Ok(v)
}

/// [`write_field`] for an explicit `obj.field = v` at `at`: a write through a
/// null or stale `obj` is reported and dropped.
pub fn write_field_checked<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    member: &sv_lang::Symbol<'d>,
    value: LoweredValue<'ctx>,
    at: sv_lang::SourceLoc,
    assign: bool,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let (slot, ty) = member_slot_and_type(member)?;
    let (v, live) = store_field_live(cx, h, slot, &ty, value, assign)?;
    report_dead_handle_access(cx, live, at, member.name(), "write")?;
    Ok(v)
}

/// The slot and declared type of non-static property `member` (see
/// [`read_field`]).
pub(crate) fn member_slot_and_type<'d>(
    member: &sv_lang::Symbol<'d>,
) -> Result<(FieldSlot, sv_lang::Type<'d>), LoweringError> {
    let class_sym = member.parent().ok_or_else(|| {
        LoweringError::unsupported_at("class property has no enclosing class", member)
    })?;
    let layout = ObjectLayout::for_template(class_sym)?;
    let slot = layout.slot_of(member).ok_or_else(|| {
        LoweringError::unsupported_at(
            "internal: class property missing from its own class's layout",
            member,
        )
    })?;
    let ty = member
        .value_type()
        .ok_or_else(|| LoweringError::unsupported_at("class property has no type", member))?;
    Ok((slot, ty))
}

/// The write counterpart of [`read_field`].
pub fn write_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    member: &sv_lang::Symbol<'d>,
    value: LoweredValue<'ctx>,
    assign: bool,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let class_sym = member.parent().ok_or_else(|| {
        LoweringError::unsupported_at("class property has no enclosing class", member)
    })?;
    let layout = ObjectLayout::for_template(class_sym)?;
    let slot = layout.slot_of(member).ok_or_else(|| {
        LoweringError::unsupported_at(
            "internal: class property missing from its own class's layout",
            member,
        )
    })?;
    let ty = member
        .value_type()
        .ok_or_else(|| LoweringError::unsupported_at("class property has no type", member))?;
    store_field(cx, h, slot, &ty, value, assign)
}

/// `h` (an `i64` class handle) as a string `null`, or `<Class>@<N>` with `N`
/// the object's heap index: the text a class handle prints as when it is a
/// property of the object being printed (not expanded again, so a
/// self-referencing list or tree prints finitely). Branch-free: both texts
/// are built and a `select` on `h == 0` picks one.
fn handle_ref_text<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    ty: sv_lang::Type<'_>,
    h: IntValue<'ctx>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let i32t = cx.ctx.i32_type();
    let index = cx.b.build_int_truncate(h, i32t, "obj_index").unwrap();
    let fmt = crate::process_lower::build_c_string_global(
        cx.ctx,
        cx.module,
        &format!("{}@%0d", ty.as_symbol().name().replace('%', "%%")),
        "obj_ref_fmt",
    );
    let named = crate::strings::sformat_with(
        cx,
        fmt,
        vec![LoweredValue::Packed(op.pack(
            index,
            i32t.const_zero(),
            32,
            cx.repr,
            false,
        ))],
    )?;
    let null = crate::strings::literal(cx, b"null");
    let is_null =
        cx.b.build_int_compare(
            inkwell::IntPredicate::EQ,
            h,
            h.get_type().const_zero(),
            "obj_ref_null",
        )
        .unwrap();
    let id =
        cx.b.build_select(is_null, null.llvm, named.llvm, "obj_ref")
            .unwrap()
            .into_int_value();
    Ok(LoweredValue::Str(crate::strings::StrValue { llvm: id }))
}

/// `%p` of the class handle `h` of static type `ty` (LRM 1800-2023 21.2.1.7,
/// which leaves a non-null handle's text to the implementation): `null` for a
/// null (or stale) handle, else an assignment pattern of the properties `ty`
/// declares, inherited ones first (`'{a:1, b:"x"}`), each leaf a singular
/// `%p`. A property that is itself a class handle prints as `null` or
/// `<Class>@<N>` ([`handle_ref_text`]), never expanded. Built as a run-time
/// string -- the null test is a `select`, the property reads of a null handle
/// being all-zero (`ObjOp::FieldGet`) -- so a caller splices it in with `%s`.
pub(crate) fn format_object<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    ty: sv_lang::Type<'_>,
    h: IntValue<'ctx>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let layout = ObjectLayout::for_template(ty.as_symbol())?;
    let mut text = String::from("'{");
    let mut leaves = Vec::new();
    for (i, f) in layout.fields().iter().enumerate() {
        if i > 0 {
            text.push_str(", ");
        }
        let fty = f
            .sym
            .value_type()
            .ok_or_else(|| LoweringError::unsupported_at("class property has no type", &f.sym))?;
        text.push_str(&f.sym.name().replace('%', "%%"));
        text.push(':');
        if fty.is_class() {
            let (fh, _) = field_get_call(cx, h, f.slot, 64, false);
            let fh = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            }
            .lane_val(fh);
            text.push_str("%s");
            leaves.push(handle_ref_text(cx, fty, fh)?);
        } else if sv_sim_sim::state::storage::is_unpacked_aggregate(&fty)
            || (fty.is_unpacked_array() && !sv_sim_sim::state::storage::is_collection(&fty))
        {
            // An unpacked struct or fixed-size array property is one flat
            // value; print it as its own assignment pattern, like a
            // variable of that type.
            let v = load_field(cx, h, f.slot, &fty)
                .into_packed("an aggregate class property", &f.sym)?;
            crate::systask::aggregate_pattern(cx, &fty, v, &mut text, &mut leaves)?;
        } else {
            let v = load_field(cx, h, f.slot, &fty);
            let named = match v {
                LoweredValue::Packed(p) => crate::sysfunc::enum_pattern_text(cx, &fty, p)?,
                _ => None,
            };
            if let Some(s) = named {
                text.push_str("%s");
                leaves.push(s);
            } else {
                text.push_str("%p");
                leaves.push(v);
            }
        }
    }
    text.push('}');
    let fmt = crate::process_lower::build_c_string_global(cx.ctx, cx.module, &text, "obj_fmt");
    let body = crate::strings::sformat_with(cx, fmt, leaves)?;
    let null = crate::strings::literal(cx, b"null");
    let is_null =
        cx.b.build_int_compare(
            inkwell::IntPredicate::EQ,
            h,
            h.get_type().const_zero(),
            "obj_null",
        )
        .unwrap();
    let id =
        cx.b.build_select(is_null, null.llvm, body.llvm, "obj_text")
            .unwrap()
            .into_int_value();
    Ok(LoweredValue::Str(crate::strings::StrValue { llvm: id }))
}

// --- Static properties (classes plan Task 9; the plan's Task 4 gave STATE a
// per-template singleton segment but wired no codegen access to it, and
// nothing before this task read or wrote a `static` property from compiled
// code). Each class SPECIALIZATION's statics live in ONE heap object,
// allocated the first time any code touches one of them and named by a
// per-compile LLVM global, so `Box#(int)::count` and `Box#(string)::count`
// are two different variables (8.25) and an object-free `Reg#(4)::n` works.

/// The handle of `class_sym`'s static-property singleton object, allocating
/// and initializing it on first use: emits `if (g == 0) { g = alloc();
/// <store each static's initializer or default> }` against a private
/// per-specialization global `g`, and returns the loaded handle.
///
/// Constant initializers are stored on that first use, which is
/// unobservable. A NON-constant one (a call) is not: it runs in the class's
/// time-zero kernel ([`run_dynamic_static_initializers`], LRM 6.21 / 8.9;
/// `netlist::classes_with_dynamic_static_init`, emitted by `run_design`).
pub(crate) fn static_singleton_handle<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    class_sym: sv_lang::Symbol<'d>,
) -> Result<IntValue<'ctx>, LoweringError> {
    let layout = ObjectLayout::for_statics(class_sym)?;
    let id = static_singleton_template_id(&class_sym)?;
    let i64t = cx.ctx.i64_type();
    let name = format!("sv_class_static_{}", id.0);
    let cell = cx.module.get_global(&name).unwrap_or_else(|| {
        let g = cx.module.add_global(i64t, None, &name);
        g.set_initializer(&i64t.const_zero());
        g.set_linkage(Linkage::Private);
        g
    });
    let cur_bb =
        cx.b.get_insert_block()
            .ok_or_else(|| LoweringError::unsupported_at("no insertion block", &cx.fn_sym))?;
    let func = cur_bb
        .get_parent()
        .ok_or_else(|| LoweringError::unsupported_at("no enclosing function", &cx.fn_sym))?;
    let init = cx.ctx.append_basic_block(func, "cls_static_init");
    let done = cx.ctx.append_basic_block(func, "cls_static_done");
    let cached =
        cx.b.build_load(i64t, cell.as_pointer_value(), "cls_static_cached")
            .unwrap()
            .into_int_value();
    let live =
        cx.b.build_int_compare(
            inkwell::IntPredicate::NE,
            cached,
            i64t.const_zero(),
            "cls_static_live",
        )
        .unwrap();
    cx.b.build_conditional_branch(live, done, init).unwrap();

    cx.b.position_at_end(init);
    let h = alloc_call(cx, id, layout.total_words());
    // Publish the handle BEFORE running initializers, so nothing an
    // initializer touches can re-enter this block and allocate a second
    // singleton.
    cx.b.build_store(cell.as_pointer_value(), h).unwrap();
    for f in layout.fields() {
        let fty = f
            .sym
            .value_type()
            .ok_or_else(|| LoweringError::unsupported_at("class property has no type", &f.sym))?;
        let default = || {
            LoweredValue::Packed(PackedValue {
                llvm: crate::arrays::default_value(cx, &fty),
                width: fty.value_width(),
                repr: cx.repr,
                signed: fty.is_signed(),
            })
        };
        if fty.is_event() {
            // A static `event` property is one event object (LRM 8.9, 15.5);
            // an initializer naming another event is applied by
            // [`run_dynamic_static_initializers`].
            let id = crate::class_events::new_event(cx);
            let o = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            };
            let v = o.pack(id, o.i_n(64).const_zero(), 64, cx.repr, false);
            let _live = field_set_call(cx, h, f.slot, v);
            continue;
        }
        let value = match f.sym.initializer() {
            Some(init_expr) => {
                let cv = init_expr.constant_value();
                if let Some(iv) = cv.as_ref().and_then(|c| c.as_integer()) {
                    // The folded value itself, never the expression: a
                    // constant function call is a constant to slang but
                    // `lower_expr` would still emit the call.
                    crate::expr::lower_constant(cx, iv, Some(init_expr))?
                } else if cv.is_some() && init_expr.kind() == ExpressionKind::Call {
                    // A constant function call folding to a real or a string
                    // (LRM 13.4.3, 8.9): the folded value, never the call.
                    match cv.as_ref() {
                        Some(sv_lang::ConstantValue::Real(r)) => LoweredValue::Real(RealValue {
                            llvm: cx.ctx.f64_type().const_float(*r),
                        }),
                        Some(sv_lang::ConstantValue::String(text)) => {
                            LoweredValue::Str(crate::strings::literal(cx, text.as_bytes()))
                        }
                        _ => {
                            return Err(LoweringError::unsupported_at(
                                "a static class property initialized by a call whose constant \
                                 value is neither an integer, a real nor a string",
                                &f.sym,
                            ));
                        }
                    }
                } else if cv.is_some() {
                    crate::collections::owned(cx, init_expr)?
                } else {
                    // Not a constant: its initializer runs in the class's
                    // time-zero kernel ([`run_dynamic_static_initializers`]),
                    // never in whatever function first touches the class
                    // (which may not see the signals the initializer's
                    // callees reach). Until then it reads as the default.
                    default()
                }
            }
            None => default(),
        };
        store_field(cx, h, f.slot, &fty, value, false)?;
    }
    let init_end = cx.b.get_insert_block().unwrap();
    cx.b.build_unconditional_branch(done).unwrap();

    cx.b.position_at_end(done);
    let phi = cx.b.build_phi(i64t, "cls_static_h").unwrap();
    phi.add_incoming(&[(&cached, cur_bb), (&h, init_end)]);
    Ok(phi.as_basic_value().into_int_value())
}

/// Evaluates, in declaration order, every static property of `class_sym`
/// whose initializer is not a constant and stores the result in the class's
/// singleton ([`static_singleton_handle`] allocates it first if nothing did).
/// Emitted once, into the class's time-zero kernel.
pub(crate) fn run_dynamic_static_initializers<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    class_sym: sv_lang::Symbol<'d>,
) -> Result<(), LoweringError> {
    let layout = ObjectLayout::for_statics(class_sym)?;
    let h = static_singleton_handle(cx, class_sym)?;
    for f in layout.fields() {
        let Some(init_expr) = f.sym.initializer().filter(|e| e.constant_value().is_none()) else {
            continue;
        };
        let fty = f
            .sym
            .value_type()
            .ok_or_else(|| LoweringError::unsupported_at("class property has no type", &f.sym))?;
        if fty.is_event() {
            let id = crate::class_events::id_of(cx, init_expr)?;
            let o = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            };
            let v = o.pack(id, o.i_n(64).const_zero(), 64, cx.repr, false);
            let _live = field_set_call(cx, h, f.slot, v);
            continue;
        }
        let value = crate::collections::owned(cx, init_expr)?;
        store_field(cx, h, f.slot, &fty, value, false)?;
    }
    Ok(())
}

/// The shared "where does static `member` live" lookup of [`read_static`]/
/// [`write_static`]: its singleton's handle, [`FieldSlot`] and type.
pub(crate) fn static_location<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    member: &sv_lang::Symbol<'d>,
) -> Result<(IntValue<'ctx>, FieldSlot, sv_lang::Type<'d>), LoweringError> {
    let class_sym = member.parent().ok_or_else(|| {
        LoweringError::unsupported_at("class property has no enclosing class", member)
    })?;
    let layout = ObjectLayout::for_statics(class_sym)?;
    let slot = layout.slot_of(member).ok_or_else(|| {
        LoweringError::unsupported_at(
            "internal: static class property missing from its own class's static layout",
            member,
        )
    })?;
    let ty = member
        .value_type()
        .ok_or_else(|| LoweringError::unsupported_at("class property has no type", member))?;
    let h = static_singleton_handle(cx, class_sym)?;
    Ok((h, slot, ty))
}

/// Reads static class property `member` (`Cls::n`, `Cls#(P)::n`, a bare `n`
/// in a method of `Cls`, or `obj.n`).
pub fn read_static<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    member: &sv_lang::Symbol<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let (h, slot, ty) = static_location(cx, member)?;
    Ok(load_field(cx, h, slot, &ty))
}

/// The write counterpart of [`read_static`].
pub fn write_static<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    member: &sv_lang::Symbol<'d>,
    value: LoweredValue<'ctx>,
    assign: bool,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let (h, slot, ty) = static_location(cx, member)?;
    store_field(cx, h, slot, &ty, value, assign)
}

/// `cx.fn_sym`'s own `this` pseudo-symbol -- `Symbol::subroutine_this_var()`
/// (§1.3: "`this` inside a method body lowers to that parameter"; NOT
/// `Type::class_this_var()`, the CLASS's own `this` used by non-static
/// property initializers -- a different symbol, see [`lower_method_body`]'s
/// own doc comment for the exact confusion this crate's first draft hit).
/// A named `LoweringError` outside a class method body (never reachable
/// from a genuinely-compiling SV design -- a bare field name or `this`
/// only resolves inside one in the first place -- but still a real,
/// checked failure mode for this function's own callers, never an
/// `unwrap`).
pub fn current_this_var<'d>(
    cx: &LowerCtx<'_, 'd, '_>,
) -> Result<sv_lang::Symbol<'d>, LoweringError> {
    cx.fn_sym
        .subroutine_this_var()
        .or(cx.inline_this)
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                "`this`/a bare field reference outside a (non-static) class method body",
                &cx.fn_sym,
            )
        })
}

/// The handle every bare-field reference/write resolves `this` against --
/// [`try_read_bare_field`]/[`try_write_field`]'s single shared "what is
/// `this` right now" lookup.
///
/// Review fix (r2), Task 5 finding 1: checks `cx.ctor_this` FIRST. While
/// [`lower_new_class`] is lowering one of ITS OWN property initializers
/// (LRM 1800-2023 §8.7's "`int b = a + 1;`" referencing an earlier sibling
/// property by bare name), that `Cell` holds the handle of the object JUST
/// ALLOCATED, so the initializer resolves against the new object itself.
/// Previously this always fell straight through to [`current_this_var`]/
/// `cx.locals`, i.e. whatever subroutine happened to be lexically
/// executing the `new` expression -- wrong in two confirmed ways: from a
/// non-method context (e.g. an `initial` block constructing the design's
/// first object) `current_this_var` has no `this` at all and fails the
/// compile outright, even though the construct is ordinary, LRM-legal SV;
/// from inside ANY class method body, it silently resolves against THAT
/// method's own receiver -- a different, possibly differently-typed,
/// object entirely, landing on whatever word happens to sit at the same
/// slot offset and computing a silently wrong value with no error at all.
/// Outside that window (`cx.ctor_this` is `None` at every other call site:
/// an ordinary method body, a continuous assign, ...), this is exactly the
/// pre-existing `current_this_var`/`cx.locals` path, unchanged.
pub(crate) fn current_this_handle<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
) -> Result<IntValue<'ctx>, LoweringError> {
    if let Some(h) = cx.ctor_this.get() {
        return Ok(h);
    }
    let this_var = current_this_var(cx)?;
    let (slot, _, _) = *cx.locals.get(&this_var.uid()).ok_or_else(|| {
        LoweringError::unsupported_at("`this` is unavailable in this scope", &cx.fn_sym)
    })?;
    Ok(cx
        .b
        .build_load(cx.ctx.i64_type(), slot, "this_ld")
        .unwrap()
        .into_int_value())
}

/// Reads a bare `NamedValue`/`HierarchicalValue` reference to a non-static
/// class property (implicit `this.field`) -- `expr.rs`'s `NamedValue` arm's
/// own class-field intercept, tried before that arm's ordinary `cx.locals`
/// lookup (a `ClassProperty` is never a `locals` entry). `Ok(None)` for any
/// other symbol kind -- not this function's concern.
pub fn try_read_bare_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    sym: &sv_lang::Symbol<'d>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    if is_static_field(sym) {
        return Ok(Some(read_static(cx, sym)?));
    }
    if !is_instance_field(sym) {
        return Ok(None);
    }
    let h = current_this_handle(cx)?;
    Ok(Some(read_field(cx, h, sym)?))
}

/// Cheap, `cx`-free pre-check for `expr.rs`'s generalized `Assignment` arm
/// (which has its OWN plain-`NamedValue` assignment shortcut that never
/// reaches `store_to` at all): whether `lhs` is a class-field assignment
/// target at all (an `obj.field` member access, or a bare name resolving
/// to a non-static class property) -- [`try_write_field`] is the real,
/// `cx`-needing implementation this guards; kept as its own function so
/// that arm can route around its OWN RHS-lowering/collections-ownership
/// bookkeeping only when this is actually a class-field target.
pub fn is_class_field_lvalue(lhs: sv_lang::Expression<'_>) -> bool {
    // Deliberately `if`/`matches!`, not a `match lhs.kind() { .. }` with a
    // continuing wildcard arm: this is a two-shape *reject-list*
    // membership test ("is this one of the two class-field lvalue
    // shapes; if not, it is not this function's concern"), not an
    // exhaustive classification of `ExpressionKind` -- `xtask lint-
    // unimplemented`'s Kind-typed-match heuristic (VF-069) cannot tell
    // that shape apart from a genuine silently-defaulted classification
    // match by syntax alone, so this is written to not be a `match` over
    // `ExpressionKind` at all.
    if lhs.kind() == ExpressionKind::MemberAccess {
        return lhs
            .member_symbol()
            .is_some_and(|m| is_instance_field(&m) || is_static_field(&m));
    }
    if matches!(
        lhs.kind(),
        ExpressionKind::NamedValue | ExpressionKind::HierarchicalValue
    ) {
        return lhs
            .referenced_symbol()
            .is_some_and(|s| is_instance_field(&s) || is_static_field(&s));
    }
    false
}

/// Where the class property named by `e` (an `obj.field`, a bare
/// implicit-`this` `field`, or a static property by any route) lives: its
/// object's handle (the static singleton's for a `static`), [`FieldSlot`] and
/// declared type -- the storage root of a PARTIAL write into it (`obj.a[i] =
/// v`, `obj.s.f = v`, `obj.v[3:0] = v`, ledger XC-059), which is a
/// read-modify-write of the property's one flat value. `Ok(None)` when `e` is
/// not a class property. A null or stale `obj` is reported here
/// ([`report_dead_handle_access`]) and the write that follows is then a no-op.
pub(crate) fn class_field_root<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<Option<(IntValue<'ctx>, FieldSlot, sv_lang::Type<'d>)>, LoweringError> {
    let Some((h, slot, ty, dead)) = class_field_loc(cx, e)? else {
        return Ok(None);
    };
    if let Some((name, at)) = dead {
        // The first word of the property is enough to learn whether `h` is
        // live (`FieldGet` fills nothing and reports it dead otherwise).
        let probe = FieldSlot {
            offset: slot.offset,
            words: 1,
        };
        let (_, live) = field_get_call(cx, h, probe, 1, false);
        report_dead_handle_access(cx, live, at, &name, "write")?;
    }
    Ok(Some((h, slot, ty)))
}

/// Where the class property named by `e` lives, without touching it: the
/// handle, slot and type of [`class_field_root`], plus, for an instance
/// property reached through an explicit `obj.field`, that member's name and
/// source position (what a null-handle report needs). `Ok(None)` when `e` is
/// not a class property.
#[allow(clippy::type_complexity)]
pub(crate) fn class_field_loc<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<
    Option<(
        IntValue<'ctx>,
        FieldSlot,
        sv_lang::Type<'d>,
        Option<(String, sv_lang::SourceLoc)>,
    )>,
    LoweringError,
> {
    // `if`/`matches!`, not a `match` over `ExpressionKind` -- see
    // [`is_class_field_lvalue`].
    if e.kind() == ExpressionKind::MemberAccess {
        let Some(member) = e.member_symbol() else {
            return Ok(None);
        };
        if is_static_field(&member) {
            let (h, slot, ty) = static_location(cx, &member)?;
            return Ok(Some((h, slot, ty, None)));
        }
        if !is_instance_field(&member) {
            return Ok(None);
        }
        let base_expr = e.operand().ok_or_else(|| {
            LoweringError::unsupported_at("member-access lvalue missing base", &cx.fn_sym)
        })?;
        let h = receiver_handle(cx, base_expr)?;
        let (slot, ty) = member_slot_and_type(&member)?;
        return Ok(Some((
            h,
            slot,
            ty,
            Some((member.name().to_string(), e.source_range().start)),
        )));
    }
    if matches!(
        e.kind(),
        ExpressionKind::NamedValue | ExpressionKind::HierarchicalValue
    ) {
        let Some(sym) = e.referenced_symbol() else {
            return Ok(None);
        };
        if is_static_field(&sym) {
            let (h, slot, ty) = static_location(cx, &sym)?;
            return Ok(Some((h, slot, ty, None)));
        }
        if !is_instance_field(&sym) {
            return Ok(None);
        }
        let h = current_this_handle(cx)?;
        let (slot, ty) = member_slot_and_type(&sym)?;
        return Ok(Some((h, slot, ty, None)));
    }
    Ok(None)
}

/// Copies `h`'s field at `slot` into the image at `dst` (the field's flat
/// words are exactly a `PK` image of its width); the `i1` is whether `h` was
/// live (a dead handle fills zeros).
pub(crate) fn field_get_into<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    dst: PointerValue<'ctx>,
) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let live = obj_call(
        cx,
        ObjOp::FieldGet,
        h,
        i64t.const_int(slot.offset as u64, false),
        i64t.const_int(slot.words as u64, false),
        dst,
    );
    cx.b.build_int_compare(IntPredicate::NE, live, i64t.const_zero(), "fld_img_live")
        .unwrap()
}

/// The write counterpart of [`field_get_into`]: stores the image at `src`.
pub(crate) fn field_set_from<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    h: IntValue<'ctx>,
    slot: FieldSlot,
    src: PointerValue<'ctx>,
) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let live = obj_call(
        cx,
        ObjOp::FieldSet,
        h,
        i64t.const_int(slot.offset as u64, false),
        i64t.const_int(slot.words as u64, false),
        src,
    );
    cx.b.build_int_compare(
        IntPredicate::NE,
        live,
        i64t.const_zero(),
        "fld_img_set_live",
    )
    .unwrap()
}

/// `expr.rs::store_to`'s own class-field intercept (an explicit `obj.field =
/// v` or a bare, implicit-`this` `field = v`), tried before every other
/// lvalue shape that function already handles. `Ok(None)` for any other
/// lvalue kind/symbol -- not this function's concern.
pub fn try_write_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    value: LoweredValue<'ctx>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    try_write_field_as(cx, lhs, value, false)
}

/// [`try_write_field`] for a plain `obj.field = v` assignment (not a
/// method's store-back): a collection the field held is freed.
pub fn try_assign_field<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    value: LoweredValue<'ctx>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    try_write_field_as(cx, lhs, value, true)
}

fn try_write_field_as<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    lhs: sv_lang::Expression<'d>,
    value: LoweredValue<'ctx>,
    assign: bool,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    // Deliberately `if`/`matches!`, not a `match lhs.kind() { .. }` with a
    // continuing wildcard arm -- see [`is_class_field_lvalue`]'s own doc
    // comment for the identical reasoning (and why `xtask lint-
    // unimplemented`'s Kind-typed-match heuristic requires this shape).
    if lhs.kind() == ExpressionKind::MemberAccess {
        let Some(member) = lhs.member_symbol() else {
            return Ok(None);
        };
        if is_static_field(&member) {
            // `obj.n = v` on a static: there is one `n` for the whole
            // specialization, so the receiver is not evaluated (see
            // `read_static`'s deviation note in `expr.rs`).
            return Ok(Some(write_static(cx, &member, value, assign)?));
        }
        if !is_instance_field(&member) {
            return Ok(None);
        }
        let base_expr = lhs.operand().ok_or_else(|| {
            LoweringError::unsupported_at("member-access lvalue missing base", &cx.fn_sym)
        })?;
        let h = receiver_handle(cx, base_expr)?;
        let at = lhs.source_range().start;
        return Ok(Some(write_field_checked(
            cx, h, &member, value, at, assign,
        )?));
    }
    if matches!(
        lhs.kind(),
        ExpressionKind::NamedValue | ExpressionKind::HierarchicalValue
    ) {
        let Some(sym) = lhs.referenced_symbol() else {
            return Ok(None);
        };
        if is_static_field(&sym) {
            return Ok(Some(write_static(cx, &sym, value, assign)?));
        }
        if !is_instance_field(&sym) {
            return Ok(None);
        }
        let h = current_this_handle(cx)?;
        return Ok(Some(write_field(cx, h, &sym, value, assign)?));
    }
    Ok(None)
}

// --- Method/constructor calls (§1.4 Step 2: "is this a method call at
// all? -> lower the receiver, then: not virtual -> direct mangled call").
// No virtual dispatch yet (Task 7); every call below resolves statically.

/// `callee`'s enclosing class is never one of the `std`-package intrinsics
/// (§0/Task 1's `is_builtin_std_class`) -- those have no compiled SV body
/// for `build_pipeline`'s class sub-pass to have lowered, and dispatching to
/// them is Tasks 13/16/17/18's job, not this one's.
fn reject_if_std_intrinsic(
    cx: &LowerCtx<'_, '_, '_>,
    callee: &sv_lang::Symbol<'_>,
) -> Result<(), LoweringError> {
    let class_sym = callee.parent().ok_or_else(|| {
        LoweringError::unsupported_at("method has no enclosing class", &cx.fn_sym)
    })?;
    if let Some(intrinsic) = is_builtin_std_class(&class_sym) {
        return Err(LoweringError::unsupported_at(
            &format!(
                "calling the std-package intrinsic {intrinsic:?}'s method is not yet \
                 implemented (classes plan Task 18)"
            ),
            &cx.fn_sym,
        ));
    }
    Ok(())
}

// --- The built-in `process` class (classes plan Task 13, LRM 1800-2023 9.7).
// A `process` handle is a plain `u64` the object heap never resolves (see
// `sv_sim_runtime::process_class`), so a `process`-typed variable, its
// assignment, `== null` and `= null` all take the ordinary class-handle path;
// only the method calls below are special.

/// What [`lower_std_process_call`] made of a call.
pub(crate) enum ProcessCall<'ctx> {
    /// `call` is not a method of the `process` class: lower it as usual.
    NotProcess,
    /// Lowered; `Some` for a value-returning method (`status`, `self`).
    Lowered(Option<LoweredValue<'ctx>>),
}

fn process_fn<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> FunctionValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let symbol = sv_sim_runtime::process_class::SV_RT_PROCESS_SYMBOL;
    cx.module.get_function(symbol).unwrap_or_else(|| {
        cx.module.add_function(
            symbol,
            i64t.fn_type(&[i32t.into(), i64t.into(), i64t.into()], false),
            Some(Linkage::External),
        )
    })
}

/// `sv_rt_process(op, h, arg)`.
fn process_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    op: sv_sim_runtime::process_class::ProcessOp,
    h: IntValue<'ctx>,
    arg: IntValue<'ctx>,
) -> IntValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    cx.b.build_call(
        process_fn(cx),
        &[
            i32t.const_int(op as u32 as u64, false).into(),
            h.into(),
            arg.into(),
        ],
        "process_call",
    )
    .unwrap()
    .try_as_basic_value()
    .basic()
    .expect("sv_rt_process returns a value")
    .into_int_value()
}

/// A method of the built-in `process` class, called with an explicit receiver
/// (`p.kill()`) or statically (`process::self()`): dispatched to
/// `sv_rt_process`. A call through a null `process` handle is reported like
/// `$error` (LRM 9.7 leaves it undefined) and then does nothing (`status()`
/// reads FINISHED); `kill()` of the caller (or of an ancestor of it) ends the
/// caller on the spot ([`crate::stmt_shared::leave_if_aborted`]); `await()` on
/// the caller is the run-time error LRM 9.7 names.
pub(crate) fn lower_std_process_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    call: sv_lang::Expression<'d>,
) -> Result<ProcessCall<'ctx>, LoweringError> {
    use sv_sim_runtime::process_class::ProcessOp;

    let Some(callee) = call.call_subroutine() else {
        return Ok(ProcessCall::NotProcess);
    };
    let Some(class_sym) = callee.parent() else {
        return Ok(ProcessCall::NotProcess);
    };
    match is_builtin_std_class(&class_sym) {
        Some(StdIntrinsic::Process) => {}
        Some(StdIntrinsic::WeakReference) => return lower_weakref_call(cx, call, callee),
        Some(StdIntrinsic::Semaphore) => return lower_semaphore_call(cx, call, callee),
        Some(StdIntrinsic::Mailbox) => return lower_mailbox_call(cx, call, callee),
        _ => return lower_object_rng_call(cx, call, callee, class_sym),
    }
    let at = call.source_range().start;
    let i64t = cx.ctx.i64_type();
    let method = callee.name();
    if method == "self" {
        let h = process_call(
            cx,
            ProcessOp::SelfHandle,
            i64t.const_zero(),
            i64t.const_zero(),
        );
        return Ok(ProcessCall::Lowered(Some(LoweredValue::Packed(
            handle_as_packed(cx, h),
        ))));
    }
    let op = match method {
        "status" => ProcessOp::Status,
        "kill" => ProcessOp::Kill,
        "await" => ProcessOp::Await,
        "suspend" => ProcessOp::Suspend,
        "resume" => ProcessOp::Resume,
        "srandom" => ProcessOp::SRandom,
        "get_randstate" => ProcessOp::GetRandState,
        "set_randstate" => ProcessOp::SetRandState,
        other => {
            return Err(LoweringError::unsupported_at(
                &format!("calling process::{other} is not implemented"),
                &cx.fn_sym,
            ));
        }
    };
    let recv = call.call_this_class().ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!("process::{method} called without a process handle"),
            &cx.fn_sym,
        )
    })?;
    let h = receiver_handle(cx, recv)?;
    let null =
        cx.b.build_int_compare(IntPredicate::EQ, h, i64t.const_zero(), "process_null")
            .unwrap();
    crate::stmt_shared::error_if(
        cx,
        null,
        at,
        &format!("null process handle: call of process::{method}"),
    )?;
    // The one argument of `srandom(int)` / `set_randstate(string)`, after the
    // receiver operand; every other method passes `0`.
    let method_arg = |what: &str| {
        call.operands().get(1).copied().ok_or_else(|| {
            LoweringError::unsupported_at(
                &format!("process::{method} called without its {what} argument"),
                &cx.fn_sym,
            )
        })
    };
    let arg = match op {
        // An `int`, widened to 64 bits (the runtime keeps its low 32).
        ProcessOp::SRandom => crate::strings::index_i64(cx, method_arg("seed")?)?,
        ProcessOp::SetRandState => {
            crate::strings::to_string(cx, lower_expr(cx, method_arg("state")?)?)?.llvm
        }
        ProcessOp::Status
        | ProcessOp::Kill
        | ProcessOp::Await
        | ProcessOp::Suspend
        | ProcessOp::Resume
        | ProcessOp::GetRandState
        | ProcessOp::SelfHandle => i64t.const_zero(),
    };
    let ret = process_call(cx, op, h, arg);
    match op {
        ProcessOp::Status => {
            let ty = callee.subroutine_return_type().ok_or_else(|| {
                LoweringError::unsupported_at("process::status has no type", &cx.fn_sym)
            })?;
            let width = ty.value_width();
            let opb = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            };
            let val =
                cx.b.build_int_truncate_or_bit_cast(ret, opb.i_n(width), "state")
                    .unwrap();
            let unk = val.get_type().const_zero();
            Ok(ProcessCall::Lowered(Some(LoweredValue::Packed(opb.pack(
                val,
                unk,
                width,
                cx.repr,
                ty.is_signed(),
            )))))
        }
        ProcessOp::Kill => {
            // `ret` is 1 when the caller itself was ended: the run-time flag
            // `leave_if_aborted` reads is already set.
            crate::stmt_shared::leave_if_aborted(cx)?;
            Ok(ProcessCall::Lowered(None))
        }
        ProcessOp::Await => {
            let on_self =
                cx.b.build_int_compare(IntPredicate::EQ, ret, i64t.const_zero(), "await_on_self")
                    .unwrap();
            crate::stmt_shared::error_if(
                cx,
                on_self,
                at,
                "process::await called on the calling process itself (LRM 1800-2023 9.7)",
            )?;
            Ok(ProcessCall::Lowered(None))
        }
        ProcessOp::Suspend | ProcessOp::Resume | ProcessOp::SRandom | ProcessOp::SetRandState => {
            Ok(ProcessCall::Lowered(None))
        }
        ProcessOp::GetRandState => Ok(ProcessCall::Lowered(Some(LoweredValue::Str(
            crate::strings::StrValue { llvm: ret },
        )))),
        ProcessOp::SelfHandle => Err(LoweringError::unsupported_at(
            "internal: process::self reached the receiver path",
            &cx.fn_sym,
        )),
    }
}

// --- The built-in `weak_reference#(T)` class (classes plan Task 16, LRM
// 1800-2023 8.30). An instance is an ordinary heap object whose one field word
// holds the referent's handle bits without owning them; see
// `sv_sim_runtime::weakref`.

fn weakref_fn<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> FunctionValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let symbol = sv_sim_runtime::weakref::SV_RT_WEAKREF_SYMBOL;
    cx.module.get_function(symbol).unwrap_or_else(|| {
        cx.module.add_function(
            symbol,
            i64t.fn_type(&[i32t.into(), i64t.into(), i64t.into()], false),
            Some(Linkage::External),
        )
    })
}

/// `sv_rt_weakref(op, h, arg)`.
fn weakref_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    op: sv_sim_runtime::weakref::WeakRefOp,
    h: IntValue<'ctx>,
    arg: IntValue<'ctx>,
) -> IntValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    cx.b.build_call(
        weakref_fn(cx),
        &[
            i32t.const_int(op as u32 as u64, false).into(),
            h.into(),
            arg.into(),
        ],
        "weakref_call",
    )
    .unwrap()
    .try_as_basic_value()
    .basic()
    .expect("sv_rt_weakref returns a value")
    .into_int_value()
}

/// Whether `e` is a `weak_reference#(T)::get()` call. Its value is BORROWED:
/// `sv_rt_weakref`'s `Get` takes no reference on the handle it returns (the
/// weak reference must not own its referent), so [`crate::collections::fresh`]
/// must not mistake the call for one that built a value the caller owns, or
/// `strong = weak.get()` would store an unretained handle and a bare
/// `weak.get() == null` would leak one it never took. LRM 8.30.3: "storing the
/// result in a strongly reachable handle makes the referent strongly
/// reachable" -- the retain comes from the assignment, as for any handle read.
pub(crate) fn is_weak_get_call(e: &sv_lang::Expression<'_>) -> bool {
    if e.kind() != ExpressionKind::Call || e.is_system_call() == Some(true) {
        return false;
    }
    let Some(callee) = e.call_subroutine() else {
        return false;
    };
    callee.name() == "get"
        && callee
            .parent()
            .is_some_and(|c| is_builtin_std_class(&c) == Some(StdIntrinsic::WeakReference))
}

/// Whether evaluating `expr` reads class-object state that no signal change
/// reports: a class property (`obj.p`, a bare `p` in a method, a static
/// property), or any subroutine call -- a method of a class, a built-in
/// `weak_reference::get` / `mailbox::num` / `process::status`, or a function
/// that may dereference a handle it is given. A `wait (expr)` on such an
/// expression subscribes to object-state changes
/// ([`sv_sim_sim::sched::OBJECT_STATE_SLOT`]) besides the signals it names:
/// without that, `wait (weak_obj.get() == null)` (LRM 1800-2023 8.30.3) and
/// `wait (box.v == 3)` could never wake, because a heap write is no signal
/// change. System calls (`$time`) read no object state.
pub(crate) fn reads_object_state(expr: &sv_lang::Expression<'_>) -> bool {
    let mut stack = vec![expr.as_sem_node()];
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression() {
            // `if`s, not a `match` over `ExpressionKind`: a membership test
            // (see `is_class_field_lvalue`), not a classification.
            let kind = e.kind();
            if kind == ExpressionKind::Call && e.is_system_call() != Some(true) {
                return true;
            }
            if kind == ExpressionKind::MemberAccess
                && e.member_symbol()
                    .is_some_and(|m| is_instance_field(&m) || is_static_field(&m))
            {
                return true;
            }
            if matches!(
                kind,
                ExpressionKind::NamedValue | ExpressionKind::HierarchicalValue
            ) && e
                .referenced_symbol()
                .is_some_and(|s| is_instance_field(&s) || is_static_field(&s))
            {
                return true;
            }
        }
        stack.extend(n.children());
    }
    false
}

/// A method of `weak_reference#(T)`: `get`, `clear` (through a handle) or the
/// static `get_id(obj)`; `new` is [`lower_new_weakref`]'s. A call through a
/// null weak-reference handle is reported like `$error` (the LRM leaves it
/// undefined) and then does nothing -- `get` reads null.
fn lower_weakref_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    call: sv_lang::Expression<'d>,
    callee: sv_lang::Symbol<'d>,
) -> Result<ProcessCall<'ctx>, LoweringError> {
    use sv_sim_runtime::weakref::WeakRefOp;

    let at = call.source_range().start;
    let i64t = cx.ctx.i64_type();
    let method = callee.name();
    match method {
        "get_id" => {
            let obj = call.operands().first().copied().ok_or_else(|| {
                LoweringError::unsupported_at(
                    "weak_reference::get_id called without its object argument",
                    &cx.fn_sym,
                )
            })?;
            let h = receiver_handle(cx, obj)?;
            let ret = weakref_call(cx, WeakRefOp::GetId, i64t.const_zero(), h);
            let ty = callee.subroutine_return_type().ok_or_else(|| {
                LoweringError::unsupported_at("weak_reference::get_id has no type", &cx.fn_sym)
            })?;
            let width = ty.value_width();
            let opb = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            };
            let val =
                cx.b.build_int_truncate_or_bit_cast(ret, opb.i_n(width), "weak_id")
                    .unwrap();
            let unk = val.get_type().const_zero();
            Ok(ProcessCall::Lowered(Some(LoweredValue::Packed(opb.pack(
                val,
                unk,
                width,
                cx.repr,
                ty.is_signed(),
            )))))
        }
        "get" | "clear" => {
            let op = if method == "get" {
                WeakRefOp::Get
            } else {
                WeakRefOp::Clear
            };
            let recv = call.call_this_class().ok_or_else(|| {
                LoweringError::unsupported_at(
                    &format!("weak_reference::{method} called without a weak-reference handle"),
                    &cx.fn_sym,
                )
            })?;
            let h = receiver_handle(cx, recv)?;
            let null =
                cx.b.build_int_compare(IntPredicate::EQ, h, i64t.const_zero(), "weakref_null")
                    .unwrap();
            crate::stmt_shared::error_if(
                cx,
                null,
                at,
                &format!("null weak_reference handle: call of weak_reference::{method}"),
            )?;
            let ret = weakref_call(cx, op, h, i64t.const_zero());
            if op == WeakRefOp::Get {
                Ok(ProcessCall::Lowered(Some(LoweredValue::Packed(
                    handle_as_packed(cx, ret),
                ))))
            } else {
                Ok(ProcessCall::Lowered(None))
            }
        }
        other => Err(LoweringError::unsupported_at(
            &format!("calling weak_reference::{other} is not implemented"),
            &cx.fn_sym,
        )),
    }
}

/// `new(referent)` on `weak_reference#(T)` (LRM 8.30.2): an ordinary one-word
/// heap object holding the referent's handle without owning it.
fn lower_new_weakref<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
    class_sym: &sv_lang::Symbol<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    use sv_sim_runtime::weakref::WeakRefOp;

    let referent_expr = e
        .new_class_constructor_call()
        .and_then(|c| c.operands().first().copied())
        .or_else(|| e.operands().first().copied())
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                "`new()` of weak_reference without its referent argument",
                &cx.fn_sym,
            )
        })?;
    let referent = receiver_handle(cx, referent_expr)?;
    let id = class_template_id_of(class_sym)?;
    let h = alloc_call(cx, id, 1);
    weakref_call(cx, WeakRefOp::New, h, referent);
    Ok(LoweredValue::Packed(handle_as_packed(cx, h)))
}

// --- The built-in `semaphore` class (classes plan Task 17, LRM 1800-2023
// 15.3). An instance is an ordinary one-word heap object holding the key count;
// the waiting queue and the grant policy live in
// `sv_sim_sim::sched::semaphore`, reached through `sv_sim_runtime::semaphore_rt`.

fn semaphore_fn<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> FunctionValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let symbol = sv_sim_runtime::semaphore_rt::SV_RT_SEMAPHORE_SYMBOL;
    cx.module.get_function(symbol).unwrap_or_else(|| {
        cx.module.add_function(
            symbol,
            i64t.fn_type(&[i32t.into(), i64t.into(), i64t.into()], false),
            Some(Linkage::External),
        )
    })
}

/// `sv_rt_semaphore(op, h, arg)`.
pub(crate) fn semaphore_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    op: sv_sim_runtime::semaphore_rt::SemaphoreOp,
    h: IntValue<'ctx>,
    arg: IntValue<'ctx>,
) -> IntValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    cx.b.build_call(
        semaphore_fn(cx),
        &[
            i32t.const_int(op as u32 as u64, false).into(),
            h.into(),
            arg.into(),
        ],
        "semaphore_call",
    )
    .unwrap()
    .try_as_basic_value()
    .basic()
    .expect("sv_rt_semaphore returns a value")
    .into_int_value()
}

/// The `int keyCount` argument of a semaphore method, sign-extended to 64 bits;
/// `default` when the call omitted it (`get()`, `put()` and `try_get()` default
/// to one key, 15.3.3-15.3.5). It is the operand after the receiver.
fn semaphore_count_arg<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    call: sv_lang::Expression<'d>,
    default: u64,
) -> Result<IntValue<'ctx>, LoweringError> {
    match call.operands().get(1).copied() {
        Some(e) => crate::strings::index_i64(cx, e),
        None => Ok(cx.ctx.i64_type().const_int(default, false)),
    }
}

/// A method of `semaphore`: `put`, `get` or `try_get` through a handle; `new` is
/// [`lower_new_semaphore`]'s. A call through a null semaphore handle is reported
/// like `$error` (the LRM leaves it undefined) and then does nothing -- a `get`
/// does not block, `try_get` reads 0. A blocking `get` is a suspend point of the
/// calling process: the CFG walker (`sv_sim_sim::process::cfg`) yields right
/// after the statement, and the runtime has queued the request that keeps the
/// process blocked until a `put` grants its keys.
fn lower_semaphore_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    call: sv_lang::Expression<'d>,
    callee: sv_lang::Symbol<'d>,
) -> Result<ProcessCall<'ctx>, LoweringError> {
    use sv_sim_runtime::semaphore_rt::SemaphoreOp;

    let at = call.source_range().start;
    let i64t = cx.ctx.i64_type();
    let method = callee.name();
    let op = match method {
        "put" => SemaphoreOp::Put,
        "get" => SemaphoreOp::Get,
        "try_get" => SemaphoreOp::TryGet,
        other => {
            return Err(LoweringError::unsupported_at(
                &format!("calling semaphore::{other} is not implemented"),
                &cx.fn_sym,
            ));
        }
    };
    let recv = call.call_this_class().ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!("semaphore::{method} called without a semaphore handle"),
            &cx.fn_sym,
        )
    })?;
    let h = receiver_handle(cx, recv)?;
    let null =
        cx.b.build_int_compare(IntPredicate::EQ, h, i64t.const_zero(), "semaphore_null")
            .unwrap();
    crate::stmt_shared::error_if(
        cx,
        null,
        at,
        &format!("null semaphore handle: call of semaphore::{method}"),
    )?;
    let arg = semaphore_count_arg(cx, call, 1)?;
    // A negative keyCount "shall result in an error" in all three methods
    // (15.3.2-15.3.4); the runtime then leaves the bucket alone and `try_get`
    // returns 0, which is what the LRM says it returns for a negative count.
    let negative =
        cx.b.build_int_compare(IntPredicate::SLT, arg, i64t.const_zero(), "semaphore_neg")
            .unwrap();
    crate::stmt_shared::error_if(
        cx,
        negative,
        at,
        &format!("semaphore::{method}: negative keyCount"),
    )?;
    let ret = semaphore_call(cx, op, h, arg);
    if op != SemaphoreOp::TryGet {
        return Ok(ProcessCall::Lowered(None));
    }
    let ty = callee.subroutine_return_type().ok_or_else(|| {
        LoweringError::unsupported_at("semaphore::try_get has no type", &cx.fn_sym)
    })?;
    let width = ty.value_width();
    let opb = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let val =
        cx.b.build_int_truncate_or_bit_cast(ret, opb.i_n(width), "try_get")
            .unwrap();
    let unk = val.get_type().const_zero();
    Ok(ProcessCall::Lowered(Some(LoweredValue::Packed(opb.pack(
        val,
        unk,
        width,
        cx.repr,
        ty.is_signed(),
    )))))
}

/// `new(keyCount)` on `semaphore` (LRM 15.3.1): a one-word heap object holding
/// the initial key count (`0` when `new()` omits it).
fn lower_new_semaphore<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
    class_sym: &sv_lang::Symbol<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    use sv_sim_runtime::semaphore_rt::{SEMAPHORE_FIELD_WORDS, SemaphoreOp};

    let count = match e
        .new_class_constructor_call()
        .and_then(|c| c.operands().first().copied())
        .or_else(|| e.operands().first().copied())
    {
        Some(arg) => crate::strings::index_i64(cx, arg)?,
        None => cx.ctx.i64_type().const_zero(),
    };
    let id = class_template_id_of(class_sym)?;
    let h = alloc_call(cx, id, SEMAPHORE_FIELD_WORDS);
    semaphore_call(cx, SemaphoreOp::New, h, count);
    Ok(LoweredValue::Packed(handle_as_packed(cx, h)))
}

// --- The built-in `mailbox` class (classes plan Task 18, LRM 1800-2023 15.4).
// An instance is an ordinary one-word heap object; its message queue and the
// processes blocked on it live in `sv_sim_sim::sched::mailbox`, reached through
// `sv_sim_runtime::mailbox_rt` (whose module doc has the blocking protocol and
// the return codes this code decodes).
//
// A message is stored like a collection element (the 4-state packed form of the
// message type, class handles as one owned reference), so the element helpers of
// `crate::collections` do the packing: a `Coll` describes the message shape.
//
// A blocking `get`/`peek` is lowered TWICE by the CFG walker (once before and
// once after its suspend point, `sv_sim_sim::process::cfg`): the first call
// takes a message that is already there or blocks the process; the second
// delivers the message a `put` handed to the waiter. Both run the same code
// below, so the destination and the receiver are evaluated in both phases --
// which is why a destination or receiver with side effects is refused.

/// The type-check key of a mailbox message type: equal for equivalent types
/// (LRM 6.22.2) and different otherwise. An integral type is identified by
/// width, signing and 4-state-ness, a real by width, a string and a class by
/// name; any other type (enum, struct, array) by its spelled-out canonical form
/// (so two typedefs of one type match, two distinct types do not).
fn mailbox_type_fingerprint(ty: &sv_lang::Type<'_>) -> u64 {
    let t = ty.canonical();
    let key = if t.is_string() {
        "string".to_string()
    } else if t.is_class() {
        format!("class:{}", t.to_sv_string())
    } else if t.is_floating() {
        format!("float:{}", t.bit_width())
    } else if t.is_integral() && !t.is_enum() && !t.is_struct() {
        format!(
            "int:{}:{}:{}",
            t.bit_width(),
            t.is_signed(),
            t.is_four_state()
        )
    } else {
        format!("other:{}", t.to_sv_string())
    };
    // 64-bit FNV-1a.
    key.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
    })
}

/// A message type's storage shape. Class handles are one owned reference;
/// anything else must hold no reference-counted handle (a queue, or a struct
/// with a class handle inside, would be copied as bare bits).
fn mailbox_message_shape<'d>(
    cx: &LowerCtx<'_, 'd, '_>,
    ty: &sv_lang::Type<'d>,
) -> Result<crate::collections::Coll<'d>, LoweringError> {
    if ty.is_untyped_type() {
        return Err(LoweringError::unsupported_at(
            "a mailbox message of no type",
            &cx.fn_sym,
        ));
    }
    let obj = ty.is_class();
    // A queue, dynamic array or associative array message is ONE collection
    // handle the mailbox owns (a `put` stores a copy, a `peek` a
    // copy-on-write clone, LRM 15.4.3, 15.4.8).
    let coll = sv_sim_sim::state::storage::is_collection(ty);
    if !obj && !coll && !crate::collections::handle_offsets(ty).is_empty() {
        return Err(LoweringError::unsupported_at(
            &format!(
                "a mailbox message of type `{}`, which holds a queue, dynamic or associative \
                 array or a class handle inside a struct, union or fixed-size array",
                ty.to_sv_string()
            ),
            &cx.fn_sym,
        ));
    }
    let width = if coll { 64 } else { ty.value_width().max(1) };
    Ok(crate::collections::Coll {
        elem: *ty,
        width,
        words: (2 * width).div_ceil(64).max(1),
        assoc: false,
        queue: false,
        bound: 0,
        key_kind: 0,
        key_width: 0,
        obj,
        leaky: false,
    })
}

/// `e` without the conversion slang wraps around an argument bound to an
/// untyped (`mailbox` with no `#(T)`) formal, so the argument keeps the type
/// it was written with.
fn strip_untyped_conversion<'d>(e: sv_lang::Expression<'d>) -> sv_lang::Expression<'d> {
    let mut e = e;
    while e.kind() == ExpressionKind::Conversion
        && e.expr_type().is_some_and(|t| t.is_untyped_type())
        && let Some(inner) = e.operand()
    {
        e = inner;
    }
    e
}

/// Whether evaluating `e` can change anything (a call, an assignment, `++`/`--`
/// anywhere inside it).
pub(crate) fn has_side_effects(e: sv_lang::Expression<'_>) -> bool {
    use sv_lang::UnaryOp;
    let kind = e.kind();
    // Not a `match` over the kind: every other expression is side-effect free
    // itself and is searched through its operands.
    if kind == ExpressionKind::Call || kind == ExpressionKind::Assignment {
        return true;
    }
    if kind == ExpressionKind::UnaryOp
        && matches!(
            e.unary_op(),
            Some(
                UnaryOp::Preincrement
                    | UnaryOp::Predecrement
                    | UnaryOp::Postincrement
                    | UnaryOp::Postdecrement
            )
        )
    {
        return true;
    }
    e.operands().into_iter().any(has_side_effects)
}

fn mailbox_fn<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> FunctionValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let ptr = cx.ctx.ptr_type(AddressSpace::default());
    let symbol = sv_sim_runtime::mailbox_rt::SV_RT_MAILBOX_SYMBOL;
    cx.module.get_function(symbol).unwrap_or_else(|| {
        cx.module.add_function(
            symbol,
            i64t.fn_type(&[i32t.into(), i64t.into(), ptr.into()], false),
            Some(Linkage::External),
        )
    })
}

/// `MailboxArgs::obj` for a message of shape `c`: what word 0 owns.
fn mailbox_owner_kind(c: &crate::collections::Coll<'_>) -> u64 {
    use sv_sim_runtime::mailbox_rt::{OWNS_COLLECTION, OWNS_OBJECT};
    if c.obj {
        u64::from(OWNS_OBJECT)
    } else if sv_sim_sim::state::storage::is_collection(&c.elem) {
        u64::from(OWNS_COLLECTION)
    } else {
        0
    }
}

/// `sv_rt_mailbox(op, h, &args)`, the argument block laid out like
/// `MailboxArgs` (`{ u32 words, u32 obj, u64 fingerprint, ptr msg, i64 bound }`).
/// `msg` is the message buffer of the shape `c`; `None` for `new` and `num`.
fn mailbox_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    op: sv_sim_runtime::mailbox_rt::MailboxOp,
    h: IntValue<'ctx>,
    msg: Option<(&crate::collections::Coll<'_>, u64, PointerValue<'ctx>)>,
    bound: IntValue<'ctx>,
) -> IntValue<'ctx> {
    let i32t = cx.ctx.i32_type();
    let i64t = cx.ctx.i64_type();
    let ptr_t = cx.ctx.ptr_type(AddressSpace::default());
    let ty = cx.ctx.struct_type(
        &[
            i32t.into(),
            i32t.into(),
            i64t.into(),
            ptr_t.into(),
            i64t.into(),
        ],
        false,
    );
    let args = entry_alloca(cx, ty, "mailbox_args");
    let (words, obj, fingerprint, buf) = match msg {
        Some((c, fp, buf)) => (u64::from(c.words), mailbox_owner_kind(c), fp, buf),
        None => (0, 0, 0, ptr_t.const_null()),
    };
    let fields: [inkwell::values::BasicValueEnum<'ctx>; 5] = [
        i32t.const_int(words, false).into(),
        i32t.const_int(obj, false).into(),
        i64t.const_int(fingerprint, false).into(),
        buf.into(),
        bound.into(),
    ];
    for (i, v) in fields.into_iter().enumerate() {
        let p =
            cx.b.build_struct_gep(ty, args, i as u32, "mailbox_arg")
                .unwrap();
        cx.b.build_store(p, v).unwrap();
    }
    cx.b.build_call(
        mailbox_fn(cx),
        &[
            i32t.const_int(op as u32 as u64, false).into(),
            h.into(),
            args.into(),
        ],
        "mailbox_call",
    )
    .unwrap()
    .try_as_basic_value()
    .basic()
    .expect("sv_rt_mailbox returns a value")
    .into_int_value()
}

/// Runs `body` only when `cond` (an `i1`) holds, then continues after it.
fn if_then<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    cond: IntValue<'ctx>,
    name: &str,
    body: impl FnOnce() -> Result<(), LoweringError>,
) -> Result<(), LoweringError> {
    let (_, f) = crate::stmt_shared::current_block_and_fn(cx)?;
    let then_bb = cx.ctx.append_basic_block(f, &format!("{name}_then"));
    let done_bb = cx.ctx.append_basic_block(f, &format!("{name}_done"));
    cx.b.build_conditional_branch(cond, then_bb, done_bb)
        .unwrap();
    cx.b.position_at_end(then_bb);
    body()?;
    cx.b.build_unconditional_branch(done_bb).unwrap();
    cx.b.position_at_end(done_bb);
    Ok(())
}

/// An `i1` that holds when the calling process starts a blocking `get`/`peek`
/// statement (its first phase, `MailboxOp::Phase`).
fn mailbox_first_phase<'ctx>(cx: &LowerCtx<'ctx, '_, '_>) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let second = mailbox_call(
        cx,
        sv_sim_runtime::mailbox_rt::MailboxOp::Phase,
        i64t.const_zero(),
        None,
        i64t.const_zero(),
    );
    cx.b.build_int_compare(IntPredicate::EQ, second, i64t.const_zero(), "mailbox_first")
        .unwrap()
}

/// Evaluates the parts of the blocking `get`/`peek` destination `arg` that run
/// code (a select index with `++` or a call) ONCE: in the first phase, saving
/// each value in the runtime's per-process stash across the suspend; both
/// phases then read the values back, and the returned guard makes the
/// destination's lvalue lowering use them ([`crate::vif::hoisted`]). A
/// destination without such parts costs nothing.
fn mailbox_hoist_destination<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    arg: &sv_lang::Expression<'d>,
) -> Result<crate::vif::Hoisted, LoweringError> {
    use sv_sim_runtime::mailbox_rt::MailboxOp;
    let guard = crate::vif::hoist_begin();
    if !has_side_effects(*arg) {
        return Ok(guard);
    }
    let (parts, terminal) = crate::vif::side_effect_selectors(arg);
    if has_side_effects(terminal) {
        return Err(LoweringError::unsupported_at(
            "mailbox get/peek into a destination whose base expression runs code",
            &cx.fn_sym,
        ));
    }
    let i64t = cx.ctx.i64_type();
    let mut slot = 0u64;
    // Outside-in; evaluate the innermost (leftmost) first.
    for p in parts.into_iter().rev() {
        let mut meta = None;
        let first = mailbox_first_phase(cx);
        let first_slot = slot;
        if_then(cx, first, "mailbox_dest", || {
            let pv = lower_expr(cx, p)?.into_packed("a mailbox destination part", &cx.fn_sym)?;
            let bits = pv.llvm.get_type().get_bit_width();
            if bits > 256 {
                return Err(LoweringError::unsupported_at(
                    "mailbox get/peek destination part wider than 256 bits",
                    &cx.fn_sym,
                ));
            }
            for c in 0..bits.div_ceil(64) {
                let shifted = if c == 0 {
                    pv.llvm
                } else {
                    cx.b.build_right_shift(
                        pv.llvm,
                        pv.llvm.get_type().const_int(u64::from(64 * c), false),
                        false,
                        "mailbox_dest_shr",
                    )
                    .unwrap()
                };
                let chunk = if bits <= 64 {
                    cx.b.build_int_z_extend_or_bit_cast(shifted, i64t, "w")
                        .unwrap()
                } else {
                    cx.b.build_int_truncate_or_bit_cast(shifted, i64t, "w")
                        .unwrap()
                };
                mailbox_call(
                    cx,
                    MailboxOp::StashSet,
                    i64t.const_int(first_slot + u64::from(c), false),
                    None,
                    chunk,
                );
            }
            meta = Some((pv.llvm.get_type(), pv.width, pv.repr, pv.signed));
            Ok(())
        })?;
        let (ty, width, repr, signed) = meta.expect("the closure ran at lowering time");
        let bits = ty.get_bit_width();
        let mut acc = ty.const_zero();
        for c in 0..bits.div_ceil(64) {
            let w = mailbox_call(
                cx,
                MailboxOp::StashGet,
                i64t.const_int(slot + u64::from(c), false),
                None,
                i64t.const_zero(),
            );
            let w = if bits <= 64 {
                cx.b.build_int_truncate_or_bit_cast(w, ty, "w").unwrap()
            } else {
                cx.b.build_int_z_extend_or_bit_cast(w, ty, "w").unwrap()
            };
            let w = if c == 0 {
                w
            } else {
                cx.b.build_left_shift(w, ty.const_int(u64::from(64 * c), false), "w")
                    .unwrap()
            };
            acc = cx.b.build_or(acc, w, "w").unwrap();
        }
        slot += u64::from(bits.div_ceil(64));
        crate::vif::hoist_push(
            &p,
            crate::value::PackedValue {
                llvm: acc,
                width,
                repr,
                signed,
            },
        );
    }
    Ok(guard)
}

/// A method of `mailbox`: `num`, `put`, `try_put`, `get`, `try_get`, `peek` or
/// `try_peek` through a handle; `new` is [`lower_new_mailbox`]'s. A call through
/// a null mailbox handle is reported like `$error` (the LRM leaves it undefined)
/// and then does nothing -- a `get` does not block and `try_*` read as failed.
///
/// * `put` of a message into a full bounded mailbox, and `get`/`peek` of an
///   empty one, block the calling process (a suspend point of the CFG walker).
/// * A take whose destination is not of the message's type is a run-time error
///   for `get`/`peek` (the message stays in the mailbox) and the result `-1` for
///   `try_get`/`try_peek` (LRM 15.4.6, 15.4.8). The type is checked by
///   [`mailbox_type_fingerprint`]; a typed mailbox's messages all have its `T`.
fn lower_mailbox_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    call: sv_lang::Expression<'d>,
    callee: sv_lang::Symbol<'d>,
) -> Result<ProcessCall<'ctx>, LoweringError> {
    use sv_sim_runtime::mailbox_rt::MailboxOp;

    let at = call.source_range().start;
    let i64t = cx.ctx.i64_type();
    let method = callee.name();
    let op = match method {
        "num" => MailboxOp::Num,
        "put" => MailboxOp::Put,
        "try_put" => MailboxOp::TryPut,
        "get" => MailboxOp::Get,
        "try_get" => MailboxOp::TryGet,
        "peek" => MailboxOp::Peek,
        "try_peek" => MailboxOp::TryPeek,
        other => {
            return Err(LoweringError::unsupported_at(
                &format!("calling mailbox::{other} is not implemented"),
                &cx.fn_sym,
            ));
        }
    };
    let recv = call.call_this_class().ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!("mailbox::{method} called without a mailbox handle"),
            &cx.fn_sym,
        )
    })?;
    let blocking_take = matches!(op, MailboxOp::Get | MailboxOp::Peek);
    // A blocking `get`/`peek` runs twice (see the module comment): a receiver
    // that runs code is evaluated in the first phase only (the second reads
    // no handle: the runtime keys the delivery by process).
    let h = if blocking_take && has_side_effects(recv) {
        let slot = entry_alloca(cx, i64t, "mailbox_recv");
        cx.b.build_store(slot, i64t.const_zero()).unwrap();
        let first = mailbox_first_phase(cx);
        if_then(cx, first, "mailbox_recv", || {
            let h = receiver_handle(cx, recv)?;
            cx.b.build_store(slot, h).unwrap();
            Ok(())
        })?;
        cx.b.build_load(i64t, slot, "mailbox_recv_h")
            .unwrap()
            .into_int_value()
    } else {
        receiver_handle(cx, recv)?
    };
    let null_msg = format!("null mailbox handle: call of mailbox::{method}");
    // A blocking `get`/`peek` runs twice (see the module comment of
    // `sched::mailbox`); only its first phase reports a null handle, through the
    // runtime's return code, so the error is raised once.
    if !blocking_take {
        let null =
            cx.b.build_int_compare(IntPredicate::EQ, h, i64t.const_zero(), "mailbox_null")
                .unwrap();
        crate::stmt_shared::error_if(cx, null, at, &null_msg)?;
    }
    if op == MailboxOp::Num {
        let ret = mailbox_call(cx, op, h, None, i64t.const_zero());
        return Ok(ProcessCall::Lowered(Some(crate::collections::int(cx, ret))));
    }
    let arg = call.operands().get(1).copied().ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!("mailbox::{method} called without its message argument"),
            &cx.fn_sym,
        )
    })?;
    // `message` is the first formal; an untyped mailbox's has no type, so the
    // message type is the argument's own.
    let formal_ty = callee
        .subroutine_arguments()
        .next()
        .and_then(|f| f.value_type())
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                &format!("mailbox::{method} has no message formal"),
                &cx.fn_sym,
            )
        })?;
    let untyped = formal_ty.is_untyped_type();
    let arg = if untyped {
        strip_untyped_conversion(arg)
    } else {
        arg
    };
    let arg = match op {
        // A `ref` argument: the variable itself (some bindings wrap it).
        MailboxOp::Get | MailboxOp::TryGet | MailboxOp::Peek | MailboxOp::TryPeek
            if arg.kind() == ExpressionKind::Assignment =>
        {
            arg.left().unwrap_or(arg)
        }
        _ => arg,
    };
    let msg_ty = if untyped {
        arg.expr_type().ok_or_else(|| {
            LoweringError::unsupported_at("a mailbox message with no type", &cx.fn_sym)
        })?
    } else {
        formal_ty
    };
    let c = mailbox_message_shape(cx, &msg_ty)?;
    let fp = mailbox_type_fingerprint(&msg_ty);
    let zero = i64t.const_zero();
    match op {
        MailboxOp::Put | MailboxOp::TryPut => {
            // The queue takes over one reference to a class message, or an
            // owned copy of a collection message.
            let owns = mailbox_owner_kind(&c) != 0;
            let v = if owns {
                crate::collections::owned(cx, arg)?
            } else {
                crate::collections::elem_value(cx, &c, arg)?
            };
            let handle = match v {
                LoweredValue::Packed(pv) if owns => Some(crate::collections::op(cx).lane_val(pv)),
                _ => None,
            };
            let buf = crate::collections::elem_buf(cx, &c, v)?;
            let ret = mailbox_call(cx, op, h, Some((&c, fp, buf)), zero);
            if op == MailboxOp::Put {
                return Ok(ProcessCall::Lowered(None));
            }
            // A full mailbox leaves the reference with the caller: drop it.
            if let Some(handle) = handle {
                let full =
                    cx.b.build_int_compare(IntPredicate::EQ, ret, zero, "mailbox_full")
                        .unwrap();
                if_then(cx, full, "mailbox_refused", || {
                    if c.obj {
                        release_handle(cx, handle);
                    } else {
                        crate::collections::raw_call(
                            cx,
                            [1, 0, 0, 0, 0],
                            sv_sim_runtime::collections_rt::CollOp::Release,
                            handle,
                            crate::collections::Args::default(),
                        );
                    }
                    Ok(())
                })?;
            }
            Ok(ProcessCall::Lowered(Some(crate::collections::int(cx, ret))))
        }
        MailboxOp::Get | MailboxOp::TryGet | MailboxOp::Peek | MailboxOp::TryPeek => {
            // A destination that runs code (`m.get(a[i++])`) is evaluated once,
            // in the first phase; the second reads the saved values.
            let _once = if blocking_take {
                mailbox_hoist_destination(cx, &arg)?
            } else {
                crate::vif::hoist_begin()
            };
            let out = entry_alloca(
                cx,
                OpBuilder {
                    ctx: cx.ctx,
                    b: &cx.b,
                }
                .i_n(64 * c.words),
                "mailbox_out",
            );
            let ret = mailbox_call(cx, op, h, Some((&c, fp, out)), zero);
            if blocking_take {
                let no_mailbox =
                    cx.b.build_int_compare(
                        IntPredicate::EQ,
                        ret,
                        i64t.const_int(4, false),
                        "mailbox_none",
                    )
                    .unwrap();
                crate::stmt_shared::error_if(cx, no_mailbox, at, &null_msg)?;
                let bad =
                    cx.b.build_int_compare(
                        IntPredicate::EQ,
                        ret,
                        i64t.const_int(3, false),
                        "mailbox_mismatch",
                    )
                    .unwrap();
                crate::stmt_shared::error_if(
                    cx,
                    bad,
                    at,
                    &format!(
                        "mailbox::{method}: the message is not of the type of the variable \
                         (`{}`)",
                        msg_ty.to_sv_string()
                    ),
                )?;
            }
            let got =
                cx.b.build_int_compare(
                    IntPredicate::EQ,
                    ret,
                    i64t.const_int(1, false),
                    "mailbox_got",
                )
                .unwrap();
            if_then(cx, got, "mailbox_deliver", || {
                let v = match crate::collections::load_elem(cx, &c, out) {
                    LoweredValue::Packed(pv) if c.elem.is_string() => {
                        LoweredValue::Str(crate::strings::StrValue {
                            llvm: crate::collections::op(cx).lane_val(pv),
                        })
                    }
                    v => v,
                };
                // The delivered class handle carries its own reference (a
                // `peek` was given a retained one): the destination takes it
                // over and drops what it held.
                let owns = mailbox_owner_kind(&c) != 0;
                if owns && sv_sim_sim::symid::is_value_name(arg.kind()) {
                    crate::collections::release_old(cx, arg)?;
                    crate::expr::store_to(cx, arg, v)?;
                } else if owns {
                    crate::collections::store_releasing(cx, arg, v)?;
                } else {
                    crate::expr::store_to(cx, arg, v)?;
                }
                Ok(())
            })?;
            if blocking_take {
                Ok(ProcessCall::Lowered(None))
            } else {
                Ok(ProcessCall::Lowered(Some(crate::collections::int(cx, ret))))
            }
        }
        MailboxOp::New
        | MailboxOp::Num
        | MailboxOp::Phase
        | MailboxOp::StashSet
        | MailboxOp::StashGet => unreachable!("handled above"),
    }
}

/// `new(bound)` on `mailbox` (LRM 15.4.1): a one-word heap object whose queue
/// lives in the scheduler, bounded to `bound` messages (`0`, the default, and a
/// negative `bound` mean unbounded).
fn lower_new_mailbox<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
    class_sym: &sv_lang::Symbol<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    use sv_sim_runtime::mailbox_rt::{MAILBOX_FIELD_WORDS, MailboxOp};

    let bound = match e
        .new_class_constructor_call()
        .and_then(|c| c.operands().first().copied())
        .or_else(|| e.operands().first().copied())
    {
        Some(arg) => crate::strings::index_i64(cx, arg)?,
        None => cx.ctx.i64_type().const_zero(),
    };
    let id = class_template_id_of(class_sym)?;
    let h = alloc_call(cx, id, MAILBOX_FIELD_WORDS);
    mailbox_call(cx, MailboxOp::New, h, None, bound);
    Ok(LoweredValue::Packed(handle_as_packed(cx, h)))
}

/// The three built-in random-stability methods every user class has (LRM
/// 1800-2023 18.13): `obj.srandom(seed)`, `obj.get_randstate()` and
/// `obj.set_randstate(state)`, plus the same names called bare inside a method
/// (implicit `this`). Slang synthesizes them as `BUILT_IN` members of the class,
/// with no SV body for the class sub-pass to have compiled, so they are lowered
/// here to `sv_rt_obj`'s `SRandom`/`GetRandState`/`SetRandState` ops, which
/// address the object's own generator ([`sv_sim_sim::objects::prng_seed`]).
/// [`ProcessCall::NotProcess`] for any other call. A null receiver is reported
/// like a null `process` handle and then does nothing (`get_randstate` reads
/// the empty string).
fn lower_object_rng_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    call: sv_lang::Expression<'d>,
    callee: sv_lang::Symbol<'d>,
    class_sym: sv_lang::Symbol<'d>,
) -> Result<ProcessCall<'ctx>, LoweringError> {
    // The built-in `pre_randomize()`/`post_randomize()` (LRM 18.6.2) of a
    // class that declares none: the nearest base's hook, or nothing.
    if matches!(callee.name(), "pre_randomize" | "post_randomize")
        && matches!(
            class_sym.kind(),
            SymbolKind::ClassType | SymbolKind::GenericClassDef
        )
        && callee
            .subroutine_flags()
            .contains(sv_lang::MethodFlags::BUILT_IN)
    {
        crate::classes_randomize::lower_builtin_hook_call(cx, call, callee, class_sym)?;
        return Ok(ProcessCall::Lowered(None));
    }
    // `obj.rand_mode(on)` / `obj.constraint_mode(on)` (LRM 18.8, 18.9).
    if matches!(callee.name(), "rand_mode" | "constraint_mode")
        && matches!(
            class_sym.kind(),
            SymbolKind::ClassType | SymbolKind::GenericClassDef
        )
        && callee
            .subroutine_flags()
            .contains(sv_lang::MethodFlags::BUILT_IN)
    {
        return crate::rand_mode::lower_object_mode_call(cx, call, callee);
    }
    let op = match callee.name() {
        "srandom" => ObjOp::SRandom,
        "get_randstate" => ObjOp::GetRandState,
        "set_randstate" => ObjOp::SetRandState,
        _ => return Ok(ProcessCall::NotProcess),
    };
    if !matches!(
        class_sym.kind(),
        SymbolKind::ClassType | SymbolKind::GenericClassDef
    ) || !callee
        .subroutine_flags()
        .contains(sv_lang::MethodFlags::BUILT_IN)
    {
        return Ok(ProcessCall::NotProcess);
    }
    let method = callee.name();
    let at = call.source_range().start;
    let i64t = cx.ctx.i64_type();
    let recv = call.call_this_class();
    let h = match recv {
        Some(recv) => receiver_handle(cx, recv)?,
        // `srandom(5);` inside a method: the current object.
        None => current_this_handle(cx)?,
    };
    let null =
        cx.b.build_int_compare(IntPredicate::EQ, h, i64t.const_zero(), "obj_rng_null")
            .unwrap();
    crate::stmt_shared::error_if(
        cx,
        null,
        at,
        &format!("null object handle: call of {method}"),
    )?;
    let mut actuals = call.operands();
    if recv.is_some() {
        actuals.remove(0);
    }
    let method_arg = |what: &str| {
        actuals.first().copied().ok_or_else(|| {
            LoweringError::unsupported_at(
                &format!("{method} called without its {what} argument"),
                &cx.fn_sym,
            )
        })
    };
    let arg = match op {
        ObjOp::SRandom => crate::strings::index_i64(cx, method_arg("seed")?)?,
        ObjOp::SetRandState => {
            crate::strings::to_string(cx, lower_expr(cx, method_arg("state")?)?)?.llvm
        }
        _ => i64t.const_zero(),
    };
    let null_ptr = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    let ret = obj_call(cx, op, h, arg, i64t.const_zero(), null_ptr);
    match op {
        ObjOp::GetRandState => Ok(ProcessCall::Lowered(Some(LoweredValue::Str(
            crate::strings::StrValue { llvm: ret },
        )))),
        _ => Ok(ProcessCall::Lowered(None)),
    }
}

/// Review fix (r2), Task 6 finding 1: `call.call_this_class()` is `None` not
/// only for a genuinely static call, but also for `super.method(...)`
/// (LRM 8.15) and a bare, implicit-`this` sibling-method call -- slang binds
/// BOTH the same way it binds `Class::method()` (§1.4/8.23): the lookup
/// (`Lookup::findSuperHandle`/unqualified-name lookup) resolves the callee
/// symbol directly, by scope, never through a `this`-bearing `MemberAccess`
/// node, so there is no receiver expression for `call_this_class()` to give
/// back even though the call DOES have a live receiver -- the CURRENT
/// object, exactly as if it had been written `this.method(...)`. The two
/// call sites below (`func.rs::lower_task_call`, `expr.rs::
/// lower_user_subroutine_call`) try this check, in this OR-fallback form,
/// right after their own `call_this_class()` check comes back empty; `None`
/// here means "not an instance-method call at all" (a plain subroutine, or
/// a genuinely static class method -- `resolve_or_lower_static_method`'s
/// own concern, reached via the existing generic path).
///
/// `callee.kind() == MethodPrototype` indirection mirrors
/// [`resolve_or_lower_static_method`]'s own identical dereference: `super.`
/// and a bare unqualified name both resolve through the SAME scope-lookup
/// machinery `Class::method()` colon-resolution uses (`Lookup::qualified`'s
/// own "pretend we used colon access" comment on `SyntaxKind::SuperHandle`),
/// which can hand back the in-class `extern` prototype symbol rather than
/// the out-of-block, `this`-bearing real subroutine -- the ordinary
/// `obj.method()`/`this.method()` dot-call path never needs this
/// dereference because `MemberAccessExpression` binding already resolves
/// all the way through for THAT shape, but nothing guarantees the identical
/// shortcut for a colon-style lookup.
///
/// Review fix (r2 #2), Task 7 finding 1: a bare/colon-style lookup can also
/// hand back (directly, or via the `MethodPrototype` dereference above) the
/// synthesized stub slang builds for a still-unimplemented `pure virtual`
/// method -- the EXACT SAME `subroutine_this_var() == None` shape a
/// genuine `static` method has ([`classify_virtual_member`]'s own doc
/// comment, and [`resolve_or_lower_static_method`]'s own identical fix for
/// the colon/explicit-receiver case). Without this, a bare call to a
/// method that is still pure virtual AT THE CALLING LEXICAL LEVEL (e.g.
/// `double_area()` on the declaring abstract class itself calling
/// `area()`) was misclassified as "not an instance-method call at all" and
/// fell through this predicate's two callers into the generic, non-class
/// `resolve_callee_fn` path, which has no declaration for the stub's own
/// mangled name (`pipeline::build_pipeline`'s method_specs pass
/// deliberately skips an unresolved pure-virtual stub) -- a hard JIT
/// "symbol not found" failure, confirmed live on `abstract_pure_virtual.sv`
/// before this fix. `is_virtual_method` (this module's own single source
/// of truth for "is this symbol virtual at all", already used by
/// `virtual_call_arms`/`lower_method_call`/`lower_method_task_call` further
/// down this same call) is reused here rather than re-deriving the same
/// classification by hand, so this predicate and the dispatch machinery it
/// gates can never disagree about which bare calls are virtual.
pub(crate) fn resolve_implicit_this_instance_method<'d>(
    callee: sv_lang::Symbol<'d>,
) -> Result<Option<sv_lang::Symbol<'d>>, LoweringError> {
    let callee = if callee.kind() == SymbolKind::MethodPrototype {
        let Some(real) = callee.method_prototype_subroutine() else {
            return Ok(None);
        };
        real
    } else {
        callee
    };
    let Some(class_sym) = callee.parent() else {
        return Ok(None);
    };
    if !matches!(
        class_sym.kind(),
        SymbolKind::ClassType | SymbolKind::GenericClassDef
    ) {
        return Ok(None);
    }
    if is_builtin_std_class(&class_sym).is_some() {
        // Tasks 13/17/18's own dedicated `sv_rt_*` dispatch (reached via
        // `reject_if_std_intrinsic` once routed through `lower_method_call`/
        // `lower_method_task_call` below) -- not this predicate's concern,
        // and in practice unreachable here anyway (every std-intrinsic
        // method is always called through an explicit receiver).
        return Ok(None);
    }
    if callee.subroutine_this_var().is_some() {
        return Ok(Some(callee));
    }
    // `this_var() == None` here is NOT proof this is a genuine `static`
    // method (see this function's own doc comment above) -- only
    // `is_virtual_method`'s own prototype-first classification can tell a
    // pure-virtual stub apart from a real static method, so defer to it
    // before concluding "not an instance-method call at all".
    if is_virtual_method(&callee)? {
        return Ok(Some(callee));
    }
    Ok(None)
}

/// Resolves `callee` (a method or the constructor) to its already-lowered
/// [`FunctionValue`] in `cx.module` (`pipeline::build_pipeline`'s own class
/// sub-pass declares/defines every reachable class's methods and
/// constructor into that one shared module before any process/subroutine
/// body is lowered -- `func::mangled_subroutine_name` is the SAME name both
/// that pass and this lookup compute), builds its SV-argument list via
/// [`crate::func::lower_call_args`] (empty hidden ABI params: a class
/// method's body can never reach a module-level signal, `subroutine_abi`'s
/// own `is_module_level_signal` gate), and prepends `h` as the implicit
/// receiver parameter (§1.3).
///
/// Deviation from the plan's literal §1.4 text: a genuinely CROSS-module
/// class method call (one `pipeline::build_pipeline` run calling into a
/// class another run's module owns) is out of this task's scope -- unlike
/// `func::resolve_callee_fn`'s own case 3, this never silently builds a
/// fresh, receiver-less `extern` declaration (which would be a real,
/// wrong-ABI miscompile for a method); it is instead this named, loud
/// error. Classes are not yet reachable across the module-per-top-instance
/// boundary `sv-sim run` builds today in the first place (no fixture in
/// this crate's probe corpus exercises more than one top instance sharing a
/// class), so this is a real but currently-unreachable scope limit, not a
/// silent narrowing of a case any fixture depends on.
fn build_method_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    callee: sv_lang::Symbol<'d>,
    h: IntValue<'ctx>,
    call: sv_lang::Expression<'d>,
) -> Result<
    (
        FunctionValue<'ctx>,
        Vec<BasicMetadataValueEnum<'ctx>>,
        Vec<CopyBack<'ctx, 'd>>,
    ),
    LoweringError,
> {
    let mangled = crate::func::mangled_subroutine_name(&callee)?;
    let fv = cx.module.get_function(&mangled).ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!(
                "class method/constructor `{mangled}` was not lowered into this module -- \
                 cross-module class method calls are not yet supported (classes plan Task 5 \
                 scope)"
            ),
            &cx.fn_sym,
        )
    })?;
    build_method_call_with(cx, fv, callee, h, call)
}

/// Classes plan Task 7: [`build_method_call`]'s own argument-marshaling
/// tail, factored out so [`virtual_call_arms`]'s own callers can reuse it
/// against a PRE-RESOLVED `fv` (one virtual-dispatch candidate's own
/// `FunctionValue`) while still marshaling arguments against `args_callee`
/// -- the call's STATIC callee symbol, whose formal-argument SHAPE every
/// candidate implementation is guaranteed to share bit-for-bit (8.14:
/// overriding members "shall have the same name, operand types ... as the
/// method being overridden"), so marshaling once against the static
/// callee's own formals is correct for every arm, never re-derived per
/// candidate.
fn build_method_call_with<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    fv: FunctionValue<'ctx>,
    args_callee: sv_lang::Symbol<'d>,
    h: IntValue<'ctx>,
    call: sv_lang::Expression<'d>,
) -> Result<
    (
        FunctionValue<'ctx>,
        Vec<BasicMetadataValueEnum<'ctx>>,
        Vec<CopyBack<'ctx, 'd>>,
    ),
    LoweringError,
> {
    let (mut llvm_args, copy_backs) = crate::func::lower_call_args(cx, &args_callee, call)?;
    // The static callee's hidden shadows (the union over every override, see
    // `register_method_names`) are replaced by this candidate's own below.
    let candidate_hidden = HIDDEN_SHADOWS.with(|m| {
        m.borrow()
            .get(fv.get_name().to_string_lossy().as_ref())
            .cloned()
    });
    if candidate_hidden.is_some() {
        let base = crate::func::subroutine_abi(&args_callee);
        if !base.needs_handle {
            let keep = llvm_args.len().saturating_sub(base.signals.len());
            llvm_args.truncate(keep);
        }
    }
    llvm_args.insert(0, h.into());
    // A virtual candidate can take hidden module-signal shadows its statically
    // named callee does not (they come from whatever the override calls,
    // transitively; see `method_fn_type`): pass the caller's own shadow of
    // each, or a scratch slot for a static input formal.
    // A candidate that stages a nonblocking assignment (10.4.2) or otherwise
    // uses the instance handle takes it as one more trailing parameter (after
    // the shadows) that its statically named callee does not.
    let wants_handle = candidate_hidden
        .as_ref()
        .is_some_and(|hidden| llvm_args.len() + hidden.len() + 1 == fv.count_params() as usize)
        && cx.mem_accessor.is_some();
    if llvm_args.len() < fv.count_params() as usize
        && let Some(hidden) = candidate_hidden
        && llvm_args.len() + hidden.len() + usize::from(wants_handle) == fv.count_params() as usize
        && hidden
            .iter()
            .all(|(id, w)| w.is_some() || cx.locals.contains_key(id))
    {
        let op = OpBuilder {
            ctx: cx.ctx,
            b: &cx.b,
        };
        for (id, w) in hidden {
            if let Some(&(ptr, _, _)) = cx.locals.get(&id) {
                llvm_args.push(ptr.into());
            } else if let Some(w) = w {
                let ty = op.packed_type(w, cx.repr);
                let scratch = entry_alloca(cx, ty, "static_formal_scratch");
                cx.b.build_store(scratch, ty.const_zero()).unwrap();
                llvm_args.push(scratch.into());
            }
        }
        if wants_handle && let Some(accessor) = cx.mem_accessor {
            llvm_args.push(accessor.handle.into());
        }
    }
    if llvm_args.len() != fv.count_params() as usize {
        return Err(LoweringError::unsupported_at(
            &format!(
                "class method/constructor call argument count ({}) does not match the callee's \
                 declared parameter count ({}, with the implicit receiver) (callee `{}`, \
                 implementation `{}` of type {})",
                llvm_args.len(),
                fv.count_params(),
                args_callee.name(),
                fv.get_name().to_string_lossy(),
                fv.get_type().print_to_string().to_string_lossy()
            ),
            &cx.fn_sym,
        ));
    }
    Ok((fv, llvm_args, copy_backs))
}

// --- Classes plan Task 7 (§1.3 "Vtables", §1.4 step 2): virtual dispatch.
//
// Design note -- a deliberate, named deviation from §1.3's literal "one
// `SV_SIM_CLASS_VTABLE_<mangled>` LLVM global array per concrete class,
// indexed by slot" text: this crate instead builds, AT EACH VIRTUAL CALL
// SITE, a chain of compare-and-branch arms (one per concrete class
// descendant that implements this call's slot), mirroring `vif.rs::
// call_arms`'s own already-proven shape for "dispatch to one of several
// known candidates based on a runtime id, falling through to a shared
// default for anything else" exactly. Both approaches are observationally
// identical (every candidate's own mangled function is resolved once, by
// name, from the SAME shared module every other class method is declared
// into); the switch/branch-chain shape was chosen because it makes the
// "no UB for a null/stale/cross-hierarchy handle" requirement trivial BY
// CONSTRUCTION (an LLVM `br`/compare chain's "no case matched" path is
// always a plain, defined jump to its `default`/next block, never a
// separate bounds-checked array index into a second, length-varying global
// this crate would otherwise have to guard by hand) rather than needing a
// second, per-class "how many slots does THIS vtable actually have" length
// table purely to keep a literal array-of-pointers indexing scheme safe.

// Classes plan Task 7: the per-pipeline-run registry `register_virtual_
// impls` builds once and `virtual_candidates` reads from -- maps a virtual
// method symbol's own `SymbolUid::uid` (an in-class raw member, OR, when
// that member is a `MethodPrototype`, its resolved out-of-block
// `Subroutine` too -- see `VtableLayout`'s own doc comment on why both keys
// are populated) to every CONCRETE class template that implements the same
// slot, each with that template's own resolved implementation's already-
// mangled name (a `String`, not a live `Symbol` -- this table deliberately
// carries no `'d`-lifetime-tied data, so it can be a plain `'static`
// thread-local exactly like `CLASS_TEMPLATE_IDS` above, for the identical
// "never cross-contaminate two unrelated `cargo test` compiles on different
// threads" reason that one's own doc comment gives).
//
// Classes plan Task 9: keyed by `(uid, declaring class's specialization key)`
// -- see `VtableLayout::declared_in`'s own doc comment for why the uid alone
// is ambiguous across the specializations of one generic class.
type VirtualImplKey = (SymbolId, String);
type VirtualImplMap = HashMap<VirtualImplKey, Vec<(ClassTemplateId, String)>>;

thread_local! {
    static VIRTUAL_IMPLS: RefCell<VirtualImplMap> = RefCell::new(HashMap::new());
}

/// `pipeline::build_pipeline`'s own class sub-pass calls this once, after
/// every class template's methods have been registered
/// ([`register_template`]) -- for every `(id, class_sym)` pair (which,
/// thanks to `run.rs`'s own `ancestor_types` extension, already includes
/// every ancestor of every `new()`-reachable class, concrete or abstract,
/// see [`VtableLayout::for_template`]'s own doc comment), walks its
/// [`VtableLayout`] and records every slot IT resolves (an abstract
/// ancestor's own still-unimplemented pure-virtual slot is simply skipped
/// here -- never a candidate, since no object's dynamic type is ever that
/// abstract template, D9) under every uid [`VtableLayout::by_uid`] knows for
/// that slot.
pub fn register_virtual_impls<'d>(
    classes: &[(ClassTemplateId, sv_lang::Symbol<'d>)],
) -> Result<(), LoweringError> {
    let mut map: VirtualImplMap = HashMap::new();
    // Every (slot's member uids, implementation) pair, for the abort fixed
    // point below.
    let mut impls: Vec<(Vec<SymbolId>, sv_lang::Symbol<'d>)> = Vec::new();
    for &(id, class_sym) in classes {
        let layout = VtableLayout::for_template(class_sym)?;
        for (slot, impl_sym) in layout.slots.iter().enumerate() {
            if let Some(impl_sym) = impl_sym {
                // An `extern` implementation's body hangs off its resolved
                // out-of-block `Subroutine`, not the in-class prototype.
                let impl_sym = if impl_sym.kind() == SymbolKind::MethodPrototype {
                    impl_sym.method_prototype_subroutine().unwrap_or(*impl_sym)
                } else {
                    *impl_sym
                };
                let uids = layout
                    .by_uid
                    .iter()
                    .filter(|&(_, &s)| s == slot)
                    .map(|(uid, _)| uid.clone())
                    .collect();
                impls.push((uids, impl_sym));
            }
        }
        for (uid, &slot) in &layout.by_uid {
            let Some(impl_sym) = layout.slots[slot] else {
                continue;
            };
            let declared_in = layout.declared_in.get(uid).ok_or_else(|| {
                LoweringError::unsupported_at(
                    "internal: a vtable-slot member has no recorded declaring class",
                    &class_sym,
                )
            })?;
            let mangled = crate::func::mangled_subroutine_name(&impl_sym)?;
            map.entry((uid.clone(), declared_in.clone()))
                .or_default()
                .push((id, mangled));
        }
    }
    VIRTUAL_IMPLS.with(|c| *c.borrow_mut() = map);
    // A virtual call can run any implementation of its slot, and a failing
    // `$cast`/`$fatal`/`$finish` in one must stop the caller (LRM 1800-2023
    // 6.24.2, 20.2/20.10), so every member of a slot with an aborting
    // implementation is marked -- to a fixed point, since an implementation
    // may itself reach the abort only through another virtual call (or a
    // constructor/subroutine that does).
    sv_sim_sim::process::cfg::reset_aborting_virtuals();
    // `randomize()` runs the `pre_/post_randomize()` hooks of whichever class
    // it reaches (LRM 18.6.2), so once any hook can abort every `randomize()`
    // call can: part of the same fixed point (a hook may reach the abort
    // through a virtual call, and a virtual method through a `randomize()`).
    let hooks = crate::classes_randomize::register_hook_impls(classes)?;
    loop {
        let mut changed = false;
        if !sv_sim_sim::process::cfg::randomize_can_abort()
            && hooks
                .iter()
                .any(|h| sv_sim_sim::process::cfg::subroutine_can_abort(h))
        {
            changed |= sv_sim_sim::process::cfg::set_randomize_can_abort();
        }
        for (uids, impl_sym) in &impls {
            if sv_sim_sim::process::cfg::subroutine_can_abort(impl_sym) {
                for uid in uids {
                    changed |= sv_sim_sim::process::cfg::mark_aborting_virtual(uid.clone());
                }
            }
        }
        if !changed {
            break;
        }
    }
    crate::classes_randomize::settle_hook_aborts(&hooks);
    Ok(())
}

/// Every concrete class template that implements `callee`'s own slot, with
/// that template's own resolved implementation's mangled name -- empty if
/// `callee` is not virtual, or (an internal-consistency question, never a
/// reachable SV-source outcome once [`register_virtual_impls`] has run over
/// the whole design) its slot has no concrete implementer at all.
fn virtual_candidates(
    callee: &sv_lang::Symbol<'_>,
) -> Result<Vec<(ClassTemplateId, String)>, LoweringError> {
    let class_sym = callee.parent().ok_or_else(|| {
        LoweringError::unsupported_at("virtual method has no enclosing class", callee)
    })?;
    let key = (callee.uid(), specialization_key_of_symbol(&class_sym)?);
    Ok(VIRTUAL_IMPLS.with(|c| c.borrow().get(&key).cloned().unwrap_or_default()))
}

/// `sv_rt_obj(DynamicTemplate, h, <unused>)`'s call-site builder --
/// `objects::dynamic_template(h)`'s runtime id, or the documented
/// `u32::MAX` dead-handle sentinel (`objects_rt.rs::ObjOp::
/// DynamicTemplate`'s own doc comment), as a plain `i64`.
pub(crate) fn dynamic_template_call<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    h: IntValue<'ctx>,
) -> IntValue<'ctx> {
    let i64t = cx.ctx.i64_type();
    let null = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    obj_call(
        cx,
        ObjOp::DynamicTemplate,
        h,
        i64t.const_zero(),
        i64t.const_zero(),
        null,
    )
}

/// Classes plan Task 7 (§1.4 step 2's "virtual -> vtable load + indirect
/// call" branch): `Ok(None)` if `callee` is not virtual at all (the
/// caller's own existing direct-[`build_method_call`] path handles it
/// unchanged, zero extra codegen). Otherwise builds one compare-and-branch
/// arm per candidate concrete class ([`virtual_candidates`]), mirroring
/// [`crate::vif::call_arms`]'s own "falls through to the returned block
/// directly for anything that matches no candidate" shape exactly -- a
/// null, stale, or (impossible under a type-correct design, but never
/// trusted to not occur -- see this section's own design note) cross-
/// hierarchy handle simply matches no arm and reaches the returned block
/// with nothing having been called, the identical "no live candidate" outcome
/// `vif.rs` already gives a `null`/non-driving virtual-interface handle.
/// Every arm must end by branching to the returned block (the caller's own
/// concern, exactly as `vif::call_arms`'s own doc comment requires of ITS
/// callers).
#[allow(clippy::type_complexity)]
fn virtual_call_arms<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    callee: sv_lang::Symbol<'d>,
    h: IntValue<'ctx>,
) -> Result<
    Option<(
        Vec<(FunctionValue<'ctx>, inkwell::basic_block::BasicBlock<'ctx>)>,
        inkwell::basic_block::BasicBlock<'ctx>,
    )>,
    LoweringError,
> {
    if !is_virtual_method(&callee)? {
        return Ok(None);
    }
    let candidates = virtual_candidates(&callee)?;
    let f =
        cx.b.get_insert_block()
            .and_then(|bb| bb.get_parent())
            .expect("lowering happens inside a function");
    let merge = cx.ctx.append_basic_block(f, "virtual_call_done");
    let dyn_id = dynamic_template_call(cx, h);
    // One arm per DISTINCT implementation, reached by a `switch` on the
    // receiver's template id (every id whose slot resolves to the same
    // implementation shares that arm's block): a design with thousands of
    // class specializations inheriting one default (UVM's `get_full_name`)
    // would otherwise inline the whole call -- arguments, abort check,
    // copy-back -- once per specialization, which made UVM's
    // `uvm_objection::m_report` 2.2M lines of IR. An id matching none
    // reaches `merge` with nothing called, as before.
    let mut arms: Vec<(FunctionValue<'ctx>, inkwell::basic_block::BasicBlock<'ctx>)> = Vec::new();
    let mut impl_arm: HashMap<String, usize> = HashMap::new();
    let mut cases = Vec::new();
    for (id, mangled) in candidates {
        let k = match impl_arm.get(&mangled) {
            Some(&k) => k,
            None => {
                let fv = cx.module.get_function(&mangled).ok_or_else(|| {
                    LoweringError::unsupported_at(
                        &format!(
                            "internal: virtual method implementation `{mangled}` was not \
                             lowered into this module -- pipeline::build_pipeline's own class \
                             sub-pass must declare every class template \
                             register_virtual_impls walks before any call site is lowered"
                        ),
                        &cx.fn_sym,
                    )
                })?;
                let arm = cx.ctx.append_basic_block(f, "virtual_call");
                arms.push((fv, arm));
                impl_arm.insert(mangled, arms.len() - 1);
                arms.len() - 1
            }
        };
        cases.push((
            cx.ctx.i64_type().const_int(u64::from(id.0), false),
            arms[k].1,
        ));
    }
    cx.b.build_switch(dyn_id, merge, &cases).unwrap();
    Ok(Some((arms, merge)))
}

// --- Classes plan Task 7 (LRM 8.15): detecting an EXPLICIT `super.method(
// ...)` call, which §1.4's own design fixes as never virtually dispatched
// even when the callee is virtual -- the one piece of information
// `call_this_class()`/`call_subroutine()` alone cannot recover (verified
// live, `classes::tests::explicit_super_call_is_detected_only_for_an_
// actual_super_prefix`: a bare, implicit-`this` sibling call to a NOT-yet-
// overridden-in-this-class inherited method resolves to the EXACT SAME
// callee `Symbol` an explicit `super.` call to it would, yet the two must
// dispatch differently -- static for `super.`, virtual for bare -- so no
// symbol-level check can ever tell them apart; only the call's own SOURCE
// SYNTAX can).

thread_local! {
    /// The design's own syntax trees, held live only while
    /// `pipeline::build_pipeline` is lowering (entered/dropped exactly like
    /// `dpi.rs::DPI_DESIGN`, which this is deliberately NOT folded into: that
    /// thread-local's own name and `c_symbols` field are DPI-specific, and
    /// this need -- recovering one call expression's own source syntax -- is
    /// not).
    static DESIGN_SYNTAX_TREES: RefCell<Vec<sv_lang::SyntaxTree>> =
        const { RefCell::new(Vec::new()) };
}

/// Runs `f` over the design's own syntax trees (empty outside a
/// [`DesignSyntaxScope`]). The constraint builder reads `soft` markers from
/// them (`classes_randomize::build_program`).
pub(crate) fn with_design_trees<R>(f: impl FnOnce(&[sv_lang::SyntaxTree]) -> R) -> R {
    DESIGN_SYNTAX_TREES.with(|t| f(&t.borrow()))
}

/// While alive, [`call_is_explicit_super`] can recover `design`'s own
/// syntax. `pipeline::build_pipeline` holds one around its lowering, the
/// same shape `crate::dpi::DpiDesignScope` already establishes.
pub struct DesignSyntaxScope(
    Option<(
        Vec<sv_lang::SyntaxTree>,
        Option<sv_sim_sim::sva::sampled::InferredDisableResolver>,
    )>,
);

impl DesignSyntaxScope {
    pub fn enter(design: &sv_lang::Design) -> Self {
        let outer_trees = DESIGN_SYNTAX_TREES
            .with(|t| std::mem::replace(&mut *t.borrow_mut(), design.syntax_trees()));
        // 17.4: a checker `always_ff`'s sampled signals (the layout) include
        // its instantiation scope's `default disable iff` signal, which only
        // the syntax resolves.
        let outer_resolver = sv_sim_sim::sva::sampled::set_inferred_disable_resolver(Some(
            crate::sva::emit::resolve_checker_inferred_disable,
        ));
        DesignSyntaxScope(Some((outer_trees, outer_resolver)))
    }
}

impl Drop for DesignSyntaxScope {
    fn drop(&mut self) {
        // Scopes nest (the CLI's, then the pipeline's): leave the outer one's
        // state as it was.
        let (trees, resolver) = self.0.take().unwrap_or_default();
        sv_sim_sim::sva::sampled::set_inferred_disable_resolver(resolver);
        DESIGN_SYNTAX_TREES.with(|t| *t.borrow_mut() = trees);
    }
}

/// Whether `call` (a `Call` expression with no `call_this_class()` receiver
/// -- [`resolve_implicit_this_instance_method`]'s own OR-fallback case,
/// `super.method(...)`/a bare sibling call) was written with an EXPLICIT
/// `super.` prefix, by inspecting its own syntax directly
/// (`InvocationExpressionSyntax::left()`'s own kind: a bare call's callee is
/// a plain `IdentifierName`; `super.f()`'s is a `ScopedName` -- NOT a
/// `MemberAccessExpression`, despite the dotted source text, verified live
/// -- whose own `left()` is the `SuperHandle` keyword node). `false` (never
/// panics, never a loud error) for a compiler-synthesized call with no
/// syntax at all, or one this scope's own trees don't contain -- a
/// synthesized call can never literally BE a `super.` call written in
/// source, so treating it as "not super" here is exactly correct, not a
/// narrowed approximation.
pub fn call_is_explicit_super(call: sv_lang::Expression<'_>) -> bool {
    use sv_lang::AstNode;
    use sv_lang::kinds::SyntaxKind;
    use sv_lang::nodes::{InvocationExpressionSyntax, ScopedNameSyntax};

    DESIGN_SYNTAX_TREES.with(|trees| {
        for tree in trees.borrow().iter() {
            let Some(node) = call.syntax(tree) else {
                continue;
            };
            // `super.f(args)` is an invocation whose callee is `left()`; a
            // call with no argument list at all (`super.f;`, legal for a
            // void function or task with no arguments, LRM 1800-2023 13.4/
            // 13.3) has no invocation node -- the call's own syntax IS the
            // callee name. Reading only the invocation form misclassified
            // `super.f;` as a bare sibling call, which dispatches virtually
            // and re-enters the overriding method forever.
            let callee = match InvocationExpressionSyntax::cast(node) {
                Some(inv) => inv.left().syntax(),
                None => node,
            };
            if callee.kind() == SyntaxKind::SuperHandle {
                return true;
            }
            return ScopedNameSyntax::cast(callee)
                .is_some_and(|scoped| scoped.left().syntax().kind() == SyntaxKind::SuperHandle);
        }
        false
    })
}

/// Whether `callee`'s class has no registered template and its method was not
/// lowered: no `new` site names the class or any subclass (a subclass's
/// registration brings its ancestors along), so no object of it can exist and
/// a call through a handle of it always has a null receiver. Such a call is
/// reached through code the design never runs against a live object (UVM's
/// `uvm_report_catcher::process_all_report_catchers` with no catcher).
fn callee_class_never_instantiated(
    cx: &LowerCtx<'_, '_, '_>,
    callee: &sv_lang::Symbol<'_>,
) -> bool {
    let Ok(mangled) = crate::func::mangled_subroutine_name(callee) else {
        return false;
    };
    cx.module.get_function(&mangled).is_none()
        && callee
            .parent()
            .is_some_and(|p| class_template_id_of(&p).is_err())
}

/// A method call used as a statement (`func.rs::lower_task_call`'s own
/// class-method intercept, tried before its ordinary vif/mangled/extern
/// resolution). `recv` is `None` for the review-fix (r2), Task 6 finding 1
/// OR-fallback case (`super.method(...)`/a bare implicit-`this` sibling
/// call -- [`resolve_implicit_this_instance_method`]): the receiver is then
/// the CURRENT `this`, via [`current_this_handle`], exactly as if the call
/// had been written `this.method(...)`.
///
/// Classes plan Task 7 (8.20-8.22): when `callee` is virtual, dispatches
/// through [`virtual_call_arms`] instead of a single direct
/// [`build_method_call`] -- UNLESS this is an explicit `super.method(...)`
/// call (8.15, [`call_is_explicit_super`]: only reachable through the
/// `recv.is_none()` window, since an explicit receiver expression can never
/// be `super`), which 8.15 defines as never virtually dispatched regardless
/// of whether `callee` is virtual.
pub fn lower_method_task_call<'ctx, 'd, 'm>(
    cx: &mut LowerCtx<'ctx, 'd, 'm>,
    recv: Option<sv_lang::Expression<'d>>,
    call: sv_lang::Expression<'d>,
) -> Result<(), LoweringError> {
    let callee = call.call_subroutine().ok_or_else(|| {
        LoweringError::unsupported_at("method call missing its callee symbol", &cx.fn_sym)
    })?;
    reject_if_std_intrinsic(cx, &callee)?;
    if recv.is_some()
        && let Some((fv, args, copy_backs)) = static_method_call_via_handle(cx, callee, call)?
    {
        cx.b.build_call(fv, &args, "static_method_task_call")
            .unwrap();
        if sv_sim_sim::process::cfg::subroutine_can_abort(&callee) {
            crate::stmt_shared::leave_if_aborted(cx)?;
        }
        crate::func::copy_back_outputs(cx, copy_backs)?;
        return Ok(());
    }
    let h = match recv {
        Some(recv) => receiver_handle(cx, recv)?,
        None => current_this_handle(cx)?,
    };
    let is_super = recv.is_none() && call_is_explicit_super(call);
    let null_done = begin_null_receiver_guard(cx, recv, h, call, &callee)?;
    hold_receiver(cx, recv, h);
    if !is_super && let Some((arms, merge)) = virtual_call_arms(cx, callee, h)? {
        for (fv, bb) in arms {
            cx.b.position_at_end(bb);
            let (fv, llvm_args, copy_backs) = build_method_call_with(cx, fv, callee, h, call)?;
            cx.b.build_call(fv, &llvm_args, "virtual_method_task_call")
                .unwrap();
            if sv_sim_sim::process::cfg::subroutine_can_abort(&callee) {
                crate::stmt_shared::leave_if_aborted(cx)?;
            }
            crate::func::copy_back_outputs(cx, copy_backs)?;
            cx.b.build_unconditional_branch(merge).unwrap();
        }
        cx.b.position_at_end(merge);
        unhold_receiver(cx, recv, h);
        end_null_receiver_guard(cx, null_done);
        return Ok(());
    }
    if callee_class_never_instantiated(cx, &callee) {
        unhold_receiver(cx, recv, h);
        end_null_receiver_guard(cx, null_done);
        return Ok(());
    }
    let (fv, llvm_args, copy_backs) = build_method_call(cx, callee, h, call)?;
    cx.b.build_call(fv, &llvm_args, "method_task_call").unwrap();
    if sv_sim_sim::process::cfg::subroutine_can_abort(&callee) {
        crate::stmt_shared::leave_if_aborted(cx)?;
    }
    crate::func::copy_back_outputs(cx, copy_backs)?;
    unhold_receiver(cx, recv, h);
    end_null_receiver_guard(cx, null_done);
    Ok(())
}

/// A call of an instance method through a null handle (LRM 1800-2023 8.5:
/// the access is illegal and its result indeterminate; an implementation may
/// issue an error): reported like `$error` (`null object handle: call of
/// <method>`), then the call is skipped -- the arguments are not evaluated,
/// the body never runs (so a member access inside it cannot touch a null
/// `this`), and a value-returning call yields all-zero. Without this a
/// non-virtual method ran with `this == 0`, and a virtual call matched no arm
/// and silently returned its default.
///
/// Emitted right after the receiver `h` is read, BEFORE [`hold_receiver`]
/// (a null handle holds nothing). Returns the block the skipped path joins
/// (`None` for an implicit-`this` call -- `recv` is `None` -- where `h` is
/// the running method's own receiver, never null); the live path continues
/// in the current block and must finish with [`end_null_receiver_guard`].
/// A `static` method has no receiver (8.10, `call_this_class()` is `None`
/// for it), so it never reaches this guard.
fn begin_null_receiver_guard<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    recv: Option<sv_lang::Expression<'d>>,
    h: IntValue<'ctx>,
    call: sv_lang::Expression<'d>,
    callee: &sv_lang::Symbol<'d>,
) -> Result<Option<inkwell::basic_block::BasicBlock<'ctx>>, LoweringError> {
    if recv.is_none() {
        return Ok(None);
    }
    let f =
        cx.b.get_insert_block()
            .and_then(|bb| bb.get_parent())
            .expect("lowering happens inside a function");
    let null =
        cx.b.build_int_compare(
            IntPredicate::EQ,
            h,
            cx.ctx.i64_type().const_zero(),
            "method_recv_null",
        )
        .unwrap();
    crate::stmt_shared::error_if(
        cx,
        null,
        call.source_range().start,
        &format!("null object handle: call of {}", callee.name()),
    )?;
    let live = cx.ctx.append_basic_block(f, "method_recv_live");
    let done = cx.ctx.append_basic_block(f, "method_recv_done");
    cx.b.build_conditional_branch(null, done, live).unwrap();
    cx.b.position_at_end(live);
    Ok(Some(done))
}

/// Closes [`begin_null_receiver_guard`]: the live path joins the skipped one.
fn end_null_receiver_guard<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    done: Option<inkwell::basic_block::BasicBlock<'ctx>>,
) {
    if let Some(done) = done {
        cx.b.build_unconditional_branch(done).unwrap();
        cx.b.position_at_end(done);
    }
}

/// Classes plan Task 10 (review fix r1, finding 4): an object lives while
/// any handle names it (LRM 1800-2023 8.29), and the method being called
/// IS using it through `this` -- so the call holds one reference on the
/// receiver for its duration, however the body reassigns the handle the
/// receiver was read from (`g = null;` inside `g.run()`). Taken right after
/// the receiver is evaluated (before the arguments, which may themselves
/// drop the last handle) and given back after the output copy-backs. A
/// bare/`super` call (`recv` is `None`) needs none: the caller's own
/// `this` is already held by the call it is running in. The paths that end
/// the run (`$finish`/`$fatal`, [`crate::stmt_shared::leave_if_aborted`])
/// skip the release: a held object that is never freed is harmless.
fn hold_receiver<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    recv: Option<sv_lang::Expression<'d>>,
    h: IntValue<'ctx>,
) {
    if recv.is_some() {
        retain_handle(cx, h);
    }
}

/// Gives back the reference [`hold_receiver`] took.
fn unhold_receiver<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    recv: Option<sv_lang::Expression<'d>>,
    h: IntValue<'ctx>,
) {
    if recv.is_some() {
        release_handle(cx, h);
    }
}

/// Function, arguments and copy-backs of a receiver-less static-method call.
type StaticViaHandle<'ctx, 'd> = (
    FunctionValue<'ctx>,
    Vec<BasicMetadataValueEnum<'ctx>>,
    Vec<CopyBack<'ctx, 'd>>,
);

/// LRM 8.10: a `static` method called through an object handle
/// (`obj.static_method(...)`) takes no implicit receiver, so the call is the
/// same receiver-less call `Class::static_method(...)` makes. `Some` carries
/// that call's function, arguments and copy-backs; `None` when `callee` is
/// not a static method. The handle expression is not evaluated (a `null`
/// handle is legal here and the method cannot observe the object).
fn static_method_call_via_handle<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    callee: sv_lang::Symbol<'d>,
    call: sv_lang::Expression<'d>,
) -> Result<Option<StaticViaHandle<'ctx, 'd>>, LoweringError> {
    let Some(fv) = resolve_or_lower_static_method(cx, callee)? else {
        return Ok(None);
    };
    let (args, copy_backs) = crate::func::lower_call_args(cx, &callee, call)?;
    Ok(Some((fv, args, copy_backs)))
}

/// A method call used as a value (`expr.rs`'s generalized `Call` arm's own
/// class-method intercept, tried before its ordinary vif/mangled resolution
/// -- `lower_user_subroutine_call`'s own vif check). `recv` is `None` for
/// the review-fix (r2), Task 6 finding 1 OR-fallback case -- see
/// [`lower_method_task_call`]'s identical doc comment.
pub fn lower_method_call<'ctx, 'd, 'm>(
    cx: &LowerCtx<'ctx, 'd, 'm>,
    recv: Option<sv_lang::Expression<'d>>,
    call: sv_lang::Expression<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let callee = call.call_subroutine().ok_or_else(|| {
        LoweringError::unsupported_at("method call missing its callee symbol", &cx.fn_sym)
    })?;
    reject_if_std_intrinsic(cx, &callee)?;
    let ret_sv = callee.subroutine_return_type();
    if ret_sv.as_ref().is_none_or(sv_lang::Type::is_void) {
        return Err(LoweringError::unsupported_at(
            "a void method call cannot be used as an expression value",
            &cx.fn_sym,
        ));
    }
    let ret_sv = ret_sv.unwrap();
    if recv.is_some()
        && let Some((fv, args, copy_backs)) = static_method_call_via_handle(cx, callee, call)?
    {
        let call_site = cx.b.build_call(fv, &args, "static_method_call").unwrap();
        if sv_sim_sim::process::cfg::subroutine_can_abort(&callee) {
            crate::stmt_shared::leave_if_aborted(cx)?;
        }
        crate::func::copy_back_outputs(cx, copy_backs)?;
        let ret_v = call_site.try_as_basic_value().basic().ok_or_else(|| {
            LoweringError::unsupported_at(
                "method call produced no return value despite a non-void SV return type",
                &cx.fn_sym,
            )
        })?;
        if ret_sv.is_floating() {
            let f = crate::real::as_f64(cx, ret_v.into_float_value());
            return Ok(LoweredValue::Real(RealValue { llvm: f }));
        }
        return Ok(LoweredValue::Packed(PackedValue {
            llvm: ret_v.into_int_value(),
            width: ret_sv.value_width(),
            repr: cx.repr,
            signed: ret_sv.is_signed(),
        }));
    }
    let h = match recv {
        Some(recv) => receiver_handle(cx, recv)?,
        None => current_this_handle(cx)?,
    };
    if recv.is_none() {
        return lower_method_call_live(cx, recv, call, callee, h, &ret_sv);
    }
    // Through a handle: a null one skips the call and yields all-zero (see
    // [`begin_null_receiver_guard`]), via a slot pre-stored with that zero
    // (the same shape [`lower_virtual_method_call_value`] uses).
    let is_real = ret_sv.is_floating();
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let int_ty = op.packed_type(ret_sv.value_width(), cx.repr);
    let slot = if is_real {
        let slot = entry_alloca(cx, cx.ctx.f64_type(), "null_call_ret");
        cx.b.build_store(slot, cx.ctx.f64_type().const_zero())
            .unwrap();
        slot
    } else {
        let slot = entry_alloca(cx, int_ty, "null_call_ret");
        cx.b.build_store(slot, int_ty.const_zero()).unwrap();
        slot
    };
    let done = begin_null_receiver_guard(cx, recv, h, call, &callee)?;
    let live = lower_method_call_live(cx, recv, call, callee, h, &ret_sv)?;
    match live {
        LoweredValue::Real(r) => {
            cx.b.build_store(slot, r.llvm).unwrap();
        }
        LoweredValue::Packed(p) => {
            cx.b.build_store(slot, p.llvm).unwrap();
        }
        LoweredValue::Wide(_) | LoweredValue::Str(_) | LoweredValue::Huge(_) => {
            return Err(LoweringError::unsupported_at(
                "internal: a class method call lowers to a packed or real value only",
                &cx.fn_sym,
            ));
        }
    }
    end_null_receiver_guard(cx, done);
    if is_real {
        let f =
            cx.b.build_load(cx.ctx.f64_type(), slot, "null_call_ret_ld")
                .unwrap()
                .into_float_value();
        return Ok(LoweredValue::Real(RealValue { llvm: f }));
    }
    let v =
        cx.b.build_load(int_ty, slot, "null_call_ret_ld")
            .unwrap()
            .into_int_value();
    Ok(LoweredValue::Packed(PackedValue {
        llvm: v,
        width: ret_sv.value_width(),
        repr: cx.repr,
        signed: ret_sv.is_signed(),
    }))
}

/// [`lower_method_call`] with the receiver already known live: the real
/// (virtual or direct) call.
fn lower_method_call_live<'ctx, 'd, 'm>(
    cx: &LowerCtx<'ctx, 'd, 'm>,
    recv: Option<sv_lang::Expression<'d>>,
    call: sv_lang::Expression<'d>,
    callee: sv_lang::Symbol<'d>,
    h: IntValue<'ctx>,
    ret_sv: &sv_lang::Type<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let is_super = recv.is_none() && call_is_explicit_super(call);
    hold_receiver(cx, recv, h);
    if !is_super && is_virtual_method(&callee)? {
        let v = lower_virtual_method_call_value(cx, callee, h, call, ret_sv)?;
        unhold_receiver(cx, recv, h);
        return Ok(v);
    }
    if callee_class_never_instantiated(cx, &callee) {
        // No object of this class (or a subclass) exists anywhere in the
        // design, so the receiver is always null and the call never runs.
        unhold_receiver(cx, recv, h);
        let zero = if ret_sv.is_floating() {
            LoweredValue::Real(RealValue {
                llvm: cx.ctx.f64_type().const_zero(),
            })
        } else {
            let op = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            };
            LoweredValue::Packed(PackedValue {
                llvm: op.packed_type(ret_sv.value_width(), cx.repr).const_zero(),
                width: ret_sv.value_width(),
                repr: cx.repr,
                signed: ret_sv.is_signed(),
            })
        };
        return Ok(zero);
    }
    let (fv, llvm_args, copy_backs) = build_method_call(cx, callee, h, call)?;
    let call_site = cx.b.build_call(fv, &llvm_args, "method_call").unwrap();
    if sv_sim_sim::process::cfg::subroutine_can_abort(&callee) {
        crate::stmt_shared::leave_if_aborted(cx)?;
    }
    crate::func::copy_back_outputs(cx, copy_backs)?;
    unhold_receiver(cx, recv, h);
    let ret_v = call_site.try_as_basic_value().basic().ok_or_else(|| {
        LoweringError::unsupported_at(
            "method call produced no return value despite a non-void SV return type",
            &cx.fn_sym,
        )
    })?;
    if ret_sv.is_floating() {
        let f = crate::real::as_f64(cx, ret_v.into_float_value());
        return Ok(LoweredValue::Real(RealValue { llvm: f }));
    }
    Ok(LoweredValue::Packed(PackedValue {
        llvm: ret_v.into_int_value(),
        width: ret_sv.value_width(),
        repr: cx.repr,
        signed: ret_sv.is_signed(),
    }))
}

/// [`lower_method_call`]'s own virtual-dispatch branch, once [`virtual_call_
/// arms`] has already built `arms`/`merge`: mirrors `expr.rs::
/// lower_user_subroutine_call`'s own virtual-interface value-call shape --
/// a stack slot pre-stored with the return type's default value (reached
/// directly, with that default intact, for the "no arm matched" case --
/// [`virtual_call_arms`]'s own documented null/dead/cross-hierarchy
/// outcome), each arm overwriting it with its own call's real result before
/// branching to `merge`, where the final value is loaded back out.
fn lower_virtual_method_call_value<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    callee: sv_lang::Symbol<'d>,
    h: IntValue<'ctx>,
    call: sv_lang::Expression<'d>,
    ret_sv: &sv_lang::Type<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    // The default-value slot/store MUST be built before `virtual_call_arms`
    // below -- that call leaves `cx.b` positioned at the end of its own
    // last (already `br merge`-terminated) comparison block, so anything
    // built AFTER it in the straight-line, pre-switch sense would land in
    // an already-terminated block (an earlier draft of this function did
    // exactly that, confirmed live: `virtual_dispatch.sv` failed LLVM's own
    // verifier with "Basic Block ... does not have terminator!" on the
    // FOLLOWING block, since the store landed past the existing one).
    let is_real = ret_sv.is_floating();
    let slot = if is_real {
        let slot = entry_alloca(cx, cx.ctx.f64_type(), "virtual_ret");
        cx.b.build_store(slot, cx.ctx.f64_type().const_zero())
            .unwrap();
        slot
    } else {
        let op = OpBuilder {
            ctx: cx.ctx,
            b: &cx.b,
        };
        let ty = op.packed_type(ret_sv.value_width(), cx.repr);
        let slot = entry_alloca(cx, ty, "virtual_ret");
        cx.b.build_store(slot, crate::arrays::default_value(cx, ret_sv))
            .unwrap();
        slot
    };
    let (arms, merge) = virtual_call_arms(cx, callee, h)?
        .expect("caller already confirmed `callee` is virtual before calling this function");
    for (fv, bb) in arms {
        cx.b.position_at_end(bb);
        let (fv, llvm_args, copy_backs) = build_method_call_with(cx, fv, callee, h, call)?;
        let call_site =
            cx.b.build_call(fv, &llvm_args, "virtual_method_call")
                .unwrap();
        if sv_sim_sim::process::cfg::subroutine_can_abort(&callee) {
            crate::stmt_shared::leave_if_aborted(cx)?;
        }
        crate::func::copy_back_outputs(cx, copy_backs)?;
        let ret_v = call_site.try_as_basic_value().basic().ok_or_else(|| {
            LoweringError::unsupported_at(
                "virtual method call produced no return value despite a non-void SV return \
                 type",
                &cx.fn_sym,
            )
        })?;
        cx.b.build_store(slot, ret_v).unwrap();
        cx.b.build_unconditional_branch(merge).unwrap();
    }
    cx.b.position_at_end(merge);
    if is_real {
        let f =
            cx.b.build_load(cx.ctx.f64_type(), slot, "virtual_ret_ld")
                .unwrap()
                .into_float_value();
        return Ok(LoweredValue::Real(RealValue { llvm: f }));
    }
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let ty = op.packed_type(ret_sv.value_width(), cx.repr);
    let v =
        cx.b.build_load(ty, slot, "virtual_ret_ld")
            .unwrap()
            .into_int_value();
    Ok(LoweredValue::Packed(PackedValue {
        llvm: v,
        width: ret_sv.value_width(),
        repr: cx.repr,
        signed: ret_sv.is_signed(),
    }))
}

/// Review fix (r2), Task 5 finding 1: a scoped override of `cx.ctor_this`
/// for the duration of lowering exactly ONE property's own initializer
/// expression inside [`lower_new_class`]'s loop below -- saves the
/// PREVIOUS value on construction and restores it on [`Drop`] (including
/// on an early `?` return out of the initializer's own lowering), rather
/// than unconditionally clearing it. This matters for a `new` nested
/// inside one property's initializer (e.g. `class A; B inner = new;` as
/// one of `A`'s own field initializers): lowering `inner`'s initializer
/// recurses into [`lower_new_class`] again, which pushes `B`'s own handle
/// for the duration of `B`'s own fields, then must unwind back to `A`'s
/// handle -- never to `None` -- before `A`'s own NEXT field initializer
/// (if any) is lowered.
struct CtorThisGuard<'ctx, 'a> {
    cell: &'a std::cell::Cell<Option<IntValue<'ctx>>>,
    prev: Option<IntValue<'ctx>>,
}

impl<'ctx, 'a> CtorThisGuard<'ctx, 'a> {
    fn new(cell: &'a std::cell::Cell<Option<IntValue<'ctx>>>, h: IntValue<'ctx>) -> Self {
        let prev = cell.replace(Some(h));
        Self { cell, prev }
    }
}

impl<'ctx, 'a> Drop for CtorThisGuard<'ctx, 'a> {
    fn drop(&mut self) {
        self.cell.set(self.prev);
    }
}

// --- `new`/object construction (§1.4 Step 2).

/// The LLVM signature for one of `class_sym`'s own methods or constructor --
/// `func::subroutine_fn_type` with the receiver parameter (§1.3), UNLESS
/// `method` is a `static function`/`static task` (8.10: "no implicit object
/// handle argument"), detected the same way [`lower_method_body`] detects it
/// -- `Symbol::subroutine_this_var().is_some()`. By the time either function
/// ever sees `method`, Task 6's own `pipeline::build_pipeline`/`func::
/// resolve_callee_fn` callers have already resolved any `extern`-declared
/// prototype to its real, out-of-block implementation (`method_prototype_
/// subroutine()`), so a `this_var` miss here always means a genuine static
/// method, never an unresolved prototype.
pub fn method_fn_type<'ctx, 'd>(
    ctx: &'ctx Context,
    method: &sv_lang::Symbol<'d>,
    repr: ValueRepr,
) -> Result<(FunctionType<'ctx>, bool), LoweringError> {
    let receiver = method.subroutine_this_var().is_some();
    // A virtual call's candidate can take hidden static-formal shadows its
    // statically named callee does not (they come from whatever the override
    // calls, transitively); remember them so the call site can hand
    // each arm the caller's shadow (or a scratch slot) (`build_method_call_with`).
    if let Ok(name) = crate::func::mangled_subroutine_name(method) {
        let hidden: Vec<(SymbolId, Option<u32>)> = crate::func::subroutine_abi(method)
            .signals
            .iter()
            .map(|sig| {
                let scratch_width = (sig.kind() == SymbolKind::FormalArgument
                    && sig.formal_argument_direction() == sv_lang::ArgumentDirection::In)
                    .then(|| sig.value_type())
                    .flatten()
                    .filter(|t| t.is_integral() && !crate::huge::is_huge_width(t.value_width()))
                    .map(|t| t.value_width());
                (sig.uid(), scratch_width)
            })
            .collect();
        HIDDEN_SHADOWS.with(|m| m.borrow_mut().insert(name, hidden));
    }
    crate::func::subroutine_fn_type(ctx, method, repr, receiver)
}

/// Records the pipeline's compiled class methods so
/// [`crate::func::subroutine_abi`] can union the hidden parameters of every
/// possible override of a virtual call's static callee (a caller then holds
/// every shadow whichever override runs; see [`crate::func::build_group_abis`]).
/// The returned guard clears that table when the pipeline run ends (it holds
/// lifetime-erased symbols of the design).
pub fn register_method_names<'d>(methods: &[(Symbol<'d>, Symbol<'d>)]) -> MethodRegistryGuard {
    let syms: Vec<Symbol<'d>> = methods.iter().map(|(_, m)| *m).collect();
    crate::func::build_group_abis(&syms);
    MethodRegistryGuard
}

/// Clears the per-name override ABIs when the pipeline run ends.
pub struct MethodRegistryGuard;

impl Drop for MethodRegistryGuard {
    fn drop(&mut self) {
        crate::func::clear_group_abis();
    }
}

thread_local! {
    /// Per class-method implementation (mangled name): each hidden shadow
    /// parameter it takes, with the scratch width usable when the caller has
    /// no shadow of it (a static input formal).
    static HIDDEN_SHADOWS: RefCell<HashMap<String, HiddenShadowList>> = RefCell::new(HashMap::new());
}

/// One method implementation's hidden shadow parameters ([`HIDDEN_SHADOWS`]).
type HiddenShadowList = Vec<(SymbolId, Option<u32>)>;

/// Lowers one of `class_sym`'s own methods or constructor's BODY into
/// already-declared `f` ([`method_fn_type`]'s own shape) --
/// `func::lower_function_body` with the receiver bound to the method's own
/// `this` variable (§1.3) for an ordinary instance method/constructor, or
/// with no receiver at all (`this_var: None`, exactly like an ordinary
/// non-class subroutine) for a `static function`/`static task` (8.10) --
/// Task 6 Step 4's class-scope `::` static-method calls need exactly this
/// shape, with no object handle anywhere in the ABI.
///
/// Corrected vs. an earlier draft of this function (found running Task 5's
/// own fixtures, not in the preflight corrections): `Type::class_this_var()`
/// is the CLASS's own `this` -- documented as "usable by non-static class
/// property initializers" -- a DIFFERENT symbol (different `uid()`) from the
/// METHOD's own implicit receiver, `Symbol::subroutine_this_var()`. Binding
/// the wrong one left the method's REAL `this` (which `func::
/// subroutine_locals`'s own walk also discovers, as a direct member of the
/// method's scope) unbound, failing with "a class/.../subroutine local is
/// not supported" the moment `lower_function_body`'s declared-locals loop
/// reached it.
pub fn lower_method_body<'ctx, 'd>(
    ctx: &'ctx Context,
    module: &Module<'ctx>,
    class_sym: sv_lang::Symbol<'d>,
    method: &sv_lang::Symbol<'d>,
    repr: ValueRepr,
    f: FunctionValue<'ctx>,
) -> Result<FunctionValue<'ctx>, LoweringError> {
    let _ = class_sym;
    let this_var = method.subroutine_this_var();
    crate::func::lower_function_body(ctx, module, method, repr, f, this_var)
}

/// Task 6 Step 4 (8.10/8.23): `func::resolve_callee_fn`'s own pre-check for
/// a `Class::static_method()` call (`Class::STATIC_CONST` is a plain
/// `NamedValue`/`MemberAccess` read, not a call, so it never reaches this
/// function) -- `Some(fv)` lazily declares-then-defines `callee`'s mangled
/// function (`classes::method_fn_type`/`lower_method_body`, receiver-less)
/// into `cx.module` ON FIRST USE and returns it; `None` if `callee` is not a
/// static class method at all, which is this function's one caller's cue to
/// fall through to its own ordinary same-module/mangled/extern resolution
/// unchanged.
///
/// Deliberately lazy (call-site-driven), unlike `pipeline::build_pipeline`'s
/// own upfront class sub-pass (which eagerly declares+defines every
/// INSTANCE method and the constructor): a `static` method's declaring
/// class is not necessarily ever `new()`'d anywhere in the design (8.10's
/// whole point is that it needs no object at all -- `class_scope_static_
/// call.sv`'s own `counter` class is never instantiated), so it is never a
/// member of `pipeline::build_pipeline`'s `classes` discovery list in the
/// first place; and eagerly force-lowering EVERY static method regardless
/// of whether anything ever calls it would re-litigate Task 5 review fix
/// (r1)'s own finding (a declared-but-unsupported member must not poison
/// the rest of the class's build) for static members specifically --
/// `flat_with_static_method.sv`'s own `get_count()` reads the STILL-
/// unwired static property `count` (Task 4's own commit explicitly defers
/// that codegen wiring to Task 19) and is deliberately never called; lazy,
/// call-site-only resolution is what keeps that fixture passing while still
/// compiling a static method that IS called (this function's own job).
///
/// An `extern`-declared static method prototype resolves to its real
/// out-of-block implementation the same way `pipeline::build_pipeline`'s
/// own class sub-pass does, via `method_prototype_subroutine()` --
/// `method_prototype_first_extern_impl()` is a different mechanism (an
/// INTERFACE's modport-implemented `extern` method), verified not to apply
/// here by `classes::tests::extern_method_prototype_resolves_to_a_this_
/// bearing_subroutine`.
pub(crate) fn resolve_or_lower_static_method<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    callee: sv_lang::Symbol<'d>,
) -> Result<Option<FunctionValue<'ctx>>, LoweringError> {
    let callee = if callee.kind() == SymbolKind::MethodPrototype {
        match callee.method_prototype_subroutine() {
            Some(real) => real,
            None => return Ok(None),
        }
    } else {
        callee
    };
    let Some(class_sym) = callee.parent() else {
        return Ok(None);
    };
    if !matches!(
        class_sym.kind(),
        SymbolKind::ClassType | SymbolKind::GenericClassDef
    ) {
        return Ok(None);
    }
    if is_builtin_std_class(&class_sym).is_some() {
        // Tasks 13/17/18's own dedicated `sv_rt_*` dispatch, never this
        // ordinary-method path.
        return Ok(None);
    }
    if callee.subroutine_this_var().is_some() {
        // An ordinary instance method -- `call_this_class()`-driven, not
        // this function's concern.
        return Ok(None);
    }
    // Classes plan Task 7 (found running `abstract_pure_virtual.sv`, not in
    // the preflight corrections): a `this_var()`-less `Subroutine` is NOT
    // always a genuine `static` method -- the synthesized stub slang builds
    // for a still-unimplemented `pure virtual` prototype (`Symbol::
    // method_prototype_subroutine()`'s own doc comment) has `this_var() ==
    // None` too, yet IS virtual. See `classes::is_virtual_method`'s own doc
    // comment for the identical confusion this same shape caused there.
    // Routing it through this function's own static-method lazy-declare
    // path would give it the WRONG (receiver-less) ABI shape under the
    // SAME mangled name a virtual call site's own `virtual_call_arms`
    // lookup never needs (a pure-virtual slot's own declaring class is
    // never anyone's dynamic type), so this must stay a loud `None` here,
    // never a silently-wrong static-shaped declaration.
    if is_virtual_method(&callee)? {
        return Ok(None);
    }
    let mangled = crate::func::mangled_subroutine_name(&callee)?;
    if let Some(f) = cx.module.get_function(&mangled) {
        return Ok(Some(f));
    }
    let (fn_ty, _is_void) = method_fn_type(cx.ctx, &callee, cx.repr)?;
    let f = cx.module.add_function(&mangled, fn_ty, None);
    lower_method_body(cx.ctx, cx.module, class_sym, &callee, cx.repr, f)?;
    Ok(Some(f))
}

/// Stores the type default of every declared property WITHOUT an initializer
/// (and not an event, which [`run_own_field_inits`] creates) of `class_ty` and
/// all its ancestors onto the freshly allocated `h`. LRM 1800-2023 8.7 runs
/// only DECLARED initializers after `super.new()`; a property without one
/// keeps its default from allocation, so a virtual method a base constructor
/// calls may set a derived property and have the write survive.
fn store_default_fields<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    class_ty: sv_lang::Type<'d>,
) -> Result<(), LoweringError> {
    let mut cur = Some(class_ty);
    while let Some(ty) = cur {
        let class_sym = ty.as_symbol();
        let layout = ObjectLayout::for_template(class_sym)?;
        let members = sv_sim_sim::netlist::classify_members(class_sym)
            .map_err(|e| elab_to_lowering(e, &class_sym))?;
        for f_sym in members.fields {
            if layout.is_alias(&f_sym) || f_sym.initializer().is_some() {
                continue;
            }
            let Some(slot) = layout.slot_of(&f_sym) else {
                continue;
            };
            let fty = f_sym.value_type().ok_or_else(|| {
                LoweringError::unsupported_at("class property has no type", &f_sym)
            })?;
            if fty.is_event() {
                continue;
            }
            let value = LoweredValue::Packed(PackedValue {
                llvm: crate::arrays::default_value(cx, &fty),
                width: fty.value_width(),
                repr: cx.repr,
                signed: fty.is_signed(),
            });
            store_field(cx, h, slot, &fty, value, false)?;
        }
        cur = ty.class_base();
    }
    Ok(())
}

/// Task 6 Step 1/2 helper: runs `class_sym`'s OWN (non-inherited) declared
/// properties' initializers, in order, onto `h` -- LRM 8.7's "After the base
/// class constructor call (if any) has completed, each property defined in
/// THE CLASS shall be initialized" step, scoped to exactly ONE class level.
/// An ancestor's own fields are never this function's concern -- they run
/// via that ancestor's OWN identical call, from [`chain_to_base`] or from
/// the recursive `is_super_class` path in [`lower_new_class`] (whichever one
/// is driving that ancestor's own level at the time).
fn run_own_field_inits<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    class_sym: sv_lang::Symbol<'d>,
) -> Result<(), LoweringError> {
    let layout = ObjectLayout::for_template(class_sym)?;
    let members = sv_sim_sim::netlist::classify_members(class_sym)
        .map_err(|e| elab_to_lowering(e, &class_sym))?;
    for f_sym in members.fields {
        // 19.4.1: an extended covergroup is the inherited instance, already
        // built by the base constructor; initializing it would clear it.
        if layout.is_alias(&f_sym) {
            continue;
        }
        let slot = layout.slot_of(&f_sym).ok_or_else(|| {
            LoweringError::unsupported_at(
                "internal: own field missing from its own class's layout",
                &f_sym,
            )
        })?;
        let fty = f_sym
            .value_type()
            .ok_or_else(|| LoweringError::unsupported_at("class property has no type", &f_sym))?;
        if fty.is_event() {
            // A new event object per object (LRM 1800-2023 15.5), or the one
            // an initializer names; the property holds its runtime id.
            let id = match f_sym.initializer() {
                Some(init) => {
                    let _guard = CtorThisGuard::new(&cx.ctor_this, h);
                    crate::class_events::id_of(cx, init)?
                }
                None => crate::class_events::new_event(cx),
            };
            let o = OpBuilder {
                ctx: cx.ctx,
                b: &cx.b,
            };
            let v = o.pack(id, o.i_n(64).const_zero(), 64, cx.repr, false);
            // `h` was allocated just now, so it is live.
            let _live = field_set_call(cx, h, slot, v);
            continue;
        }
        // A field without an initializer already holds its default from
        // allocation ([`store_default_fields`]): re-zeroing it here would
        // erase a write a virtual method called from a base constructor made.
        if f_sym.initializer().is_none() {
            continue;
        }
        let value = match f_sym.initializer() {
            // Review fix (r2), Task 5 finding 1: `cx.ctor_this` is pushed
            // to `h` -- THIS object, not whatever `this` is ambient at the
            // `new` expression's own call site -- for exactly the
            // duration of this one property's own initializer expression,
            // so a sibling-field bare reference (LRM 1800-2023 §8.7's
            // `int b = a + 1;`) resolves against the object being built.
            Some(init) => {
                let _guard = CtorThisGuard::new(&cx.ctor_this, h);
                crate::collections::owned(cx, init)?
            }
            None => LoweredValue::Packed(PackedValue {
                llvm: crate::arrays::default_value(cx, &fty),
                width: fty.value_width(),
                repr: cx.repr,
                signed: fty.is_signed(),
            }),
        };
        store_field(cx, h, slot, &fty, value, false)?;
    }
    Ok(())
}

/// Whether `ty`'s constructor reaches its base class through a
/// `super.new(...)` of its own (so the caller must not also chain to the
/// base): the explicit statement, or the implicit `super.new(default)` of a
/// constructor that declares `default` (LRM 1800-2023 8.17) -- written
/// `function new(default)` or generated for `extends Base(default)`.
fn embeds_super_new(ty: sv_lang::Type<'_>) -> bool {
    matches!(
        ty.class_base_constructor_call(),
        Some(e) if e.kind() == ExpressionKind::NewClass
    ) || implicit_default_super(ty)
}

/// `ty`'s constructor declares `default` and has no explicit `super.new`:
/// the compiler inserts `super.new(default)` (LRM 1800-2023 8.17).
fn implicit_default_super(ty: sv_lang::Type<'_>) -> bool {
    ty.class_base().is_some()
        && ty.class_constructor().is_some_and(|c| {
            c.subroutine_flags()
                .contains(sv_lang::MethodFlags::DEFAULTED_SUPER_ARG)
        })
        && ty.class_base_constructor_call().is_none()
}

/// The prologue of a constructor with an implicit `super.new(default)`
/// ([`implicit_default_super`]): its base class's level, with the inherited
/// arguments forwarded, then its own property initializers -- what an
/// explicit `super.new(default)` statement does through [`lower_new_class`].
pub(crate) fn emit_implicit_default_super<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
) -> Result<(), LoweringError> {
    let Some(cur_sym) = cx.fn_sym.parent() else {
        return Ok(());
    };
    if cx.fn_sym.kind() != SymbolKind::Subroutine
        || !cx
            .fn_sym
            .subroutine_flags()
            .contains(sv_lang::MethodFlags::CONSTRUCTOR)
    {
        return Ok(());
    }
    let Some(cur_ty) = cur_sym.as_type() else {
        return Ok(());
    };
    if !implicit_default_super(cur_ty) {
        return Ok(());
    }
    let h = current_this_handle(cx)?;
    let base_ty = cur_ty
        .class_base()
        .expect("checked by implicit_default_super");
    if !embeds_super_new(base_ty) {
        chain_to_base(cx, h, base_ty)?;
        run_own_field_inits(cx, h, base_ty.as_symbol())?;
    }
    if let Some(base_ctor) = base_ty.class_constructor() {
        call_ctor_level(cx, h, base_ctor, None)?;
    }
    run_own_field_inits(cx, h, cur_sym)
}

/// The constructor slang generates for `class D extends Base(default)` when
/// `D` declares none (LRM 1800-2023 8.17): it takes `Base::new`'s formals,
/// has no `this` and no body, so it is never a compiled function -- calls
/// to it are expanded in place by [`call_ctor_level`].
fn is_synth_default_ctor(ctor: &sv_lang::Symbol<'_>) -> bool {
    ctor.subroutine_this_var().is_none()
        && ctor
            .subroutine_flags()
            .contains(sv_lang::MethodFlags::DEFAULTED_SUPER_ARG)
}

/// Runs constructor `ctor`'s own level on `h`: a call with `call`'s
/// arguments, or (`call` is `None`) with the arguments the running
/// constructor inherited through `default` ([`forward_to_real_ctor`]).
/// A generated constructor ([`is_synth_default_ctor`]) expands to its base
/// class's level (the same arguments) followed by its own property
/// initializers.
fn call_ctor_level<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    ctor: sv_lang::Symbol<'d>,
    call: Option<sv_lang::Expression<'d>>,
) -> Result<(), LoweringError> {
    if is_synth_default_ctor(&ctor) {
        let cls = ctor.parent().ok_or_else(|| {
            LoweringError::unsupported_at("a generated constructor with no class", &ctor)
        })?;
        let ty = cls
            .as_type()
            .ok_or_else(|| LoweringError::unsupported_at("a constructor outside a class", &ctor))?;
        if let Some(base_ty) = ty.class_base() {
            if !embeds_super_new(base_ty) {
                chain_to_base(cx, h, base_ty)?;
                run_own_field_inits(cx, h, base_ty.as_symbol())?;
            }
            if let Some(base_ctor) = base_ty.class_constructor() {
                call_ctor_level(cx, h, base_ctor, call)?;
            }
        }
        return run_own_field_inits(cx, h, cls);
    }
    match call {
        Some(call) => {
            let (fv, llvm_args, copy_backs) = build_method_call(cx, ctor, h, call)?;
            cx.b.build_call(fv, &llvm_args, "ctor_call").unwrap();
            leave_if_ctor_aborted(cx, &ctor)?;
            crate::func::copy_back_outputs(cx, copy_backs)
        }
        None => forward_to_real_ctor(cx, h, ctor),
    }
}

/// Calls the base constructor `base_ctor` with the arguments the running
/// constructor (`cx.fn_sym`) inherited through `default` (LRM 1800-2023
/// 8.17): slang clones the base's formals into the derived list in place of
/// the keyword, same names and order, so they are the contiguous run
/// matching `base_ctor`'s formals. Inputs are passed as the derived
/// constructor's own parameters (a class or collection handle retained for
/// the callee, which releases its input); `output`/`inout`/`ref` formals
/// pass the caller's temporary straight through, so the base writes the
/// original actual.
fn forward_to_real_ctor<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    base_ctor: sv_lang::Symbol<'d>,
) -> Result<(), LoweringError> {
    let derived: Vec<sv_lang::Symbol<'d>> = cx.fn_sym.subroutine_arguments().collect();
    let base: Vec<sv_lang::Symbol<'d>> = base_ctor.subroutine_arguments().collect();
    let start = (0..=derived.len().saturating_sub(base.len()))
        .find(|&s| {
            derived.len() >= base.len()
                && base
                    .iter()
                    .enumerate()
                    .all(|(i, b)| derived[s + i].name() == b.name())
        })
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                "internal: the inherited `default` constructor arguments are not a run of \
                 the derived constructor's formals",
                &cx.fn_sym,
            )
        })?;
    let f =
        cx.b.get_insert_block()
            .and_then(|bb| bb.get_parent())
            .ok_or_else(|| LoweringError::unsupported_at("no current function", &cx.fn_sym))?;
    let mut llvm_args: Vec<BasicMetadataValueEnum<'ctx>> = vec![h.into()];
    for (i, formal) in base.iter().enumerate() {
        let t = formal
            .value_type()
            .ok_or_else(|| LoweringError::unsupported_at("formal has no type", formal))?;
        // Parameter 0 is the receiver.
        let param = f.get_nth_param(1 + (start + i) as u32).ok_or_else(|| {
            LoweringError::unsupported_at("internal: missing constructor parameter", &cx.fn_sym)
        })?;
        // An unpacked-array formal is a pointer to the caller's temporary: an
        // input is passed on as a fresh copy (the base may write its own),
        // an `output`/`inout`/`ref` one as the pointer itself.
        if let Some(shape) = crate::arrays::array_shape(&t) {
            if crate::func::is_by_reference(formal) {
                llvm_args.push(param.into());
                continue;
            }
            let ty = crate::arrays::local_array_type(cx.ctx, &shape, cx.repr);
            let copy = crate::expr::entry_alloca(cx, ty, "default_fwd_array");
            let size = inkwell::types::BasicType::size_of(&ty).expect("a sized array type");
            cx.b.build_memcpy(copy, 8, param.into_pointer_value(), 8, size)
                .unwrap();
            llvm_args.push(copy.into());
            continue;
        }
        if crate::func::is_by_reference(formal) || t.is_floating() {
            llvm_args.push(param.into());
            continue;
        }
        let pv = PackedValue {
            llvm: param.into_int_value(),
            width: t.value_width(),
            repr: cx.repr,
            signed: t.is_signed(),
        };
        llvm_args.push(crate::collections::retain_stored(cx, &t, pv).llvm.into());
    }
    let mangled = crate::func::mangled_subroutine_name(&base_ctor)?;
    let fv = cx.module.get_function(&mangled).ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!("class constructor `{mangled}` was not lowered into this module"),
            &cx.fn_sym,
        )
    })?;
    // The module signals and instance handle the base constructor reaches:
    // the running constructor's own ABI includes them (`subroutine_abi`).
    crate::func::append_hidden_args(cx, &base_ctor, &mut llvm_args)?;
    if llvm_args.len() != fv.count_params() as usize {
        return Err(LoweringError::unsupported_at(
            "internal: a constructor `default` forward passes the wrong number of arguments",
            &cx.fn_sym,
        ));
    }
    cx.b.build_call(fv, &llvm_args, "default_fwd_ctor_call")
        .unwrap();
    leave_if_ctor_aborted(cx, &base_ctor)
}

/// Task 6 Step 2: an implicit base-constructor call (LRM 8.7: "the new
/// method of a derived class shall first call its base class constructor"),
/// built with no explicit argument list at all -- reached only when a base
/// class HAS its own constructor but neither an explicit `super.new(...)`
/// statement nor an `extends Base(args)`/`extends Base(default)` clause
/// supplied one (`Type::class_base_constructor_call()` is `None` in exactly
/// this case). `ClassSymbols.cpp`'s own `BaseConstructorNotCalled`
/// diagnostic already guarantees every one of `ctor`'s formals has a
/// default value whenever slang leaves that accessor `None` with a base
/// class present, so every actual here comes from
/// [`sv_lang::Symbol::formal_argument_default_value`], never a literal `0`.
fn lower_default_ctor_call<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    ctor: sv_lang::Symbol<'d>,
) -> Result<(), LoweringError> {
    let formals: Vec<sv_lang::Symbol<'d>> = ctor.subroutine_arguments().collect();
    let mut llvm_args: Vec<BasicMetadataValueEnum<'ctx>> = vec![h.into()];
    for formal in &formals {
        let default = formal.formal_argument_default_value().ok_or_else(|| {
            LoweringError::unsupported_at(
                "an implicit base-constructor call (no explicit `super.new(...)`/`extends \
                 Base(args)`) needs every base-constructor formal to have a default value -- \
                 slang's own frontend already guarantees this whenever it leaves \
                 `Type::class_base_constructor_call()` unset with a base class present, so a \
                 missing default here is an internal inconsistency, not a reachable SV-source \
                 failure",
                &cx.fn_sym,
            )
        })?;
        let width = formal.value_type().map(|t| t.value_width()).unwrap_or(0);
        let pv = crate::real::to_storage(
            cx,
            lower_expr(cx, default)?,
            width,
            "implicit base-constructor default argument",
        )?;
        llvm_args.push(pv.llvm.into());
    }
    let mangled = crate::func::mangled_subroutine_name(&ctor)?;
    let fv = cx.module.get_function(&mangled).ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!(
                "class method/constructor `{mangled}` was not lowered into this module -- \
                 cross-module class method calls are not yet supported (classes plan Task 5 \
                 scope)"
            ),
            &cx.fn_sym,
        )
    })?;
    crate::func::append_hidden_args(cx, &ctor, &mut llvm_args)?;
    if llvm_args.len() != fv.count_params() as usize {
        return Err(LoweringError::unsupported_at(
            &format!(
                "implicit base-constructor call argument count {} does not match the callee's \
             declared parameter count {} (plus the implicit receiver) {mangled}",
                llvm_args.len(),
                fv.count_params()
            ),
            &cx.fn_sym,
        ));
    }
    cx.b.build_call(fv, &llvm_args, "base_ctor_default_call")
        .unwrap();
    leave_if_ctor_aborted(cx, &ctor)
}

/// A constructor call that can end the run (a failing `$cast`, `$fatal`,
/// `$finish` in its body, its class's property initializers, or a base
/// constructor it chains to) must stop the creator before the next phase of
/// the `new` -- the derived constructor body, the statements after the
/// `new` -- runs (LRM 1800-2023 6.24.2, 20.2/20.10; the same discipline
/// [`lower_method_task_call`] applies to a method call).
fn leave_if_ctor_aborted(
    cx: &LowerCtx<'_, '_, '_>,
    ctor: &sv_lang::Symbol<'_>,
) -> Result<(), LoweringError> {
    if sv_sim_sim::process::cfg::subroutine_can_abort(ctor) {
        crate::stmt_shared::leave_if_aborted(cx)?;
    }
    Ok(())
}

/// Task 6 Step 2: 8.7/8.17 constructor chaining -- invokes `ty`'s base
/// class's own FULL level (its own chain to ITS base, then its own field
/// inits, then its own explicit constructor call, if any) on the SAME
/// handle `h`. Called only when `ty`'s own constructor body does NOT itself
/// begin with an explicit `super.new(...)` statement -- see
/// [`lower_new_class`]'s own `embedded_super` check, which is this
/// function's one caller and decides exactly that.
///
/// `Type::class_base_constructor_call()`'s three shapes, given that
/// precondition (an explicit embedded statement is impossible here -- it
/// would be the `NewClass`-kind result `embedded_super` already filtered
/// out):
/// - `Some(call)` where `call.kind() == Call`: the `extends Base(args)`-
///   synthesized call (`ClassSymbols.cpp::getBaseConstructorCall`'s
///   `CallExpression::fromArgs` branch) -- lowered as an ordinary call to
///   the base's constructor, exactly like [`build_method_call`] builds any
///   other method/constructor call.
/// - `None` with a base class present: no call was written and none was
///   synthesized -- [`lower_default_ctor_call`] if the base has a
///   constructor at all, otherwise nothing to call (the base's own fields
///   were already initialized by the recursive chain call just above).
/// - No base class at all: nothing to do.
fn chain_to_base<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    h: IntValue<'ctx>,
    ty: sv_lang::Type<'d>,
) -> Result<(), LoweringError> {
    let Some(base_ty) = ty.class_base() else {
        return Ok(());
    };
    let base_sym = base_ty.as_symbol();
    // Whether BASE's own constructor (if any) itself begins with an
    // explicit `super.new(...)` -- if so, base's own chain-to-its-base plus
    // base's own field inits happen when THAT embedded statement is reached
    // (recursively, `lower_new_class`'s `is_super_class` branch, triggered
    // by the ctor call below); doing either again here would run them
    // twice.
    let base_embedded_super = embeds_super_new(base_ty);
    if !base_embedded_super {
        chain_to_base(cx, h, base_ty)?;
        run_own_field_inits(cx, h, base_sym)?;
    }
    match ty.class_base_constructor_call() {
        Some(base_expr) => {
            if base_expr.kind() != ExpressionKind::Call {
                return Err(LoweringError::unsupported_at(
                    "internal: a base-constructor-call expression reached `chain_to_base` with \
                     an unexpected kind -- only an `extends Base(args)`-synthesized `Call` is \
                     possible once `lower_new_class`'s own `embedded_super` check has already \
                     filtered out the explicit `super.new(...)`-statement (`NewClass`) case",
                    &cx.fn_sym,
                ));
            }
            let ctor = base_expr.call_subroutine().ok_or_else(|| {
                LoweringError::unsupported_at(
                    "base-constructor-call expression missing its callee symbol",
                    &cx.fn_sym,
                )
            })?;
            call_ctor_level(cx, h, ctor, Some(base_expr))
        }
        None => {
            let Some(ctor) = base_ty.class_constructor() else {
                return Ok(());
            };
            lower_default_ctor_call(cx, h, ctor)
        }
    }
}

/// `new(args)`/`new`/`super.new(args)` (LRM 1800-2023 §8.4-8.7, §8.11,
/// §8.13, §8.17, §8.19): allocates the object (`objects::alloc`, via
/// [`alloc_call`]) for a plain `new`, or reuses the SAME object's handle
/// (`current_this_handle`) for a `super.new(...)` chain call -- 8.2's "the
/// argument copied is the object handle, not the contents of the object"
/// means `super.new` never allocates a second object. Then: 8.7/8.17's
/// "beginning with the root base class and ending with the current class"
/// ordering --
/// 1. chain to the base class's own FULL level ([`chain_to_base`]), UNLESS
///    `ty`'s own constructor body already does this itself via an explicit
///    `super.new(...)` statement as its own literal first statement
///    (`embedded_super` below) -- in which case that statement, reached
///    during the ordinary statement walk of the constructor call in step 3,
///    recurses into THIS SAME function with `is_super_class() == Some(true)`
///    and does it there instead. Trusting `Type::class_base_constructor_
///    call()`'s own `NewClass`-vs-`Call`-vs-`None` shape to tell these two
///    cases apart (rather than re-deriving "does this body start with
///    `super.new`" independently) is deliberate: slang's own
///    `checkForSuperNew` (`ClassSymbols.cpp`) already skips leading
///    `VariableDeclaration` statements when searching for it, and
///    `class_base_constructor_call()`'s `NewClass`-kind result IS that
///    exact, already-located embedded statement (verified live,
///    `classes::tests::class_base_constructor_call_shapes`) -- re-walking
///    the body ourselves would risk disagreeing with slang's own,
///    already-correct answer.
/// 2. run every declared property's own initializer in order (explicit, or
///    its type's default via [`crate::arrays::default_value`]),
///    [`run_own_field_inits`], scoped to `class_sym`'s OWN level only.
/// 3. the explicit constructor call, if any.
///
/// The object's own generator is seeded by the runtime `Alloc` op itself
/// (Task 15: one draw from the creating thread, LRM 18.14.1; see
/// `sv_sim_runtime::objects_rt::ObjOp::Alloc`), so nothing is emitted here.
pub fn lower_new_class<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    // Deviation from §1.4 (found running this task's own `super_new_
    // chain.sv` fixture, not in the preflight corrections): a `super.new
    // (...)` `NewClass` expression's OWN `expr_type()` is `void`, not the
    // base class -- `AssignmentExpressions.cpp::resolveNewClassTarget`'s
    // own `super.new` branch literally does `assignmentTarget =
    // &context.getCompilation().getVoidType();` before constructing the
    // node, and `Expression::type` IS that `assignmentTarget`. So the
    // class this call constructs can only be found independently of
    // `e.expr_type()` for a super call: `cx.fn_sym` (the constructor whose
    // body is CURRENTLY being lowered -- always the one that lexically
    // contains this exact `super.new(...)` statement) `.parent()` gives
    // that constructor's own enclosing class, and ITS `class_base()` is
    // the base being constructed.
    let is_super = e.new_class_is_super_class() == Some(true);
    // Review fix (r1), Task 6 finding 1: for the explicit-`super.new(...)`
    // case we also need to remember the class that LEXICALLY WROTE this
    // statement (as opposed to `class_sym`/`ty` below, which name the BASE
    // being constructed) -- its own declared-property initializers
    // (LRM 1800-2023 §8.7's own worked example: `class D extends C; int
    // d1 = 4; function new; super.new(d3); endfunction` -- `d1` must end
    // up `4`) run only once this statement's base-construction has fully
    // completed, mirrored below via `run_own_field_inits(cx, h,
    // cur_class_sym)` after the base ctor call.
    let mut cur_class_sym: Option<sv_lang::Symbol<'d>> = None;
    let (class_sym, ty) = if is_super {
        let sym = cx.fn_sym.parent().ok_or_else(|| {
            LoweringError::unsupported_at(
                "`super.new(...)` reached outside any class method/constructor body",
                &cx.fn_sym,
            )
        })?;
        cur_class_sym = Some(sym);
        let cur_ty = sym.as_type().ok_or_else(|| {
            LoweringError::unsupported_at(
                "`super.new(...)`'s enclosing scope is not a class",
                &cx.fn_sym,
            )
        })?;
        let base_ty = cur_ty.class_base().ok_or_else(|| {
            LoweringError::unsupported_at(
                "`super.new(...)` used in a class with no base class",
                &cx.fn_sym,
            )
        })?;
        (base_ty.as_symbol(), base_ty)
    } else {
        // Canonical: a typedef'd specialization (`typedef C#(4) T; T h = new;`,
        // LRM 8.25) is a TypeAlias whose symbol is not the class.
        let ty = e
            .expr_type()
            .ok_or_else(|| {
                LoweringError::unsupported_at("`new` expression has no class type", &cx.fn_sym)
            })?
            .canonical();
        if !ty.is_class() {
            return Err(LoweringError::unsupported_at(
                "a `new` expression whose type is not a class (`new[]`/`new <covergroup>` are \
                 a separate ExpressionKind, not this arm's concern)",
                &cx.fn_sym,
            ));
        }
        (ty.as_symbol(), ty)
    };
    if let Some(intrinsic) = is_builtin_std_class(&class_sym) {
        if intrinsic == StdIntrinsic::WeakReference {
            return lower_new_weakref(cx, e, &class_sym);
        }
        if intrinsic == StdIntrinsic::Semaphore {
            return lower_new_semaphore(cx, e, &class_sym);
        }
        if intrinsic == StdIntrinsic::Mailbox {
            return lower_new_mailbox(cx, e, &class_sym);
        }
        return Err(LoweringError::unsupported_at(
            &format!("`new()` on the std-package intrinsic {intrinsic:?} is not supported"),
            &cx.fn_sym,
        ));
    }
    let h = if is_super {
        current_this_handle(cx)?
    } else {
        let id = class_template_id_of(&class_sym)?;
        let layout = ObjectLayout::for_template(class_sym)?;
        let h = alloc_call(cx, id, layout.total_words());
        store_default_fields(cx, h, ty)?;
        crate::classes_randomize::ensure_static_owners(cx, class_sym, id)?;
        h
    };

    let embedded_super = embeds_super_new(ty);
    if !embedded_super {
        chain_to_base(cx, h, ty)?;
        run_own_field_inits(cx, h, class_sym)?;
    }

    if let Some(ctor_call) = e.new_class_constructor_call() {
        let ctor = ctor_call.call_subroutine().ok_or_else(|| {
            LoweringError::unsupported_at(
                "`new(...)` constructor call missing its callee symbol",
                &cx.fn_sym,
            )
        })?;
        call_ctor_level(cx, h, ctor, Some(ctor_call))?;
    } else if is_super
        && cx
            .fn_sym
            .subroutine_flags()
            .contains(sv_lang::MethodFlags::DEFAULTED_SUPER_ARG)
        && let Some(base_ctor) = ty.class_constructor()
    {
        // `super.new(default)` (LRM 8.17): the constructor's inherited
        // arguments go to the base constructor.
        call_ctor_level(cx, h, base_ctor, None)?;
    }
    // Review fix (r1), Task 6 finding 1: this `NewClass` expression IS the
    // explicit `super.new(...)` statement -- `class_sym`/`ty` above name
    // the BASE just finished constructing (its base-chaining, its own
    // field inits, and its own constructor body all already ran, either
    // just above or recursively one level further down for a multi-level
    // `super.new()` chain). LRM 1800-2023 §8.7: "After the base class
    // constructor call ... has completed, each property defined in the
    // class shall be initialized" -- "the class" here is `cur_class_sym`,
    // the class that lexically wrote this `super.new(...)` statement, NOT
    // `class_sym` (its base). Run its own field inits now, exactly once,
    // using the same object handle `h` (there is exactly one object under
    // construction across this whole chain).
    if let Some(cur_class_sym) = cur_class_sym {
        run_own_field_inits(cx, h, cur_class_sym)?;
    }
    Ok(LoweredValue::Packed(handle_as_packed(cx, h)))
}

/// `new src` (LRM 1800-2023 8.12, shallow copy): a new object of `src`'s
/// DYNAMIC class -- through `sv_rt_obj`'s `Copy`, which clones the object's
/// template and fields, retaining every handle field, without running a
/// constructor or any property initializer. The result is a fresh reference
/// (refcount 1) the caller owns. A null source yields the null handle (the
/// LRM leaves it undefined).
pub fn lower_copy_class<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let src = e.copy_class_source().ok_or_else(|| {
        LoweringError::unsupported_at("a `new` copy expression with no source", &cx.fn_sym)
    })?;
    let h = receiver_handle(cx, src)?;
    let i64t = cx.ctx.i64_type();
    let null = cx.ctx.ptr_type(AddressSpace::default()).const_null();
    let new = obj_call(
        cx,
        ObjOp::Copy,
        h,
        i64t.const_zero(),
        i64t.const_zero(),
        null,
    );
    Ok(LoweredValue::Packed(handle_as_packed(cx, new)))
}

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

    /// Classes plan Task 7 regression (found running this task's own
    /// `abstract_pure_virtual.sv` fixture): a dot call through a
    /// `shape`-typed (abstract, pure-virtual) handle resolves
    /// `call_subroutine()` to the SYNTHESIZED STUB `Symbol::method_
    /// prototype_subroutine()` builds for the still-unimplemented `pure
    /// virtual` declaration -- `Subroutine`-kind, `subroutine_this_var() ==
    /// None`, the SAME shape a genuinely `static` method has. Before this
    /// fix, `is_virtual_method` mistook that `this_var`-less shape for
    /// "static, not virtual" and routed the call through the ordinary
    /// direct-call path, which found (or, via `resolve_or_lower_static_
    /// method`'s own identical confusion, lazily mis-declared) a
    /// RECEIVER-LESS 0-param function under the stub's own mangled name --
    /// confirmed live: "argument count does not match the callee's
    /// declared parameter count". `is_virtual_method` must still say
    /// `true` here, via `Symbol::subroutine_prototype()` recovering the
    /// real (virtual, pure) classification a bare `this_var` check cannot.
    #[test]
    fn pure_virtual_stub_dot_call_is_still_recognized_as_virtual() {
        let design = compile_source(
            "virtual class shape;\n\
             pure virtual function int area();\n\
             endclass\n\
             class square extends shape;\n\
             function int area(); return 1; endfunction\n\
             endclass\n\
             module top;\n\
             function void show(shape s);\n\
             $display(\"%0d\", s.area());\n\
             endfunction\n\
             endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let top = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let show = top.members().find(|m| m.name() == "show").unwrap();
        let body = show.body().unwrap();
        fn find_call<'d>(node: sv_lang::SemNode<'d>) -> Option<sv_lang::Symbol<'d>> {
            if let Some(e) = node.as_expression()
                && e.kind() == ExpressionKind::Call
                && let Some(callee) = e.call_subroutine()
            {
                return Some(callee);
            }
            node.children().into_iter().find_map(find_call)
        }
        let callee = find_call(body.as_sem_node()).expect("s.area() must be findable");
        assert_eq!(callee.kind(), SymbolKind::Subroutine);
        assert!(
            callee.subroutine_this_var().is_none(),
            "this test's own premise: the pure-virtual stub's this_var must be None"
        );
        assert!(
            is_virtual_method(&callee).unwrap(),
            "a pure-virtual stub's dot-call callee must still be recognized as virtual"
        );
    }

    /// Review fix (r2 #2), Task 7 finding 1: the BARE-call counterpart to
    /// [`pure_virtual_stub_dot_call_is_still_recognized_as_virtual`] above
    /// -- a bare, implicit-`this` call to a method that is still `pure
    /// virtual` AT THE CALLING LEXICAL LEVEL (`shape::double_area` calling
    /// `area()` with no receiver, from inside `shape` itself, the class
    /// that declares `area` pure) resolves `call_subroutine()` to the raw
    /// `MethodPrototype` (per `resolve_implicit_this_instance_method`'s
    /// own doc comment on the colon/bare-lookup shape), which `method_
    /// prototype_subroutine()` dereferences to the SAME `this_var() ==
    /// None` synthesized stub the dot-call case sees. Before this fix,
    /// `resolve_implicit_this_instance_method` returned `None` here (the
    /// EXACT same `this_var`-less misclassification `is_virtual_method`
    /// itself was fixed for in the dot-call test above), so `func.rs`'s/
    /// `expr.rs`'s own intercepts never routed this call into the class
    /// machinery at all -- confirmed end to end by `classes_vs_iverilog.
    /// rs`'s `virtual_dispatch_bare_this_pure_virtual_matches_verilator_
    /// bit_for_bit`.
    #[test]
    fn bare_call_to_a_still_pure_virtual_method_is_recognized_as_an_instance_method() {
        let design = compile_source(
            "virtual class shape;\n\
             pure virtual function int area();\n\
             function int double_area();\n\
             return 2*area();\n\
             endfunction\n\
             endclass\n\
             class square extends shape;\n\
             function int area(); return 1; endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let shape = unit.find("shape").unwrap();
        let double_area = shape.members().find(|m| m.name() == "double_area").unwrap();
        fn find_call<'d>(node: sv_lang::SemNode<'d>) -> Option<sv_lang::Expression<'d>> {
            if let Some(e) = node.as_expression()
                && e.kind() == ExpressionKind::Call
            {
                return Some(e);
            }
            node.children().into_iter().find_map(find_call)
        }
        let call = find_call(double_area.body().unwrap().as_sem_node())
            .expect("2*area() must contain a findable area() call");
        let callee = call
            .call_subroutine()
            .expect("bare area() call must resolve to a callee symbol");
        assert!(
            resolve_implicit_this_instance_method(callee)
                .unwrap_or_else(|e| panic!("resolve_implicit_this_instance_method failed: {e}"))
                .is_some(),
            "a bare call to a still-pure-virtual method, from a sibling method of its own \
             declaring class, must be recognized as an instance-method call"
        );
    }

    /// Classes plan Task 7's own named negative test (§3 Task 7's
    /// "Acceptance" text): `new AbstractClass()` is rejected by `compile_
    /// source` itself (D9 -- 8.21's illegal-instantiation check is
    /// frontend-enforced; this plan never re-implements it). Confirms the
    /// premise [`VtableLayout::for_template`]'s own doc comment rests on:
    /// an abstract class is never itself anyone's dynamic type, so its own
    /// still-unfilled pure-virtual slots never need to be dispatched to.
    #[test]
    fn new_on_an_abstract_class_is_rejected_by_the_frontend() {
        let design = compile_source(
            "virtual class shape;\n\
             pure virtual function int area();\n\
             endclass\n\
             module top;\n\
             shape s;\n\
             initial s = new;\n\
             endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        assert!(
            design.diagnostics().has_errors(),
            "`new` on an abstract class must be a compile-time diagnostic, not a clean compile"
        );
    }

    /// Classes plan Task 7 (LRM 8.15): [`call_is_explicit_super`]'s own
    /// load-bearing claim -- a `super.f()` call and a bare, implicit-`this`
    /// `f()` call, reached from a class that does NOT itself override `f`
    /// (so both resolve `call_subroutine()` to the EXACT SAME base-class
    /// `Symbol`), are nonetheless told apart correctly by source syntax
    /// alone. Exercised via `DesignSyntaxScope` directly (not through a
    /// full `sv-sim run`, which `super_call_not_virtual_matches_iverilog_
    /// bit_for_bit` in `classes_vs_iverilog.rs` already covers end to end).
    #[test]
    fn explicit_super_call_is_detected_only_for_an_actual_super_prefix() {
        let design = compile_source(
            "class base;\n\
             virtual function int f(); return 1; endfunction\n\
             endclass\n\
             class derived extends base;\n\
             function int g();\n\
             return super.f();\n\
             endfunction\n\
             function int h();\n\
             return f();\n\
             endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let _scope = DesignSyntaxScope::enter(&design);
        let unit = design.compilation_units().next().unwrap();
        let derived = unit.find("derived").unwrap();
        let g = derived.members().find(|m| m.name() == "g").unwrap();
        let h = derived.members().find(|m| m.name() == "h").unwrap();
        let g_call = g.body().unwrap().expressions().into_iter().next().unwrap();
        let h_call = h.body().unwrap().expressions().into_iter().next().unwrap();
        assert_eq!(
            g_call.call_subroutine().unwrap().uid(),
            h_call.call_subroutine().unwrap().uid(),
            "this test's own premise: both calls must resolve to the identical base::f symbol"
        );
        assert!(
            call_is_explicit_super(g_call),
            "super.f() must be detected as an explicit super call"
        );
        assert!(
            !call_is_explicit_super(h_call),
            "a bare f() must NOT be detected as an explicit super call, even though it \
             resolves to the identical callee symbol"
        );
    }

    /// The four `std`-package intrinsics are all recognized by scope
    /// identity -- this is the test Task 1's own acceptance criteria rests
    /// the rest of the plan's intrinsic-dispatch design on (§0). Found via
    /// `Design::std_package()` directly (never specializing
    /// `weak_reference#(type T)`, which needs a real class `T` and a
    /// 1800-2023-or-later compilation this crate's `compile_source` has no
    /// knob for yet -- irrelevant here: `is_builtin_std_class` only needs
    /// the GENERIC class def symbol itself, not a specialization of it).
    #[test]
    fn std_process_semaphore_mailbox_weak_reference_are_recognized() {
        let design = compile_source("module m;\nendmodule\n")
            .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let std_pkg = design.std_package();
        assert_eq!(std_pkg.name(), "std");
        for (name, expect) in [
            ("process", StdIntrinsic::Process),
            ("semaphore", StdIntrinsic::Semaphore),
            ("mailbox", StdIntrinsic::Mailbox),
            ("weak_reference", StdIntrinsic::WeakReference),
        ] {
            let sym = std_pkg
                .members()
                .find(|m| m.name() == name)
                .unwrap_or_else(|| panic!("std package must declare {name}"));
            assert_eq!(
                is_builtin_std_class(&sym),
                Some(expect),
                "mismatch for {name}"
            );
        }
    }

    /// A user class legitimately named `mailbox`, declared inside a
    /// user package (never under the real `std` package), must NOT be
    /// recognized as the built-in intrinsic -- only scope identity
    /// qualifies, never a name match alone (this is the precise failure
    /// mode `is_builtin_std_class`'s doc comment calls out: "never by
    /// string-matching a user's own same-named class").
    #[test]
    fn a_user_class_of_the_same_name_outside_std_is_not_recognized() {
        let design = compile_source(
            "package p;\n\
             class mailbox;\n\
             endclass\n\
             endpackage\n\
             module m;\n\
             import p::mailbox;\n\
             mailbox mb;\n\
             endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        assert!(
            !design.diagnostics().has_errors(),
            "the shadowing-free user `mailbox` fixture must compile cleanly: {}",
            design.diagnostics()
        );
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let sym = body.find("mb").unwrap().value_type().unwrap().as_symbol();
        assert_eq!(sym.name(), "mailbox");
        assert_eq!(
            is_builtin_std_class(&sym),
            None,
            "a user class named mailbox, outside the std package, must not be mistaken for \
             the built-in generic"
        );
    }

    /// A non-class symbol (an ordinary module-level variable) is always
    /// `None` -- the kind pre-filter at the top of the function, not just
    /// the name/scope walk below it.
    #[test]
    fn a_non_class_symbol_is_never_recognized() {
        let design = compile_source("module m;\nint x;\nendmodule\n")
            .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let x = body.find("x").unwrap();
        assert_eq!(x.kind(), SymbolKind::Variable);
        assert_eq!(is_builtin_std_class(&x), None);
    }

    /// Task 5's own literal unit-test ask: `ObjectLayout` field ordering
    /// for a 3-property class -- declaration order, never re-sorted (the
    /// mixed types -- `int`/`real`/`bit` -- also exercise that every one
    /// of this crate's supported non-collection property kinds gets a
    /// slot, not just the integral common case).
    #[test]
    fn object_layout_orders_fields_by_declaration() {
        let design = compile_source(
            "class foo;\n\
             int a;\n\
             real b;\n\
             bit c;\n\
             function void m();\n\
             endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let class_sym = unit
            .find("foo")
            .unwrap_or_else(|| panic!("top-level class `foo` must be findable"));
        let layout = ObjectLayout::for_template(class_sym)
            .unwrap_or_else(|e| panic!("ObjectLayout::for_template failed: {e}"));
        let names: Vec<&str> = layout.fields().iter().map(|f| f.sym.name()).collect();
        assert_eq!(
            names,
            ["a", "b", "c"],
            "fields must stay in declaration order, never re-sorted"
        );
        // Strictly increasing, word-addressed, non-overlapping offsets.
        let offsets: Vec<usize> = layout.fields().iter().map(|f| f.slot.offset).collect();
        assert_eq!(offsets[0], 0);
        for w in 1..offsets.len() {
            assert!(
                offsets[w] >= offsets[w - 1] + layout.fields()[w - 1].slot.words,
                "field {w}'s offset must start no earlier than the previous field's own end"
            );
        }
        assert_eq!(
            layout.total_words(),
            offsets[2] + layout.fields()[2].slot.words
        );
        assert!(
            layout.handle_field_slots().is_empty(),
            "none of a/b/c is a class handle"
        );
    }

    /// [`ObjectLayout::handle_field_slots`] finds a class-typed field --
    /// Task 3's `release` recursion, wired to the real computation here
    /// (this task's own Step 6).
    #[test]
    fn object_layout_finds_a_class_typed_handle_field() {
        let design = compile_source(
            "class node;\n\
             int v;\n\
             node next;\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let class_sym = unit
            .find("node")
            .unwrap_or_else(|| panic!("top-level class `node` must be findable"));
        let layout = ObjectLayout::for_template(class_sym)
            .unwrap_or_else(|e| panic!("ObjectLayout::for_template failed: {e}"));
        let handle_slots = layout.handle_field_slots();
        assert_eq!(
            handle_slots.len(),
            1,
            "exactly one field (`next`) is a class handle"
        );
        let next_slot = layout
            .slot_of(
                &unit
                    .find("node")
                    .unwrap()
                    .members()
                    .find(|m| m.name() == "next")
                    .unwrap(),
            )
            .unwrap();
        assert_eq!(handle_slots[0], next_slot);
    }

    /// `var`'s declared class type's symbol, from the single top module of
    /// `design` (how these tests reach a generic-class SPECIALIZATION: only
    /// a use like `Box#(int) a;` makes slang build one).
    fn var_class_sym<'d>(design: &'d sv_lang::Design, var: &str) -> sv_lang::Symbol<'d> {
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let v = body
            .members()
            .find(|m| m.name() == var)
            .unwrap_or_else(|| panic!("variable `{var}` must be a member of the top module"));
        v.value_type()
            .unwrap_or_else(|| panic!("`{var}` must have a type"))
            .as_symbol()
    }

    /// Classes plan Task 9 (8.25): two specializations of one generic class
    /// are two classes -- distinct specialization keys, distinct
    /// `ClassTemplateId`s that each resolve back to their own class, distinct
    /// object layouts (a `T v` field of a different type), distinct mangled
    /// method names, and a repeated use of one binding is the SAME key.
    #[test]
    fn two_specializations_of_one_generic_class_have_distinct_identity() {
        let design = compile_source(
            "class Box #(type T = int);\n\
             T v;\n\
             static int n;\n\
             virtual function T get(); return v; endfunction\n\
             endclass\n\
             module top;\n\
             Box#(int) a;\n\
             Box#(string) b;\n\
             Box#(int) c;\n\
             endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let a = var_class_sym(&design, "a");
        let b = var_class_sym(&design, "b");
        let c = var_class_sym(&design, "c");
        let key = |s: &sv_lang::Symbol<'_>| {
            sv_sim_sim::netlist::class_specialization_key(s.as_type().unwrap())
        };
        assert_ne!(
            key(&a),
            key(&b),
            "Box#(int) and Box#(string) are two classes"
        );
        assert_eq!(
            key(&a),
            key(&c),
            "two uses of the SAME binding are one specialization"
        );

        reset_class_registries();
        register_template(ClassTemplateId(7_100), a).expect("register Box#(int)");
        register_template(ClassTemplateId(7_101), b).expect("register Box#(string)");
        assert_eq!(class_template_id_of(&a).unwrap(), ClassTemplateId(7_100));
        assert_eq!(class_template_id_of(&b).unwrap(), ClassTemplateId(7_101));
        assert_eq!(
            class_template_id_of(&c).unwrap(),
            ClassTemplateId(7_100),
            "the second `Box#(int)` use resolves to the first one's id"
        );

        let a_layout = ObjectLayout::for_template(a).unwrap();
        let b_layout = ObjectLayout::for_template(b).unwrap();
        assert_eq!(a_layout.fields().len(), 1, "`n` is static, not a field");
        assert!(a_layout.fields()[0].sym.value_type().unwrap().is_integral());
        assert!(b_layout.fields()[0].sym.value_type().unwrap().is_string());
        let a_statics = ObjectLayout::for_statics(a).unwrap();
        assert_eq!(
            a_statics
                .fields()
                .iter()
                .map(|f| f.sym.name())
                .collect::<Vec<_>>(),
            ["n"]
        );

        let a_get = a.members().find(|m| m.name() == "get").unwrap();
        let b_get = b.members().find(|m| m.name() == "get").unwrap();
        assert_ne!(
            crate::func::mangled_subroutine_name(&a_get).unwrap(),
            crate::func::mangled_subroutine_name(&b_get).unwrap(),
            "Box#(int)::get and Box#(string)::get must not share a symbol name"
        );
        assert_eq!(
            VtableLayout::for_template(a).unwrap().len(),
            1,
            "one virtual method, one slot, per specialization"
        );
        assert_eq!(VtableLayout::for_template(b).unwrap().len(), 1);
    }

    /// Classes plan Task 9 (8.25.1): a class declared inside a class is its
    /// own class (own `ClassTemplateId`, layout, key), and two `Inner`s
    /// declared in two different outers -- or used as the type argument of
    /// one generic -- never collapse into one.
    #[test]
    fn nested_classes_have_their_own_identity_even_when_names_collide() {
        let design = compile_source(
            "class Outer1;\n\
             int o;\n\
             class Inner; int x; endclass\n\
             endclass\n\
             class Outer2;\n\
             class Inner; int x; int y; endclass\n\
             endclass\n\
             class Box #(type T = int); T v; endclass\n\
             module top;\n\
             Outer1::Inner i1;\n\
             Outer2::Inner i2;\n\
             Box#(Outer1::Inner) b1;\n\
             Box#(Outer2::Inner) b2;\n\
             endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let i1 = var_class_sym(&design, "i1");
        let i2 = var_class_sym(&design, "i2");
        let b1 = var_class_sym(&design, "b1");
        let b2 = var_class_sym(&design, "b2");
        let unit = design.compilation_units().next().unwrap();
        let outer1 = unit.find("Outer1").unwrap();
        let key = |s: &sv_lang::Symbol<'_>| {
            sv_sim_sim::netlist::class_specialization_key(s.as_type().unwrap())
        };
        assert_ne!(key(&i1), key(&outer1), "Inner is not its enclosing class");
        assert_ne!(key(&i1), key(&i2), "Outer1::Inner is not Outer2::Inner");
        assert_ne!(
            key(&b1),
            key(&b2),
            "Box#(Outer1::Inner) is not Box#(Outer2::Inner)"
        );

        reset_class_registries();
        register_template(ClassTemplateId(7_110), outer1).unwrap();
        let l1 = register_template(ClassTemplateId(7_111), i1).unwrap();
        let l2 = register_template(ClassTemplateId(7_112), i2).unwrap();
        assert_eq!(class_template_id_of(&i1).unwrap(), ClassTemplateId(7_111));
        assert_eq!(class_template_id_of(&i2).unwrap(), ClassTemplateId(7_112));
        assert_eq!(l1.total_words(), 1, "Outer1::Inner has one field");
        assert_eq!(l2.total_words(), 2, "Outer2::Inner has two fields");
        register_template(ClassTemplateId(7_113), b1).unwrap();
        register_template(ClassTemplateId(7_114), b2)
            .expect("the two Box specializations register under distinct keys");
    }

    /// Classes plan Task 9 review fix (r2): two non-generic, non-nested
    /// classes of the same name in different packages have distinct
    /// specialization keys AND distinct mangled method names (both used to
    /// be `Foo`/hash 0, so `p2::Foo` ran `p1::Foo`'s bodies).
    #[test]
    fn same_named_classes_in_two_packages_have_distinct_mangled_methods() {
        let design = compile_source(
            "package p1;\n\
             class Foo; int x; function new(); x = 1; endfunction\n\
             function int get(); return x; endfunction endclass\n\
             endpackage\n\
             package p2;\n\
             class Foo; int x; function new(); x = 2; endfunction\n\
             function int get(); return x; endfunction endclass\n\
             endpackage\n\
             module top; p1::Foo a; p2::Foo b; endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let a = var_class_sym(&design, "a");
        let b = var_class_sym(&design, "b");
        assert_ne!(
            sv_sim_sim::netlist::class_specialization_key(a.as_type().unwrap()),
            sv_sim_sim::netlist::class_specialization_key(b.as_type().unwrap()),
            "p1::Foo and p2::Foo are two classes"
        );
        for member in ["new", "get"] {
            let a_m = a.members().find(|m| m.name() == member).unwrap();
            let b_m = b.members().find(|m| m.name() == member).unwrap();
            assert_ne!(
                crate::func::mangled_subroutine_name(&a_m).unwrap(),
                crate::func::mangled_subroutine_name(&b_m).unwrap(),
                "p1::Foo::{member} and p2::Foo::{member} must not share a symbol name"
            );
        }
    }

    /// Re-registering one specialization key under a DIFFERENT id is the
    /// loud collision error, never a silent merge.
    #[test]
    fn registering_one_specialization_under_two_ids_is_a_loud_error() {
        let design = compile_source(
            "class Box #(type T = int); T v; endclass\n\
             module top; Box#(int) a; endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let a = var_class_sym(&design, "a");
        reset_class_registries();
        register_template(ClassTemplateId(7_120), a).unwrap();
        let err = register_template(ClassTemplateId(7_121), a)
            .expect_err("the same key under a second id must be rejected");
        assert!(
            err.message.contains("identical specialization key"),
            "got: {}",
            err.message
        );
    }

    /// Classes plan Task 6, Step 1: a class WITH a base class (`extends`)
    /// now gets a layout that is the base's own fields FIRST, then the
    /// derived class's own -- superseding Task 5's own `ObjectLayout::
    /// for_template` scope boundary (a plain rejection), which this test
    /// used to assert.
    #[test]
    fn object_layout_includes_inherited_fields_base_first() {
        let design = compile_source(
            "class base;\n\
             int x;\n\
             endclass\n\
             class derived extends base;\n\
             int y;\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let base_sym = unit
            .find("base")
            .unwrap_or_else(|| panic!("top-level class `base` must be findable"));
        let derived_sym = unit
            .find("derived")
            .unwrap_or_else(|| panic!("top-level class `derived` must be findable"));
        let derived_layout = ObjectLayout::for_template(derived_sym)
            .unwrap_or_else(|e| panic!("ObjectLayout::for_template(derived) failed: {e}"));
        let names: Vec<&str> = derived_layout
            .fields()
            .iter()
            .map(|f| f.sym.name())
            .collect();
        assert_eq!(
            names,
            ["x", "y"],
            "base's own field(s) must come first, then derived's own, never re-sorted"
        );
        assert_eq!(derived_layout.total_words(), 2);
        // Self-consistency (this impl's own load-bearing property, per
        // `ObjectLayout`'s own doc comment): `base`'s field `x`, computed
        // from `base`'s OWN layout alone, lands at the IDENTICAL `FieldSlot`
        // `derived`'s layout placed it at -- this is what makes `read_field`/
        // `write_field` (keyed by `member.parent()`, the field's OWN
        // declaring class, never the dynamic/leaf class) correct for an
        // inherited field with no change of their own.
        let base_layout = ObjectLayout::for_template(base_sym)
            .unwrap_or_else(|e| panic!("ObjectLayout::for_template(base) failed: {e}"));
        let x_in_base = base_layout
            .slot_of(&base_sym.members().find(|m| m.name() == "x").unwrap())
            .unwrap();
        let x_in_derived = derived_layout
            .slot_of(&base_sym.members().find(|m| m.name() == "x").unwrap())
            .unwrap();
        assert_eq!(x_in_base, x_in_derived);
    }

    /// Classes plan Task 15 (LRM 18.4): the layout lists a class's `rand`/
    /// `randc` properties -- the non-random `c` is left out -- in layout
    /// order, base-class properties first, and `register_template` hands the
    /// same list to the object runtime (`objects::rand_props`), which sizes
    /// each object's `rand_mode` bit set from it (18.8).
    #[test]
    fn rand_props_lists_rand_and_randc_in_layout_order_base_first() {
        use sv_sim_sim::objects::{RandKind, RandProp, rand_props};
        let design = compile_source(
            "class A;\n\
             rand int a;\n\
             randc bit [3:0] b;\n\
             int c;\n\
             endclass\n\
             class B extends A;\n\
             rand int d;\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let a_sym = unit.find("A").expect("class A must be findable");
        let b_sym = unit.find("B").expect("class B must be findable");
        fn member<'d>(class: &sv_lang::Symbol<'d>, name: &str) -> sv_lang::Symbol<'d> {
            class
                .members()
                .find(|m| m.name() == name)
                .unwrap_or_else(|| panic!("member `{name}` must exist"))
        }
        let a_layout = ObjectLayout::for_template(a_sym).unwrap();
        let b_layout = ObjectLayout::for_template(b_sym).unwrap();
        let slot_a = a_layout.slot_of(&member(&a_sym, "a")).unwrap();
        let slot_b = a_layout.slot_of(&member(&a_sym, "b")).unwrap();
        let slot_c = a_layout.slot_of(&member(&a_sym, "c")).unwrap();
        let slot_d = b_layout.slot_of(&member(&b_sym, "d")).unwrap();
        assert_ne!(slot_c, slot_a, "premise: `c` has its own slot");
        assert_ne!(slot_c, slot_b, "premise: `c` has its own slot");
        let expect_a = vec![
            RandProp {
                slot: slot_a,
                kind: RandKind::Rand,
            },
            RandProp {
                slot: slot_b,
                kind: RandKind::RandC,
            },
        ];
        let expect_b = vec![
            expect_a[0],
            expect_a[1],
            RandProp {
                slot: slot_d,
                kind: RandKind::Rand,
            },
        ];
        assert_eq!(a_layout.rand_props(), expect_a);
        assert_eq!(b_layout.rand_props(), expect_b);
        // The derived layout keeps the inherited slots, so a property's
        // `rand_mode` index means the same thing on the base and the derived
        // object.
        assert_eq!(b_layout.slot_of(&member(&a_sym, "a")).unwrap(), slot_a);
        assert_eq!(b_layout.slot_of(&member(&a_sym, "b")).unwrap(), slot_b);

        register_template(ClassTemplateId(7_130), a_sym).unwrap();
        register_template(ClassTemplateId(7_131), b_sym).unwrap();
        assert_eq!(rand_props(ClassTemplateId(7_130)), expect_a);
        assert_eq!(rand_props(ClassTemplateId(7_131)), expect_b);
    }

    /// Classes plan Task 6, Step 5 preflight: verifies the real sv-lang API
    /// shape this task's extern-method handling depends on, against the
    /// plan's OWN doctest-backed claim (`sv_lang::ast::Symbol::
    /// method_prototype_subroutine`'s doc comment: for a CLASS's own
    /// `extern` method, `.members()` gives the raw `MethodPrototype`, and
    /// `.method_prototype_subroutine()` -- NOT `.method_prototype_first_
    /// extern_impl()`, which is the plan's own literal (and, verified here,
    /// WRONG for this exact shape) text -- resolves it to the real,
    /// out-of-block `Subroutine`. That resolved subroutine must ALSO have a
    /// bound `this` (`subroutine_this_var()`), exactly like an ordinary
    /// in-block instance method, for `classes::lower_method_body` to bind a
    /// receiver against it at all.
    #[test]
    fn extern_method_prototype_resolves_to_a_this_bearing_subroutine() {
        let design = compile_source(
            "class pair;\n\
             int a;\n\
             int b;\n\
             extern function int sum();\n\
             endclass\n\
             function int pair::sum();\n\
             return a + b;\n\
             endfunction\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let class_sym = unit
            .find("pair")
            .unwrap_or_else(|| panic!("top-level class `pair` must be findable"));
        let proto = class_sym
            .members()
            .find(|m| m.name() == "sum")
            .unwrap_or_else(|| panic!("`pair` must declare a `sum` member"));
        assert_eq!(
            proto.kind(),
            SymbolKind::MethodPrototype,
            "an UNRESOLVED `.members()` walk (unlike `.find()`) must give the raw prototype"
        );
        assert!(
            proto.method_prototype_first_extern_impl().is_none(),
            "the plan's own literal text named this accessor, but it is for an INTERFACE's \
             modport-implemented `extern` method (`module m(Iface i); function void i.f(); \
             endfunction`), a different mechanism -- it must be `None` here"
        );
        let real = proto.method_prototype_subroutine().unwrap_or_else(|| {
            panic!("`method_prototype_subroutine` must resolve the out-of-block `pair::sum`")
        });
        assert_eq!(real.kind(), SymbolKind::Subroutine);
        assert_eq!(real.name(), "sum");
        assert!(
            real.subroutine_this_var().is_some(),
            "the resolved out-of-block implementation must have a bound `this`, exactly like \
             an ordinary in-block instance method"
        );
    }

    /// Classes plan Task 6 preflight: verifies `Type::class_base_
    /// constructor_call()`'s exact shape for the three cases `lower_new_
    /// class`'s own `embedded_super`/`chain_to_base` split depends on --
    /// `§1` of this task's own design notes.
    #[test]
    fn class_base_constructor_call_shapes() {
        let design = compile_source(
            "class root; endclass\n\
             class explicit_super extends root;\n\
             function new();\n\
             super.new();\n\
             endfunction\n\
             endclass\n\
             class no_explicit_ctor extends root;\n\
             endclass\n\
             module top;\n\
             root r;\n\
             explicit_super e;\n\
             no_explicit_ctor n;\n\
             initial begin\n\
             r = new;\n\
             e = new;\n\
             n = new;\n\
             end\n\
             endmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        // An explicit `super.new();` first statement: `class_base_
        // constructor_call()` IS that literal embedded `NewClass` node.
        let e_ty = body.find("e").unwrap().value_type().unwrap();
        let call = e_ty
            .class_base_constructor_call()
            .expect("explicit_super has a base-constructor call");
        assert_eq!(call.kind(), ExpressionKind::NewClass);
        assert_eq!(call.new_class_is_super_class(), Some(true));
        // A plain `extends root;` with no explicit `new()` and a base with
        // no constructor of its own at all: no call is synthesized, since
        // there is nothing to call and nothing to diagnose -- `chain_to_
        // base` must handle this by running `root`'s own (empty) field
        // inits only, no call at all.
        let n_ty = body.find("n").unwrap().value_type().unwrap();
        assert!(n_ty.class_base_constructor_call().is_none());
        assert!(n_ty.class_base().is_some());
        assert!(n_ty.class_base().unwrap().class_constructor().is_none());
        // A plain class with no `extends` clause at all has no base.
        let r_ty = body.find("r").unwrap().value_type().unwrap();
        assert!(r_ty.class_base_constructor_call().is_none());
        assert!(r_ty.class_base().is_none());
    }

    /// A queue, dynamic array or associative array property (constraints plan
    /// C14) is one handle-sized field, registered as a collection field so the
    /// object heap frees and clones it with its object.
    #[test]
    fn object_layout_stores_each_collection_property_as_one_handle() {
        let src = "class k;\nint a;\nint q[$];\nint d[];\nint m[string];\nendclass\n\
                   module top;\nendmodule\n";
        let design = compile_source(src).expect("compile");
        let unit = design.compilation_units().next().unwrap();
        let class_sym = unit.find("k").expect("class k");
        let layout = ObjectLayout::for_template(class_sym).expect("collections are storable");
        assert_eq!(layout.fields.len(), 4);
        let slots = layout.collection_field_slots();
        assert_eq!(slots.len(), 3, "q, d and m are collection fields");
        assert!(slots.iter().all(|s| s.words == 2));
    }

    /// A fixed-size unpacked array or an unpacked struct is a class property
    /// stored as one flat value (ledger XC-059, LRM 6.18 / 7.4): its slot is as
    /// wide as its flat stored form, instance and static alike.
    #[test]
    fn object_layout_stores_unpacked_aggregate_properties_flat() {
        // `int q[3]` is three 32-bit elements (2 bits per bit for the 4-state
        // value/unknown halves: 192 bits, 3 words); the struct is one `int`.
        for (decl, words) in [
            ("int q[3];", 3),
            ("struct { int a; byte b; } q;", 2),
            ("static int q[3];", 3),
        ] {
            let src = format!("class bad;\n{decl}\nendclass\nmodule top;\nendmodule\n");
            let design = compile_source(&src)
                .unwrap_or_else(|e| panic!("compile_source failed for `{decl}`: {e}"));
            let unit = design.compilation_units().next().unwrap();
            let class_sym = unit
                .find("bad")
                .unwrap_or_else(|| panic!("top-level class `bad` must be findable"));
            let layout = if decl.starts_with("static") {
                ObjectLayout::for_statics(class_sym)
            } else {
                ObjectLayout::for_template(class_sym)
            }
            .unwrap_or_else(|e| panic!("`{decl}` must be laid out: {}", e.message));
            assert_eq!(layout.fields().len(), 1, "{decl}");
            assert_eq!(layout.fields()[0].slot.words, words, "{decl}");
        }
    }

    /// A property with no fixed-width stored form is still a loud, named
    /// `LoweringError`, never a silently-dropped field: an unpacked union that
    /// holds a class handle (there is no flat form for a refcounted member
    /// that may or may not be the live one).
    #[test]
    fn object_layout_rejects_an_unpacked_union_holding_a_handle() {
        let src = "class h; endclass\nclass bad;\nunion { h x; int i; } q;\nendclass\n\
                   module top;\nendmodule\n";
        let design = compile_source(src).unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let class_sym = unit.find("bad").unwrap();
        let err = ObjectLayout::for_template(class_sym)
            .expect_err("a union holding a handle must be rejected, not silently dropped");
        assert!(
            err.message.contains("no fixed-width stored form"),
            "error should name the unsupported shape: {}",
            err.message
        );
    }

    /// Classes plan Task 8: the premise [`VtableLayout`]'s own Task 8 doc
    /// comment states -- verified live, not assumed -- that slang's
    /// `ClassSymbols.cpp::ClassType::handleImplements` (the non-interface,
    /// "an ordinary class implements an interface class" branch) never
    /// links an implementing class's own method back to the interface's
    /// `MethodPrototype` via `setOverride`, unlike an ordinary base-class
    /// override (8.14) or one interface class `extends`ing another. If this
    /// ever stopped being true, name-matching would be unnecessary (the
    /// existing override-chain walk `classify_virtual_member` already does
    /// for ordinary inheritance would just work), so this test's own
    /// failure would be the signal to simplify [`VtableLayout::for_template`]
    /// rather than a correctness bug in it.
    #[test]
    fn interface_implementation_has_no_override_link() {
        let design = compile_source(
            "interface class ifoo;\n\
             pure virtual function int get_val();\n\
             endclass\n\
             class a implements ifoo;\n\
             virtual function int get_val(); return 10; endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let ifoo = unit.find("ifoo").unwrap();
        let iface_proto = ifoo.members().find(|m| m.name() == "get_val").unwrap();
        assert_eq!(iface_proto.kind(), SymbolKind::MethodPrototype);
        assert!(
            iface_proto.method_prototype_override().is_none(),
            "an interface class's own top-level method prototype has no base to override"
        );
        let a = unit.find("a").unwrap();
        let a_get_val = a.members().find(|m| m.name() == "get_val").unwrap();
        assert_eq!(a_get_val.kind(), SymbolKind::Subroutine);
        assert!(
            a_get_val.subroutine_override().is_none(),
            "a class's own implementation of an interface method must have no override link \
             to the interface's MethodPrototype -- confirmed live against \
             ClassSymbols.cpp::ClassType::handleImplements, which never calls setOverride for \
             this relationship (see VtableLayout::for_template's own Task 8 doc comment)"
        );
        assert!(
            a_get_val.subroutine_prototype().is_none(),
            "nor does it resolve back to the interface's own MethodPrototype via \
             subroutine_prototype() -- that accessor is for an in-class `extern`/pure \
             declaration's own prototype, a different relationship entirely"
        );
    }

    /// Classes plan Task 8: [`VtableLayout::for_template`]'s own interface-
    /// aliasing pass gives TWO unrelated concrete classes' `get_val()` --
    /// `a`/`b` share no common base other than `ifoo` itself -- slots that
    /// both resolve from `ifoo::get_val`'s own `MethodPrototype` uid (and
    /// its synthesized-stub uid, the shape a dot-call through an
    /// `ifoo`-typed handle actually resolves `call_subroutine()` to -- see
    /// this module's own `classify_virtual_member` doc comment), each to
    /// ITS OWN class's real implementation -- the direct, symbol-level
    /// counterpart of `classes_vs_iverilog.rs`'s end-to-end
    /// `interface_class_dispatch_matches_verilator_bit_for_bit`.
    #[test]
    fn vtable_layout_aliases_interface_method_to_each_implementers_own_slot() {
        let design = compile_source(
            "interface class ifoo;\n\
             pure virtual function int get_val();\n\
             endclass\n\
             class a implements ifoo;\n\
             virtual function int get_val(); return 10; endfunction\n\
             endclass\n\
             class b implements ifoo;\n\
             virtual function int get_val(); return 20; endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let ifoo = unit.find("ifoo").unwrap();
        let iface_proto = ifoo.members().find(|m| m.name() == "get_val").unwrap();
        let iface_stub = iface_proto
            .method_prototype_subroutine()
            .expect("a pure interface method still gets a synthesized callable stub");

        let a = unit.find("a").unwrap();
        let a_get_val = a.members().find(|m| m.name() == "get_val").unwrap();
        let a_layout =
            VtableLayout::for_template(a).unwrap_or_else(|e| panic!("for_template(a): {e}"));
        let a_slot = a_layout
            .slot_of(&a_get_val)
            .expect("a::get_val must have its own slot");
        assert_eq!(
            a_layout.slot_of(&iface_proto),
            Some(a_slot),
            "ifoo::get_val's own MethodPrototype must alias to a::get_val's slot"
        );
        assert_eq!(
            a_layout.slot_of(&iface_stub),
            Some(a_slot),
            "ifoo::get_val's synthesized stub (what a dot-call through an ifoo-typed handle \
             actually resolves call_subroutine() to) must alias to the SAME slot"
        );
        assert_eq!(
            a_layout.impls()[a_slot].map(|s| s.uid()),
            Some(a_get_val.uid())
        );

        let b = unit.find("b").unwrap();
        let b_get_val = b.members().find(|m| m.name() == "get_val").unwrap();
        let b_layout =
            VtableLayout::for_template(b).unwrap_or_else(|e| panic!("for_template(b): {e}"));
        let b_slot = b_layout
            .slot_of(&b_get_val)
            .expect("b::get_val must have its own slot");
        assert_eq!(b_layout.slot_of(&iface_proto), Some(b_slot));
        assert_eq!(
            b_layout.impls()[b_slot].map(|s| s.uid()),
            Some(b_get_val.uid())
        );
    }

    /// Classes plan Task 8 review fix (r1): the name-to-slot mapping itself.
    /// Every other interface test has ONE interface method at slot 0, so
    /// aliasing every interface method to slot 0, or any positional /
    /// first-match mapping, passes them all. Here `ifoo` has two methods
    /// (`m1`, `m2`) and `ibar extends ifoo` adds `m3`; `a` has an unrelated
    /// two-method virtual base `pad` (so its interface slots are 2/3/4),
    /// `b` has no base and declares the same methods in a different order
    /// (`m3`, `m2`, `m1` -> slots 0/1/2). Each interface method must map
    /// to ITS OWN implementer-specific slot, and the three must be
    /// pairwise distinct. Mirrors the `interface_class_multi_method_
    /// slots.sv` fixture.
    #[test]
    fn vtable_layout_maps_each_interface_method_by_name_not_position() {
        let design = compile_source(
            "interface class ifoo;\n\
             pure virtual function int m1();\n\
             pure virtual function int m2();\n\
             endclass\n\
             interface class ibar extends ifoo;\n\
             pure virtual function int m3();\n\
             endclass\n\
             class pad;\n\
             virtual function int p1(); return 100; endfunction\n\
             virtual function int p2(); return 200; endfunction\n\
             endclass\n\
             class a extends pad implements ibar;\n\
             virtual function int m1(); return 1; endfunction\n\
             virtual function int m2(); return 2; endfunction\n\
             virtual function int m3(); return 3; endfunction\n\
             endclass\n\
             class b implements ibar;\n\
             virtual function int m3(); return 13; endfunction\n\
             virtual function int m2(); return 12; endfunction\n\
             virtual function int m1(); return 11; endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let proto = |iface: &str, name: &str| {
            unit.find(iface)
                .unwrap()
                .members()
                .find(|m| m.name() == name)
                .unwrap()
        };
        let check = |class: &str, expected_slots: [usize; 3]| {
            let cls = unit.find(class).unwrap();
            let layout = VtableLayout::for_template(cls)
                .unwrap_or_else(|e| panic!("for_template({class}): {e}"));
            let names = ["m1", "m2", "m3"];
            let mut seen = Vec::new();
            for (i, name) in names.iter().enumerate() {
                let own = cls.members().find(|m| m.name() == *name).unwrap();
                let iface = if *name == "m3" { "ibar" } else { "ifoo" };
                let iface_proto = proto(iface, name);
                let own_slot = layout
                    .slot_of(&own)
                    .unwrap_or_else(|| panic!("{class}::{name} must have its own slot"));
                assert_eq!(own_slot, expected_slots[i], "{class}::{name}'s own slot");
                assert_eq!(
                    layout.slot_of(&iface_proto),
                    Some(own_slot),
                    "{iface}::{name} must alias {class}::{name}'s own slot, not another \
                     method's"
                );
                let iface_stub = iface_proto.method_prototype_subroutine().unwrap();
                assert_eq!(layout.slot_of(&iface_stub), Some(own_slot));
                assert_eq!(
                    layout.impls()[own_slot].map(|s| s.uid()),
                    Some(own.uid()),
                    "{class}'s slot {own_slot} must hold {class}::{name}'s implementation"
                );
                seen.push(own_slot);
            }
            seen.sort_unstable();
            seen.dedup();
            assert_eq!(
                seen.len(),
                3,
                "{class}: three interface methods, three slots"
            );
        };
        check("a", [2, 3, 4]);
        check("b", [2, 1, 0]);
    }

    /// Classes plan Task 8 regression (found running this task's own
    /// `interface_class_via_base_deferred_impl.sv` fixture, not in the
    /// preflight corrections): `flattened_interfaces(derived_ty)` alone is
    /// EMPTY when `derived` implements an interface only TRANSITIVELY
    /// through its base class (`derived` itself writes no `implements`
    /// clause at all) -- `VtableLayout::for_template` must union every
    /// level's own `flattened_interfaces`, not just the leaf's, to find the
    /// alias. Before this fix, `for_template(derived)`'s interface-aliasing
    /// pass silently did nothing (iterating an empty `flattened_interfaces
    /// (derived_ty)`), so `ifoo::get_val`'s own uid never entered `by_uid`
    /// at all for `derived`'s own layout.
    #[test]
    fn vtable_layout_finds_an_interface_implemented_only_via_a_base_class() {
        let design = compile_source(
            "interface class ifoo;\n\
             pure virtual function int get_val();\n\
             endclass\n\
             virtual class base implements ifoo;\n\
             pure virtual function int get_val();\n\
             endclass\n\
             class derived extends base;\n\
             virtual function int get_val(); return 5; endfunction\n\
             endclass\n\
             module top;\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("compile_source failed: {e}"));
        let unit = design.compilation_units().next().unwrap();
        let derived = unit.find("derived").unwrap();
        let derived_ty = derived.as_type().unwrap();
        assert!(
            sv_sim_sim::netlist::flattened_interfaces(derived_ty).is_empty(),
            "this test's own premise: `derived`'s own flattened_interfaces must be empty -- \
             it implements ifoo only transitively, through `base`"
        );
        let ifoo = unit.find("ifoo").unwrap();
        let iface_proto = ifoo.members().find(|m| m.name() == "get_val").unwrap();
        let derived_get_val = derived.members().find(|m| m.name() == "get_val").unwrap();
        let layout = VtableLayout::for_template(derived)
            .unwrap_or_else(|e| panic!("for_template(derived): {e}"));
        let slot = layout
            .slot_of(&derived_get_val)
            .expect("derived::get_val must have its own slot");
        assert_eq!(
            layout.slot_of(&iface_proto),
            Some(slot),
            "ifoo::get_val must still alias to derived::get_val's slot even though the \
             `implements` clause was written on `base`, not `derived`"
        );
        assert_eq!(
            layout.impls()[slot].map(|s| s.uid()),
            Some(derived_get_val.uid())
        );
    }
}