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
//! Module/process discovery (Task S2, ledger CG-069/DT-048/XC-005/XC-006/
//! XC-007/XC-008; extended by Task 2, CG-079/CG-080/PR-084,
//! `docs/superpowers/plans/2026-09-26-wave-A2-process-kernels.md`): walks a
//! module's `sv_lang::Symbol` members to find and classify every one of the
//! 6 `ProceduralBlockKind` values (`initial`, plain `always` with an
//! edge-sensitive head, `always_ff` -- including its optional clock+async-
//! reset `EventList` head -- `always_comb`, `always_latch`, `final`), and
//! is the "unsupported in slice" guard for everything else -- every
//! construct outside the slice's restricted set (§"Slice scope",
//! `docs/superpowers/plans/2026-09-26-wave-A2-slice.md`) fails with a
//! named, `hierarchical_path()`-citing [`LoweringError`], never a silent
//! skip and never a panic.
//!
//! `sv-sim-codegen` is frontend-only by construction (it has an unconditional,
//! non-optional `sv-lang`/`sv-lang-kinds` dependency -- unlike `sv-sim-sim`,
//! which gates frontend-touching modules behind its own `frontend` feature
//! per `docs/CONTRACTS.md` D4), so this module needs no `#[cfg(feature =
//! "frontend")]` of its own.
use crate::types::TypeWidth;
use std::collections::{HashMap, HashSet};
use std::fmt;
use sv_sim_sim::symid::SymbolUid;

use crate::process_lower::{SignalSlot, SignalSlotClass};

use sv_lang::kinds::{ExpressionKind, StatementKind, SymbolKind, TimingControlKind};
use sv_lang::{
    AnalysisFlags, Design, EdgeKind, Expression, MethodFlags, ProceduralBlockKind, SemNode,
    Statement, Symbol, TimingControl, UnaryOp, Walk,
};
use sv_sim_sim::symid::SymbolId;

use crate::error::LoweringError;
pub use crate::sva::emit::procedure_inferred_disable;

/// The 6 `sv_lang::ProceduralBlockKind` values `discover_processes` accepts
/// (Task 2, `docs/superpowers/plans/2026-09-26-wave-A2-process-kernels.md`
/// -- the original 3-variant, A2-*slice*-only version of this enum has been
/// superseded now that `classify_procedure_kind` accepts every kind; the
/// name is kept as `SliceProcKind` rather than renamed, per that task's own
/// "implementer's call" note, to avoid churning every existing call site's
/// import for a rename alone).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SliceProcKind {
    Initial,
    Always,
    AlwaysComb,
    AlwaysLatch,
    AlwaysFF,
    Final,
    /// A static concurrent assertion statement (`assert property (...)`,
    /// `cover property`, `cover sequence`, `restrict property` at module
    /// level, or the equivalent `always assert property (...)`; LRM 16.14,
    /// [`static_assertion_statement`]). It is not a process the scheduler
    /// runs: `crate::sva::emit` compiles its automaton's kernels and the
    /// process body only holds its pass/fail action blocks, which the
    /// assertion engine runs in the Reactive region.
    StaticAssertion,
}

/// One accepted procedural block, as discovered by [`discover_processes`].
/// `clock` is `Some((clock_signal, edge))` for `Always`/`AlwaysFF` whose head
/// is a single `posedge`/`negedge` signal-event control, `None` for
/// `Initial`/`AlwaysComb`/`AlwaysLatch`/`Final` (none of which have a head
/// timing control at discovery time -- a leading `#delay` inside an
/// `initial` body is CFG-building's concern, Task S3a, not this function's)
/// **and also for an `Always` whose head is instead a plain `#delay`
/// (`TimingControlKind::Delay`) or `@*`/`@(*)` (`TimingControlKind::
/// ImplicitEvent`)** -- R-run Task 9 (NL-047/NL-048): neither shape names a
/// single clock signal, so `SliceProcKind::Always` is no longer proof that
/// `clock` is `Some(..)`; callers must check it.
/// `reset` is `Some((reset_signal, edge))` only for an `AlwaysFF` whose head
/// is a clock+async-reset `EventList` (Task 2, CG-079); never collapsed into
/// `clock` -- downstream body lowering (the reset-polarity `if`/`else`
/// inside the body) still needs to tell the two symbols apart. `read_set` is
/// the whole-procedure static read-set (CG-079's synthesized implicit
/// sensitivity list) for `AlwaysComb`/`AlwaysLatch` only, empty for every
/// other kind -- kept as owned [`SymbolId`]s, not `Symbol<'d>`s, because it
/// is sourced from a [`CombSensitivityIndex`] built from a transient
/// `Design::analyze` borrow strictly shorter-lived than `'d` (see that
/// type's own doc comment).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredProcess<'d> {
    pub sym: Symbol<'d>,
    pub kind: SliceProcKind,
    pub clock: Option<(Symbol<'d>, EdgeKind)>,
    pub reset: Option<(Symbol<'d>, EdgeKind)>,
    pub read_set: Vec<SymbolId>,
    /// `Some` for a [`SliceProcKind::StaticAssertion`] entry: the assertion it
    /// hosts (its action blocks run there, in the Reactive region). A static
    /// assertion's entry is the block itself (its root is the block's own body);
    /// the extra entry [`discover_processes`] adds, right after the enclosing
    /// process, for each procedural assertion nested in a block (16.14.6) has the
    /// enclosing block as `sym` and the assertion statement as its root
    /// ([`crate::sva::proc::HostedAssertion::procedural`]). `None` otherwise.
    pub assertion: Option<crate::sva::proc::HostedAssertion<'d>>,
}

/// Walks `module_body`'s direct members, finds every `SymbolKind::
/// ProceduralBlock`, and classifies it into a [`DiscoveredProcess`] or a
/// named [`LoweringError`]. Every non-procedural member (ports, nets,
/// variables, gate-primitive instances, generate blocks, ...) is skipped --
/// discovering *them* is STATE's `build_template_layout`/netlist
/// elaboration's job, not this function's (see the plan's "current tree
/// state" note on why this file does not touch `netlist::template.rs`).
///
/// Stops at the FIRST unsupported procedural block it encounters (in
/// `members()`'s declaration order) rather than accumulating the supported
/// ones and silently dropping the unsupported one -- a still-genuinely-
/// unsupported block (e.g. a plain `always @(a)` bare level-sensitive head,
/// or an `always_ff` with a level-sensitive/multi-signal head this file's
/// own `require_clock_and_optional_reset` still rejects) sitting next to a
/// perfectly good `always_ff` block still fails the whole call (XC-005/
/// CG-069's "never a silent no-op" discipline, applied to discovery itself;
/// `always_comb`/`always_latch`/`final` are no longer in this "unsupported"
/// set at all, per Task 2; nor, since R-run Task 9 (NL-047/NL-048), is a
/// plain `always @*`/implicit-sensitivity or `always #delay` head).
pub fn discover_processes<'d>(
    module_body: &Symbol<'d>,
    comb_sensitivity: &CombSensitivityIndex,
) -> Result<Vec<DiscoveredProcess<'d>>, LoweringError> {
    discover_processes_dispatching(module_body, comb_sensitivity, None)
}

/// [`discover_processes`] that also follows a virtual method call (8.20) into
/// every implementation `virtual_tasks` says a dynamic class can run, so an
/// `expect` (16.17) in an override is hosted for the caller of the base method.
/// Without `virtual_tasks` only the statically-resolved callee is followed.
pub fn discover_processes_dispatching<'d>(
    module_body: &Symbol<'d>,
    comb_sensitivity: &CombSensitivityIndex,
    virtual_tasks: Option<&sv_sim_sim::process::cfg::VirtualTasks<'d>>,
) -> Result<Vec<DiscoveredProcess<'d>>, LoweringError> {
    let mut out = Vec::new();
    // 17.3: the static assertions of a procedural checker instance are queued by
    // the procedure that instantiates it ([`collect_nested_assertions`]), not
    // run as processes of their own.
    let procedural_instances: HashSet<SymbolId> =
        sv_sim_sim::netlist::procedural_checkers(module_body)
            .iter()
            .map(|c| c.instance.uid())
            .collect();
    for (ordinal, m) in sv_sim_sim::netlist::module_items(module_body)
        .into_iter()
        .enumerate()
    {
        // A `class`/generic-class DECLARATION (`SymbolKind::ClassType`/
        // `GenericClassDef`) is a non-procedural member like a net or a
        // variable here. A generic class is only ever lowered through its
        // SPECIALIZATIONS (`crate::classes`, classes plan Task 9): each
        // `Box#(int)`-style binding a `new()` site reaches is its own
        // `ClassType` with its own template id, layout and methods, and a
        // generic class that is declared and never specialized has nothing
        // to lower. A class this crate cannot lower (an unsupported base,
        // say) fails loudly in `classes::ObjectLayout::for_template` when
        // a `new()` site reaches it, never here, since such a class can be
        // declared and never instantiated in a design this crate otherwise
        // fully supports.
        if m.kind() != SymbolKind::ProceduralBlock {
            continue;
        }
        let full_body = m.body().ok_or_else(|| {
            LoweringError::unsupported_at("procedural block has no body statement", &m)
        })?;
        // An error slang suppressed inside a statically dead `if`/`case` arm
        // leaves the whole body `Invalid`; lower the real (live-arm) body.
        let full_body = sv_sim_sim::process::cfg::unwrap_invalid(full_body);

        if is_procedural_instance_assertion(&m, &procedural_instances) {
            // A deferred one runs at the instantiation point, inline in the
            // procedure that reaches it; the same restrictions apply.
            if static_assertion_statement(full_body).is_none() {
                reject_unsupported_in_body_with(&m, full_body, true)?;
            }
            continue;
        }

        // XC-007: reject any concurrent/immediate assertion
        // anywhere in the block's body -- including at the very root (a
        // standalone module-level `assert property (...)` elaborates as its
        // own `ProceduralBlock` member whose body IS the assertion
        // statement, per LRM 1800-2023 -- `reject_unsupported_in_body`
        // checks the root node itself, not just its descendants, so this
        // case is caught without needing a separate special case here).
        // The static form of a concurrent assertion (16.14: a module-level
        // `assert property`, which slang elaborates as `always assert
        // property`) is the one place an assertion statement is accepted
        // here. Its 16.6 leaf restrictions still apply, and so do the
        // action blocks' own (16.14.1: no assertion statement in one).
        if m.procedural_block_procedure_kind() == ProceduralBlockKind::Always
            && let Some(stmt) = static_assertion_statement(full_body)
        {
            validate_assertion_leaves(&m, stmt)?;
            for action in [stmt.assertion_if_true(), stmt.assertion_if_false()]
                .into_iter()
                .flatten()
            {
                reject_unsupported_in_body(&m, action)?;
            }
            out.push(DiscoveredProcess {
                sym: m,
                kind: SliceProcKind::StaticAssertion,
                clock: None,
                reset: None,
                read_set: Vec::new(),
                assertion: Some(crate::sva::proc::HostedAssertion {
                    stmt,
                    procedural: false,
                    instance: None,
                }),
            });
            continue;
        }
        // 16.14.6: an assertion statement nested in the block is hosted by an
        // entry of its own, listed right after the block.
        let nested = collect_nested_assertions(&m, full_body, virtual_tasks)?;
        reject_unsupported_in_body_with(&m, full_body, true)?;

        // 16.4.3: a static deferred assertion "is treated as if it were
        // contained in an always_comb procedure".
        let kind = if is_static_deferred_assertion(&m) {
            SliceProcKind::AlwaysComb
        } else {
            classify_procedure_kind(&m, m.procedural_block_procedure_kind())?
        };
        let mut clock = None;
        let mut reset = None;
        let mut read_set = Vec::new();
        match kind {
            SliceProcKind::Initial | SliceProcKind::Final => {}
            SliceProcKind::StaticAssertion => {
                unreachable!("classify_procedure_kind never yields StaticAssertion")
            }
            SliceProcKind::Always => {
                if is_implicit_or_delay_always_head(full_body) || body_suspends_inside(full_body) {
                    // R-run Task 9 (NL-047/NL-048, `docs/superpowers/plans/
                    // 2026-09-27-run-wiring.md`): a plain `always #delay
                    // ...;` (`TimingControlKind::Delay`) or `always @*`/
                    // `always @(*)` (`TimingControlKind::ImplicitEvent`)
                    // head -- previously rejected right here, before the
                    // body ever reached `process::cfg`, by
                    // `require_single_edge_head`'s own "not a single
                    // posedge/negedge signal-event control" check. Neither
                    // shape names a single clock signal, so `clock` stays
                    // `None` (the same default `Initial`/`Final` already
                    // use), and `read_set` deliberately stays empty too --
                    // NOT populated via `comb_sensitivity` the way
                    // `AlwaysComb`/`AlwaysLatch` are, despite this being the
                    // "implicit sensitivity" idiom in the LRM sense.
                    // `process::cfg`'s own `SuspendPoint::ImplicitComb`
                    // (Task 6/CG-081) already derives its own read-set
                    // directly from the body's AST at CFG-build time,
                    // independent of this field; feeding the SAME read-set
                    // into `sv-sim-bin::run::build_static_sensitivity` as
                    // well would install a SECOND, external re-trigger path
                    // alongside `Always`'s own internal per-iteration
                    // suspend/resume dynamic subscription for the identical
                    // signals -- a real double-dispatch risk this
                    // `module.rs`-only task does not take on. For the
                    // `Delay` head specifically, reusing the RHS's read-set
                    // as a wake condition would be outright WRONG, not
                    // merely redundant: `always #5 clk = ~clk;`'s own
                    // re-trigger is time-driven (`SuspendPoint::Delay`,
                    // already-general non-zero-delay machinery), never
                    // driven by `clk`'s own value changing.
                } else {
                    clock = Some(require_single_edge_head(&m, "always", full_body)?);
                }
            }
            SliceProcKind::AlwaysFF => {
                // LRM 17.5's checker `always_ff` heads are any event control
                // (`@(e1)`, `@(rst or e3)`, `@(e2 or e3)`, whose entries are
                // event formals, bare signals or edges): no clock/reset pair,
                // the process's own `EdgeList` wait wakes it on each entry, so
                // `clock` stays `None` like a plain `always @(a or b)`'s.
                //
                // So is a head with an `@$global_clock` entry (14.14), in a module too:
                // `always_ff @($global_clock or posedge rst)`. The global clocking's
                // event is not one signal (it is resolved against the clocking
                // declaration in scope, `process::cfg`), so no clock is recorded and
                // the wait wakes the process on each entry alike.
                if full_body.kind() == StatementKind::Timed
                    && (sv_sim_sim::sva::sampled::is_checker_always_ff(&m)
                        || full_body
                            .timing_control()
                            .is_some_and(sv_sim_sim::sva::sampled::mentions_global_clock_event))
                    && !is_clock_reset_idiom_head(full_body)
                {
                    // nothing to record
                } else if full_body
                    .timing_control()
                    .is_some_and(has_value_change_entry)
                    || is_wide_edge_list_head(full_body)
                {
                    // LRM 9.2.2.4.1: an `always_ff` event control may list any number
                    // of edge events (`@(posedge clk or negedge rst1 or negedge
                    // rst2)`); only the one-clock + one-async-reset shape has the
                    // `(clock, reset)` roles to identify, so a longer list is handled
                    // like the any-change head just below: no clock is recorded and
                    // the process's own `EdgeList` wait wakes it on each entry.
                    // LRM 9.4.2 / 9.2.2.4: an event control entry with no edge
                    // (`@(clk)`, `@(posedge clk or !rst)`) fires on any value change
                    // of its expression. Synthesis wants every `always_ff` entry
                    // edge-qualified (a tool warning, not an error), so the head is
                    // no clock/reset pair: like a checker's, the process's own
                    // `EdgeList` wait wakes it on each entry and no clock is recorded.
                } else {
                    let in_checker = sv_sim_sim::sva::sampled::is_checker_always_ff(&m);
                    let (clk, rst) = require_clock_and_optional_reset(&m, full_body, in_checker)?;
                    clock = Some(clk);
                    reset = rst;
                }
            }
            SliceProcKind::AlwaysComb | SliceProcKind::AlwaysLatch => {
                read_set = comb_sensitivity
                    .read_set_of(&m.uid(), ordinal)
                    .map(<[_]>::to_vec)
                    .ok_or_else(|| {
                        LoweringError::unsupported_at(
                            "no precomputed read-set entry for this always_comb/always_latch \
                             block -- `build_comb_sensitivity_index` must be called over the \
                             WHOLE design (including this block's own instance) before \
                             `discover_processes` runs",
                            &m,
                        )
                    })?;
                // The analysis does not count an assertion statement's reads, but
                // the procedure evaluates its `const'(...)` casts (16.14.6.2).
                let locals = block_locals(&m);
                for h in &nested {
                    for sym in crate::sva::proc::const_cast_reads(h.stmt) {
                        let id = sym.uid();
                        if !locals.contains(&id) && !read_set.contains(&id) {
                            read_set.push(id);
                        }
                    }
                }
            }
        };
        out.push(DiscoveredProcess {
            sym: m,
            kind,
            clock,
            reset,
            read_set,
            assertion: None,
        });
        for hosted in nested {
            out.push(DiscoveredProcess {
                sym: m,
                kind: SliceProcKind::StaticAssertion,
                clock: None,
                reset: None,
                read_set: Vec::new(),
                assertion: Some(hosted),
            });
        }
    }
    Ok(out)
}

/// Every concurrent assertion statement nested in `root`, the body of the
/// procedural block `m`, in source order. The 16.6 leaf restrictions apply, and
/// so does 16.14.1's: no assertion statement in an action block.
fn collect_nested_assertions<'d>(
    m: &Symbol<'d>,
    root: Statement<'d>,
    virtual_tasks: Option<&sv_sim_sim::process::cfg::VirtualTasks<'d>>,
) -> Result<Vec<crate::sva::proc::HostedAssertion<'d>>, LoweringError> {
    let mut out: Vec<crate::sva::proc::HostedAssertion<'d>> = Vec::new();
    let mut stack = vec![(root.as_sem_node(), false)];
    // The user tasks already walked: a task's body is inlined into every process
    // that calls it, so an `expect` (16.17) in one is hosted for each caller.
    let mut visited = std::collections::HashSet::new();
    while let Some((node, in_task)) = stack.pop() {
        if let Some(e) = node.as_expression()
            && e.kind() == sv_lang::kinds::ExpressionKind::Call
            && e.is_system_call() != Some(true)
        {
            // An interface `extern` call reaches every implementation.
            for callee in sv_sim_sim::netlist::itf::call_callees(&e) {
                if callee.subroutine_flags().contains(MethodFlags::DPI_IMPORT) {
                    continue;
                }
                if let Some(body) = sv_sim_sim::process::cfg::proc_body(&callee)
                    && visited.insert(callee.uid())
                {
                    stack.push((body.as_sem_node(), true));
                }
                // 8.20: a call through a base handle runs the dynamic class's
                // override, which the call's static callee does not name.
                if let Some(vt) = virtual_tasks
                    && callee.subroutine_this_var().is_some()
                    && (callee.subroutine_flags().contains(MethodFlags::VIRTUAL)
                        || callee.subroutine_override().is_some())
                {
                    for (_, imp) in vt.implementations(&callee) {
                        if let Some(body) = sv_sim_sim::process::cfg::proc_body(&imp)
                            && visited.insert(imp.uid())
                        {
                            stack.push((body.as_sem_node(), true));
                        }
                    }
                }
            }
        }
        if let Some(stmt) = node.as_statement()
            && stmt.kind() == StatementKind::ConcurrentAssertion
            // Only an `expect` is hosted from a subroutine: any other assertion
            // statement there stays unsupported.
            && (!in_task || stmt.assertion_kind() == Some(sv_lang::AssertionKind::Expect))
        {
            if out
                .iter()
                .any(|h| h.stmt.source_range().start == stmt.source_range().start)
            {
                continue;
            }
            validate_assertion_leaves(m, stmt)?;
            for action in [stmt.assertion_if_true(), stmt.assertion_if_false()]
                .into_iter()
                .flatten()
            {
                reject_unsupported_in_body(m, action)?;
            }
            out.push(crate::sva::proc::HostedAssertion {
                stmt,
                procedural: true,
                instance: None,
            });
            continue;
        }
        // 17.3: reaching a procedural checker instantiation queues the
        // instance's static concurrent assertions like procedural ones (16.14.6).
        if let Some(stmt) = node.as_statement()
            && stmt.kind() == StatementKind::ProceduralChecker
        {
            for instance in stmt.procedural_checker_instances() {
                if instance.kind() != SymbolKind::CheckerInstance {
                    return Err(LoweringError::unsupported_at(
                        "an array of procedural checker instances: the grammar has no such \
                         construct (17.3 instantiates one checker per statement), so this is \
                         an internal error",
                        m,
                    ));
                }
                for block in sv_sim_sim::netlist::module_items(&instance) {
                    let Some(assertion) = static_concurrent_assertion_of(&block) else {
                        continue;
                    };
                    validate_assertion_leaves(&block, assertion)?;
                    for action in [
                        assertion.assertion_if_true(),
                        assertion.assertion_if_false(),
                    ]
                    .into_iter()
                    .flatten()
                    {
                        reject_unsupported_in_body(&block, action)?;
                    }
                    out.push(crate::sva::proc::HostedAssertion {
                        stmt: assertion,
                        procedural: true,
                        instance: Some(instance),
                    });
                }
            }
            continue;
        }
        // A statement inside a statically dead `if`/`case` arm slang could not
        // bind arrives wrapped in `Invalid`; walk the live node it holds.
        let mut kids = sv_sim_sim::process::cfg::live_children(&node);
        kids.reverse();
        stack.extend(kids.into_iter().map(|k| (k, in_task)));
    }
    Ok(out)
}

/// The assertion statement of `block` when it is a static concurrent assertion
/// (`assert property (...)` written in a module or checker body, which slang
/// elaborates as an `always` block holding it).
pub fn static_concurrent_assertion_of<'d>(block: &Symbol<'d>) -> Option<Statement<'d>> {
    if block.kind() != SymbolKind::ProceduralBlock
        || block.procedural_block_procedure_kind() != ProceduralBlockKind::Always
    {
        return None;
    }
    static_assertion_statement(sv_sim_sim::process::cfg::proc_body(block)?)
}

/// The procedural checker instance (17.3) whose body holds `block`, if `block`
/// is a static assertion of one of `procedural_instances` (concurrent, or the
/// deferred immediate assertions of 16.4.3): those are queued where the
/// instantiation is reached, so no process of their own runs them.
fn is_procedural_instance_assertion(
    block: &Symbol<'_>,
    procedural_instances: &HashSet<SymbolId>,
) -> bool {
    if procedural_instances.is_empty()
        || !(static_concurrent_assertion_of(block).is_some() || is_static_deferred_assertion(block))
    {
        return false;
    }
    let mut scope = block.parent();
    while let Some(s) = scope {
        if s.kind() == SymbolKind::CheckerInstanceBody {
            return s
                .checker_instance_body_parent_instance()
                .is_some_and(|i| procedural_instances.contains(&i.uid()));
        }
        scope = s.parent();
    }
    false
}

/// One ordinary (non-DPI) `function`/`task` subroutine, discovered by
/// [`discover_subroutines`] -- R-run Task 10 (CG-061 reused, CG-042
/// deliberately untouched, `docs/superpowers/plans/2026-09-27-run-wiring.md`).
/// `sym` is the `SymbolKind::Subroutine` member itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiscoveredSubroutine<'d> {
    pub sym: Symbol<'d>,
}

/// Walks `module_body`'s direct members for a `SymbolKind::Subroutine` that
/// is NOT a DPI import (`Symbol::subroutine_flags()` excludes
/// `MethodFlags::DPI_IMPORT` -- DPI marshaling/invocation is wave-B-
/// runtime's own scope, not this discovery function's; see `func.rs`'s/
/// `expr.rs`'s own generalized `Call`-arm doc comments for the full
/// CG-154/DPI-import split). Mirrors [`discover_processes`]'s own "walk
/// direct members, classify, collect" shape; UNLIKE that function, a
/// subroutine member this crate cannot actually LOWER (e.g. a `real`-typed
/// argument, a suspend point inside a task body, CG-154) is NOT rejected
/// here -- discovery only enumerates candidates. `pipeline::build_pipeline`'s
/// own subroutine pre-pass is what actually lowers each one and surfaces a
/// named [`LoweringError`] if one doesn't fit this crate's still-narrower
/// lowering scope, exactly mirroring how a still-unsupported `always`/
/// `always_ff` head is caught downstream of THIS function elsewhere in this
/// same file, not by discovery itself.
pub fn discover_subroutines<'d>(module_body: &Symbol<'d>) -> Vec<DiscoveredSubroutine<'d>> {
    sv_sim_sim::netlist::module_items(module_body)
        .into_iter()
        .filter(|m| m.kind() == SymbolKind::Subroutine)
        .filter(|m| !m.subroutine_flags().contains(MethodFlags::DPI_IMPORT))
        .map(|sym| DiscoveredSubroutine { sym })
        .collect()
}

/// R-run Task 10 review fix (r1): using [`discover_subroutines`]'s blanket
/// "every non-DPI subroutine declared in this module body" enumeration to
/// decide what `sv-sim run` actually LOWERS made a merely-unused
/// function/task fail the whole run if its shape happened to be outside
/// this crate's still-narrower lowering scope (e.g. a `real`-typed
/// argument, CG-037; a task body containing `#delay`/`wait`, CG-154) --
/// iverilog runs the identical design fine, since dead code was never its
/// problem either. R-run Task 10's own stated scope (`docs/superpowers/
/// plans/2026-09-27-run-wiring.md`, Task 10, "Files") is explicitly
/// reachability-based: "discover and lower every non-DPI subroutine the
/// design's processes CALL" -- this function realizes that literally,
/// [`discover_subroutines`] does not.
///
/// Walks every `ExpressionKind::Call` node reachable from `roots` (each
/// discovered process's own body / each continuous assign's own RHS
/// expression, as [`SemNode`]s), resolves each call's callee via
/// `Expression::call_subroutine()` (`None` for a system call -- silently
/// skipped: never a user subroutine, never has a body to recurse into),
/// and -- for a non-DPI callee not already collected -- recurses into
/// THAT callee's own body too, so a function called only indirectly (one
/// user function calling another) is still found. A DPI import callee is
/// skipped exactly the way [`discover_subroutines`] already skips one
/// outright (its own invocation is wave-B runtime's concern, not this
/// lowering pipeline's). Dedup is by [`SymbolId`] (`seen`), both to
/// terminate on a recursive/mutually-recursive call cycle and to avoid
/// walking (and later double-lowering) a subroutine reached from two
/// different call sites.
///
/// An unreferenced function/task -- of any shape, supported or not -- is
/// therefore never visited at all here: never discovered, never lowered,
/// never rejected by this pipeline, exactly the pre-Task-10 behavior
/// (`run_design` never touched subroutine bodies at all). Only a call
/// site actually reachable from a live process/continuous-assign can
/// surface `func::lower_function`'s own named errors (CG-037/CG-154/etc.).
///
/// Classes plan Task 7 addendum: a callee whose own enclosing scope is a
/// class (a user method, or a `std`-package intrinsic's) is excluded from
/// the returned list -- `pipeline::build_pipeline`'s own class-aware
/// sub-pass (or, for a `std` intrinsic, Tasks 13/16/17/18's dedicated
/// dispatch) already owns declaring/lowering it with the right ABI shape;
/// this function's own plain, receiver-less `func::lower_function` path
/// would give it the wrong one. Its body is still walked (the `stack.push`
/// below) so an ORDINARY subroutine it in turn calls is still discovered.
pub fn discover_called_subroutines<'d>(
    roots: impl IntoIterator<Item = SemNode<'d>>,
) -> Vec<DiscoveredSubroutine<'d>> {
    discover_called_subroutines_seen(roots, &mut HashSet::new())
}

/// [`discover_called_subroutines`] with a caller-owned `seen` set, shared
/// across calls: a callee already in `seen` is neither returned nor walked
/// again (the call that inserted it returned its transitive callees).
/// Calling it once per root with one set returns, concatenated, the
/// first-occurrence order of the per-root calls with their duplicates
/// dropped, but walks each reachable body once instead of once per root (the
/// per-root form is quadratic over thousands of class methods).
pub fn discover_called_subroutines_seen<'d>(
    roots: impl IntoIterator<Item = SemNode<'d>>,
    seen: &mut HashSet<SymbolId>,
) -> Vec<DiscoveredSubroutine<'d>> {
    discover_called_subroutines_inlined(roots, seen).0
}

/// [`discover_called_subroutines_seen`], also returning the called tasks that
/// can suspend: those are inlined into each calling process
/// (`process::cfg`), so they are never lowered as functions and are absent
/// from the first list.
pub fn discover_called_subroutines_inlined<'d>(
    roots: impl IntoIterator<Item = SemNode<'d>>,
    seen: &mut HashSet<SymbolId>,
) -> (Vec<DiscoveredSubroutine<'d>>, Vec<Symbol<'d>>) {
    let mut out = Vec::new();
    let mut inlined = Vec::new();
    let mut stack: Vec<SemNode<'d>> = roots.into_iter().collect();
    while let Some(node) = stack.pop() {
        // A call through a virtual interface reaches every candidate
        // instance's own subroutine (`crate::vif`), never the interface
        // type's generic one.
        let callees: Vec<Symbol<'d>> = match node.as_expression() {
            Some(expr) => match sv_sim_sim::netlist::vif::call_targets(&expr) {
                Some((_, targets)) => targets.into_iter().flatten().collect(),
                // An interface `extern` method: every module-side
                // implementation (LRM 25.7).
                None => sv_sim_sim::netlist::itf::call_callees(&expr),
            },
            None => Vec::new(),
        };
        for callee in callees {
            if callee.subroutine_flags().contains(MethodFlags::DPI_IMPORT)
                || !seen.insert(callee.uid())
            {
                continue;
            }
            // Classes plan Task 7 (found running `abstract_pure_virtual.sv`,
            // not in the preflight corrections): a class method (or
            // `std`-package intrinsic method) call reached from an
            // ordinary (non-class) subroutine's body -- e.g. a plain
            // `function show(shape s); s.area(); endfunction` calling a
            // class method -- must NOT be added to `out`. Class methods
            // are ALREADY declared/lowered by `pipeline::build_pipeline`'s
            // own, class-aware sub-pass, which gives them the receiver-
            // taking ABI shape this function's own ordinary, receiver-less
            // `func::lower_function` path has no concept of; a
            // `std`-package intrinsic has no SV body to lower via EITHER
            // path at all (§0/D2). Before this fix, a callee the class
            // sub-pass deliberately leaves undeclared (a still-pure `pure
            // virtual` prototype's own synthesized, body-less stub --
            // `classes::VtableLayout`'s own doc comment) got declared AND
            // lowered HERE instead, with the wrong (receiver-less)
            // signature and an empty, unterminated body -- confirmed
            // live, LLVM's own verifier: "Basic Block ... does not have
            // terminator!". The callee's own body is still walked below
            // (`stack.push`) so a NESTED, ordinary subroutine it calls is
            // still discovered -- only the callee itself, as a class
            // method, is excluded from `out`.
            // A covergroup's predefined methods (19.8) are runtime calls
            // (`crate::covergroup`), with no body either.
            let is_class_method = callee.parent().is_some_and(|p| {
                matches!(
                    p.kind(),
                    SymbolKind::ClassType
                        | SymbolKind::GenericClassDef
                        | SymbolKind::CovergroupBody
                        | SymbolKind::Coverpoint
                        | SymbolKind::CoverCross
                )
            });
            // A task that can suspend is inlined into each calling process
            // (`process::cfg`), never compiled as a function -- but the
            // subroutines IT calls still are.
            if !is_class_method {
                if sv_sim_sim::process::cfg::subroutine_can_suspend(&callee) {
                    inlined.push(callee);
                } else {
                    out.push(DiscoveredSubroutine { sym: callee });
                }
            }
            if let Some(body) = sv_sim_sim::process::cfg::proc_body(&callee) {
                stack.push(body.as_sem_node());
            }
            // A local's initializer (`int x = f();`) runs with the call but is
            // no child of its body: its callees are reached from here.
            for m in callee.members() {
                if m.kind() == SymbolKind::Variable
                    && let Some(init) = m.initializer()
                {
                    stack.push(init.as_sem_node());
                }
            }
        }
        // Unconditional (not an `else`): a call node's own operand
        // (argument) expressions can themselves contain further calls even
        // when the outer callee itself was a DPI import or already seen.
        // `live_children`: a call in the live arm of a dead-branch `Invalid`
        // statement must still be discovered.
        stack.extend(sv_sim_sim::process::cfg::live_children(&node));
    }
    (out, inlined)
}

/// One accepted continuous assign (`assign target = rhs;`), discovered by
/// [`discover_cont_assigns`] (R-run Task 2, NL-034,
/// `docs/superpowers/plans/2026-09-27-run-wiring.md`): `sym` is the
/// `SymbolKind::ContinuousAssign` member itself (cited in every
/// [`LoweringError`] this discovery function returns), `target` is the LHS's
/// resolved plain-identifier symbol, and `assign_expr` is the whole bound
/// `y = a + 1`-shaped `Assignment` expression
/// (`Symbol::continuous_assign_assignment`).
///
/// **There is no `Statement` wrapping `assign_expr` at all** -- verified
/// empirically against real `sv-lang`=0.1.9 output: `Symbol::body()` returns
/// `None` for a `ContinuousAssign` symbol (only a `ProceduralBlock`/
/// subroutine symbol has one), and `Expression::as_sem_node().as_statement()`
/// is also `None`. This is why this is a distinct discovery type from
/// [`DiscoveredProcess`] rather than a `SliceProcKind` variant sharing its
/// shape: `sv-sim-codegen::process_lower::lower_cont_assign_kernel_fn` lowers
/// `assign_expr` directly via `expr::lower_expr`, never through
/// `process::cfg::build_cfg`/`Segment` (which need a real `Statement` this
/// symbol never has -- `process::cfg`'s CFG/segment machinery is built for
/// general statement sequences with suspend points, which a continuous
/// assign's body, by LRM construction, never has: it is always exactly one
/// blocking assignment expression that can never suspend and never declares
/// a frame-local).
///
/// `read_set` is the RHS's whole-expression static read-set -- the SAME
/// `AnalyzedProcedure::read_set()` mechanism CG-079 already uses for
/// `always_comb`/`always_latch`, now also covering
/// `SymbolKind::ContinuousAssign` (see [`CombSensitivityIndex`]'s own doc
/// comment).
// Deliberately not `PartialEq`/`Eq` (unlike `DiscoveredProcess`): `sv_lang::
// Expression` (the `assign_expr` field's type) implements neither.
#[derive(Debug, Clone)]
pub struct DiscoveredContAssign<'d> {
    pub sym: Symbol<'d>,
    /// For an `assign`: its whole `Assignment` expression (any target shape
    /// -- a name, a select, a concatenation). For a net declaration
    /// assignment (`wire w = rhs;`, `net_target: Some(w)`): the RHS only.
    pub assign_expr: Expression<'d>,
    /// The net a net-declaration assignment drives; `None` for an `assign`.
    pub net_target: Option<Symbol<'d>>,
    pub read_set: Vec<SymbolId>,
    /// Its delay (`assign #d ...`, `wire #d w = ...`), if any: the caller
    /// routes the kernel's write through a delay line.
    pub delay: Option<sv_lang::SemNode<'d>>,
}

/// `module_body`'s variables whose initializer is not a constant
/// (`int z = y + 1;`, `int x = f(3);`, `C h = new;`; LRM 6.8): the layout
/// already folds a constant one into the variable's starting value, so these
/// are the ones it silently dropped. Each is returned as a
/// [`DiscoveredContAssign`] (`net_target: Some(var)`, `assign_expr` the
/// initializer) in declaration order, for the caller to run as a one-shot
/// time-zero kernel (`ContAssignLoweringSpec::var_init`).
///
/// Integral, real, string, class-handle and fixed-size unpacked array variables: a queue
/// or other collection initializer (`int q[$] = f();`) is not covered and
/// stays unexecuted, as it was before.
pub fn discover_variable_initializers<'d>(
    module_body: &Symbol<'d>,
) -> Vec<DiscoveredContAssign<'d>> {
    let mut out = Vec::new();
    // A static variable declared in a process's own block
    // (`initial begin static C c = new; ... end`) or in a task/function
    // (`function C mk(); static C c = new; ...`) is initialized the same way:
    // once, before time zero (LRM 1800-2023 6.21, 6.8) -- not on the first
    // call (`func.rs` skips a static local, which is a state slot).
    let block_statics = sv_sim_sim::netlist::static_procedural_vars(module_body);
    for m in sv_sim_sim::netlist::module_items(module_body)
        .into_iter()
        .chain(block_statics)
    {
        if m.kind() != SymbolKind::Variable {
            continue;
        }
        let Some(init) = sv_sim_sim::netlist::variable_initializer(&m) else {
            continue;
        };
        let Some(ty) = m.value_type() else {
            continue;
        };
        // A constant tagged union (or aggregate of one) has no encoded
        // form the state layout can read (`ConstantValue::Union` is only a
        // string): its slot starts undefined and this assignment, run once
        // before time zero, gives it its value.
        // An event's `= null` is a constant too, yet the layout has no starting
        // value for it (the variable begins as a new object), so the kernel
        // must break that association (LRM 6.17).
        if init.constant_value().is_some()
            && !sv_sim_sim::state::storage::contains_tagged_union(&ty)
            && !ty.is_event()
        {
            continue;
        }
        if sv_sim_sim::state::storage::is_collection(&ty) {
            continue;
        }
        // A fixed-size unpacked array is initialized element-wise by the
        // kernel (`assign_array_into_fresh`), except an array of virtual
        // interfaces, whose layout resolves its instances itself.
        if crate::arrays::array_shape(&ty).is_some_and(|s| s.elem.is_virtual_interface()) {
            continue;
        }
        out.push(DiscoveredContAssign {
            sym: m,
            assign_expr: init,
            net_target: Some(m),
            read_set: Vec::new(),
            delay: None,
        });
    }
    out
}

/// Walks `module_body`'s direct members for every `SymbolKind::
/// ContinuousAssign` and classifies it into a [`DiscoveredContAssign`] or a
/// named [`LoweringError`] -- NEVER a silent skip (this module's own
/// top-of-file discipline), mirroring [`discover_processes`]'s own shape.
///
/// A delayed one (`assign #d ...;`) carries its delay
/// ([`DiscoveredContAssign::delay`]).
pub fn discover_cont_assigns<'d>(
    module_body: &Symbol<'d>,
) -> Result<Vec<DiscoveredContAssign<'d>>, LoweringError> {
    let mut out = Vec::new();
    for m in sv_sim_sim::netlist::module_items(module_body) {
        // `wire [7:0] w = a + 1;` is an implicit continuous assignment of
        // the net's initializer (LRM 1800-2023 §10.3.1).
        if m.kind() == SymbolKind::Net
            && let Some(rhs) = m.initializer()
        {
            out.push(DiscoveredContAssign {
                sym: m,
                assign_expr: rhs,
                net_target: Some(m),
                read_set: cont_assign_read_set(rhs),
                delay: m.net_delay(),
            });
            continue;
        }
        if m.kind() != SymbolKind::ContinuousAssign {
            continue;
        }
        let assign_expr = m.continuous_assign_assignment().ok_or_else(|| {
            LoweringError::unsupported_at(
                "ContinuousAssign symbol has no bound assignment expression (unexpected AST \
                 shape)",
                &m,
            )
        })?;
        if assign_expr.kind() != ExpressionKind::Assignment {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "ContinuousAssign symbol's bound expression is `{:?}`, not `Assignment` \
                     (unexpected AST shape)",
                    assign_expr.kind()
                ),
                &m,
            ));
        }
        if assign_expr.is_nonblocking() == Some(true) {
            return Err(LoweringError::unsupported_at(
                "nonblocking (`<=`) continuous assign is not legal SystemVerilog (unexpected \
                 AST shape)",
                &m,
            ));
        }
        if assign_expr.left().is_none() {
            return Err(LoweringError::unsupported_at(
                "continuous assign missing lvalue",
                &m,
            ));
        }
        // Computed from this assign's own bound expression: every unnamed
        // `assign` in a scope shares its scope's hierarchical path (its
        // `SymbolId`), so a path-keyed lookup would hand every assign in the
        // module the same read-set.
        let read_set = cont_assign_read_set(assign_expr);
        out.push(DiscoveredContAssign {
            sym: m,
            assign_expr,
            net_target: None,
            read_set,
            delay: m.continuous_assign_delay(),
        });
    }
    Ok(out)
}

/// Design-wide index of every `always_comb`/`always_latch` procedural
/// block's AND every plain `assign` (`SymbolKind::ContinuousAssign`)
/// statement's whole-procedure read set (CG-079's synthesized implicit
/// sensitivity list: `sched::StaticSensitivity{edges: vec![(cell, None);
/// ..]}` per entry, `edge: None` meaning "any change"), built ONCE via
/// `Design::analyze(AnalysisFlags::NONE, _).procedures(scope).read_set()`
/// (`docs/design/process.md` §1's own specified mechanism) over every
/// `InstanceBody` scope in the design, keyed by each block's own stable
/// [`SymbolId`] -- never a `Symbol<'d>` directly: `Analysis::procedures`'s
/// own borrow is scoped to the local `Analysis` value
/// [`build_comb_sensitivity_index`]'s `design.analyze(..)` call constructs,
/// strictly shorter-lived than the `'d` this index must survive past (see
/// that function's own doc comment for why). `discover_processes`/
/// [`discover_cont_assigns`] never re-derive this by hand-walking a body's
/// expressions a second time.
///
/// R-run Task 2 (NL-034, `docs/superpowers/plans/2026-09-27-run-wiring.md`):
/// extended to also cover `SymbolKind::ContinuousAssign` -- `Analysis::
/// procedures`'s own doc comment already lists "continuous assignments"
/// among what it analyzes (verified directly: `AnalyzedProcedure::
/// read_set()` works identically for one), so this reuses the EXACT SAME
/// mechanism CG-079 already established for `always_comb`/`always_latch`,
/// never a second, independently-derived read-set computation.
///
/// Keyed by `(Symbol::id(), ordinal)` -- the block's position among its
/// scope's `members()` -- because an UNNAMED block's `SymbolId` is just its
/// enclosing scope's hierarchical path, shared by every unnamed block in
/// that scope.
#[derive(Debug, Clone, Default)]
pub struct CombSensitivityIndex(HashMap<(SymbolId, usize), Vec<SymbolId>>);

impl CombSensitivityIndex {
    /// The whole-procedure read set for the `always_comb`/`always_latch`
    /// block whose own [`Symbol::id`] is `block_id` and which is member
    /// number `ordinal` of its scope, if this index covers it (it always does
    /// for any such block reachable from the `Design` it was built over).
    pub fn read_set_of(&self, block_id: &SymbolId, ordinal: usize) -> Option<&[SymbolId]> {
        self.0.get(&(block_id.clone(), ordinal)).map(Vec::as_slice)
    }
}

/// Task 14: the read-set of a bound continuous-assign expression (`y = a +
/// 1`-shaped, always `ExpressionKind::Assignment` per [`discover_cont_assigns`]'s
/// own validation -- this function does not re-validate that shape, it is
/// only ever called from [`build_comb_sensitivity_index`] on a real
/// `Symbol::continuous_assign_assignment()`) -- every `NamedValue` symbol
/// reachable anywhere in the tree EXCEPT a (top-level or nested)
/// `Assignment` node's own LHS, mirroring `process_lower::
/// external_refs_in_expr`'s identical `order`-vs-`written` distinction (that
/// function's own `signals`-membership/`is_memory_signal` filters do not
/// apply here -- this runs PRE-elaboration, over the raw `sv_lang::Design`,
/// before any `SignalSlot`/`InstanceId` map exists; every symbol found here
/// is later re-validated against the CALLING instance's own resolved
/// signals by `run.rs::signal_slots_of`/`build_static_sensitivity`, so an
/// over-broad read-set here would surface as a named `LoweringError` there,
/// never a silent wrong answer).
/// Pushes the expressions an lvalue READS to find its target (select indices
/// and bounds) but not the target's base name (LRM 10.3, 11.5.1).
fn push_lvalue_index_reads<'d>(lhs: Expression<'d>, stack: &mut Vec<SemNode<'d>>) {
    let kind = lhs.kind();
    if kind == ExpressionKind::ElementSelect || kind == ExpressionKind::RangeSelect {
        for x in [lhs.selector(), lhs.range_left(), lhs.range_right()]
            .into_iter()
            .flatten()
        {
            stack.push(x.as_sem_node());
        }
        if let Some(b) = lhs.select_value() {
            push_lvalue_index_reads(b, stack);
        }
    } else if kind == ExpressionKind::MemberAccess {
        if let Some(o) = lhs.operand() {
            push_lvalue_index_reads(o, stack);
        }
    } else if kind == ExpressionKind::Concatenation {
        for o in lhs.operands() {
            push_lvalue_index_reads(o, stack);
        }
    } else if !sv_sim_sim::symid::is_value_name(kind) {
        // A bare name is the target itself; any other shape is read whole.
        stack.push(lhs.as_sem_node());
    }
}

pub fn cont_assign_read_set(assign_expr: Expression<'_>) -> Vec<SymbolId> {
    let mut order: Vec<SymbolId> = Vec::new();
    let mut seen: HashSet<SymbolId> = HashSet::new();
    let mut written: HashSet<SymbolId> = HashSet::new();
    let mut stack = vec![assign_expr.as_sem_node()];
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression() {
            if sv_sim_sim::symid::is_value_name(e.kind())
                && let Some(sym) = e.referenced_symbol()
                // Constants (parameters, a generate loop's genvar) are
                // never sensitivity sources. A modport port (`bus.lhs`
                // through a `bus_if.consumer bus` port) is one more name for
                // its interface instance's own member (LRM 25.5), so it is a
                // source too; its foreign slot is keyed by the port symbol.
                && matches!(
                    sym.kind(),
                    SymbolKind::Variable | SymbolKind::Net | SymbolKind::ModportPort
                )
                && seen.insert(sym.uid())
            {
                order.push(sym.uid());
            }
            if e.kind() == ExpressionKind::Assignment
                && e.is_nonblocking() != Some(true)
                && let Some(lhs) = e.left()
                && sv_sim_sim::symid::is_value_name(lhs.kind())
                && let Some(sym) = lhs.referenced_symbol()
                // A NET's driver reads the resolved net, which other drivers
                // also change (LRM 10.3, 28.12: a keeper `assign (pull0,
                // pull1) q = q;` must re-evaluate on q's own resolution,
                // ivtest pr509b); only a variable's own write is not
                // re-observed.
                && sym.kind() != SymbolKind::Net
            {
                written.insert(sym.uid());
            }
            // What a called function reads from the module (10.3).
            for id in crate::func::callee_reads(&e) {
                if seen.insert(id.clone()) {
                    order.push(id);
                }
            }
        }
        if let Some(e) = n.as_expression()
            && e.kind() == ExpressionKind::Assignment
            && let (Some(lhs), Some(rhs)) = (e.left(), e.right())
        {
            if sv_sim_sim::symid::is_value_name(lhs.kind()) {
                if e.is_nonblocking() == Some(true) {
                    stack.extend(n.children());
                    continue;
                }
                // The whole target is written, not read: a net driver is
                // sensitive to its own net only through its RHS (the keeper
                // above); naming the LHS would re-run every constant driver
                // on each change of its net, e.g. a VPI strength put.
                stack.push(rhs.as_sem_node());
                continue;
            }
            // A driver of part of a net (`assign y[1] = y[0];`) is not
            // sensitive to the net it drives merely by naming it as the
            // select base (LRM 10.3: only the RHS and the select indices are
            // read); the base would make the driver its own sensitivity.
            stack.push(rhs.as_sem_node());
            push_lvalue_index_reads(lhs, &mut stack);
            continue;
        }
        stack.extend(n.children());
    }
    order
        .into_iter()
        .filter(|id| !written.contains(id))
        .collect()
}

/// Builds a [`CombSensitivityIndex`] over the WHOLE `design` in one pass.
///
/// **Call-order requirement (load-bearing, not stylistic):** this must run
/// before any other borrow of `design` that keeps it exclusively borrowed
/// for the rest of a pipeline run -- e.g. `sv-sim-bin::run::run_design`'s own
/// `design.eval_session()`. Calling this function AFTER that point does not
/// type-check there: `EvalSession`'s own lifetime parameter keeps `design`
/// exclusively borrowed for as long as anything derived from it (`Netlist`,
/// an instance's own `Symbol`) is still alive, which in that pipeline is the
/// rest of the run. This is why this index is owned, `SymbolId`-keyed data
/// rather than a live `Analysis`/`Symbol` handle: it is computed once, up
/// front, and outlives that later exclusive borrow entirely.
pub fn build_comb_sensitivity_index(
    design: &Design,
) -> Result<CombSensitivityIndex, LoweringError> {
    // The index only feeds `always_comb`/`always_latch` sensitivity lists
    // (LRM 9.2.2.2.1). A design with no such block gains nothing from the
    // analysis, and must not pay for it: slang's analysis pass also walks
    // every class method of every package, and on a large class library
    // (UVM) it asserts `!isFrozen()` in `BumpAllocator::allocate`: gdb shows
    // `SubroutineSymbol::getBody` binding the body of
    // `uvm_component_registry::create_component` for the first time
    // (`Statement::bindScopeInitializers` emplaces a `VariableDeclStatement`)
    // after the compilation is frozen. Reproduces with `uvm_pkg.sv` plus any
    // module holding one `always_comb`; recorded as an SV-LANG PEER REQUEST
    // (lane uvm5), so a UVM bench whose RTL has `always_comb` is refused here.
    let mut any_comb = false;
    design.root().visit(|sym| {
        if sym.kind() != SymbolKind::Instance {
            return Walk::Continue;
        }
        if let Some(scope) = sym.instance_body() {
            let in_body = sv_sim_sim::netlist::module_items(&scope)
                .iter()
                .any(has_comb_semantics);
            let in_checker = sv_sim_sim::netlist::checker_instances(&scope)
                .iter()
                .filter_map(sv_sim_sim::netlist::checker_instance_body)
                .any(|b| {
                    sv_sim_sim::netlist::module_items(&b)
                        .iter()
                        .any(has_comb_semantics)
                });
            any_comb |= in_body || in_checker;
        }
        Walk::Continue
    });
    if !any_comb {
        return Ok(CombSensitivityIndex(HashMap::new()));
    }
    let analysis = design
        .analyze(AnalysisFlags::NONE, 1)
        .map_err(|e| LoweringError::unsupported(&format!("analysis error: {e}"), "<design>"))?;
    let mut map: HashMap<(SymbolId, usize), Vec<SymbolId>> = HashMap::new();
    // Bodies whose combinational blocks the analysis covered, with each
    // block's ordinal and reads; and those it skipped.
    type BodyReads<'d> = (Symbol<'d>, Vec<(usize, Vec<Symbol<'d>>)>);
    let mut analyzed: Vec<BodyReads<'_>> = Vec::new();
    let mut skipped: Vec<Symbol<'_>> = Vec::new();
    design.root().visit(|sym| {
        // `Design::root().visit` recurses via `Symbol::members()`, which
        // walks straight through an `Instance` symbol into its own body's
        // members transparently -- it never yields a distinct
        // `SymbolKind::InstanceBody` node of its own (verified live: a
        // one-`always_comb` design's whole-tree visit reaches `Root`,
        // `CompilationUnit`, `Instance`, `Port`/`Net`/`Variable`,
        // `ProceduralBlock` -- never `InstanceBody`). `Analysis::procedures`
        // needs the actual instance-body `Symbol` as `scope` (its own doc
        // example: "`design.top_instances().next().unwrap().instance_body()
        // .unwrap()`"), so this walk keys off `SymbolKind::Instance` instead
        // and calls `instance_body()` to get it.
        if sym.kind() != SymbolKind::Instance {
            return Walk::Continue;
        }
        let Some(scope) = sym.instance_body() else {
            return Walk::Continue;
        };
        // The body's own procedures and its generate blocks' (whose
        // processes belong to the instance, `netlist::module_items`).
        let items = sv_sim_sim::netlist::module_items(&scope);
        // A checker instance's procedures run with the instance as well
        // (LRM 17.3, [`sv_sim_sim::netlist::checker_instances`]).
        let scopes = std::iter::once(scope)
            .chain(sv_sim_sim::netlist::generate_scopes(&scope))
            .chain(
                sv_sim_sim::netlist::checker_instances(&scope)
                    .iter()
                    .filter_map(sv_sim_sim::netlist::checker_instance_body)
                    .collect::<Vec<_>>(),
            );
        let mut body_reads = Vec::new();
        for proc in scopes.flat_map(|s| analysis.procedures(s)) {
            let psym = proc.symbol();
            // R-run Task 2 (NL-034): an `always`/`initial`/`final` block
            // gets a read-set entry only when it is `AlwaysComb`/
            // `AlwaysLatch`. `ContinuousAssign` is handled in the SEPARATE
            // walk below (R-run Task 14 fix, see its own doc comment for
            // why), not here -- deliberately dropped from this loop's own
            // membership test. Deliberately an `if`/`||`-shaped membership
            // test, not a `match` over `SymbolKind`: this is an accept-list
            // test, never an exhaustive classification, so it does not need
            // `xtask lint-unimplemented`'s Kind-typed-match guard.
            if !has_comb_semantics(&psym) {
                continue;
            }
            // Only storage wakes a process: a parameter the analysis also
            // lists (a generate loop's index inside its block) never
            // changes. Nor does a variable the block declares itself (a
            // `for (int i ...)` loop variable, a block-local temporary):
            // LRM 1800-2023 9.2.2.2.1 leaves those out of the implicit
            // sensitivity list.
            let locals = block_locals(&psym);
            let mut reads: Vec<Symbol<'_>> = proc
                .read_set()
                .map(|r| r.symbol())
                .filter(|s| matches!(s.kind(), SymbolKind::Variable | SymbolKind::Net))
                .filter(|s| !locals.contains(&s.uid()))
                .collect();
            // The analysis leaves out what the action block of an immediate
            // assertion reads (`assert #0 (c) else f(opcode);`), which is
            // part of the block's statements (LRM 9.2.2.2.1 takes every
            // expression the block reads; 16.4.2's own example depends on it).
            for sym in assertion_action_reads(&psym) {
                if !locals.contains(&sym.uid()) && !reads.contains(&sym) {
                    reads.push(sym);
                }
            }
            // The analysis hands the reads back in an unspecified order; the
            // order reaches the kernel's sensitivity list (and a design
            // image), so fix it.
            reads.sort_by_cached_key(|s| s.uid());
            let Some(ordinal) = items.iter().position(|m| *m == psym) else {
                continue;
            };
            map.insert(
                (psym.uid(), ordinal),
                reads.iter().map(|s| s.uid()).collect(),
            );
            body_reads.push((ordinal, reads));
        }
        let has_comb = items.iter().any(has_comb_semantics);
        if body_reads.is_empty() && has_comb {
            skipped.push(scope);
        } else if !body_reads.is_empty() {
            analyzed.push((scope, body_reads));
        }
        Walk::Continue
    });
    // The analysis visits one body of each structurally identical set of
    // instances (same definition and parameters): the others take their
    // blocks' reads from that twin, each read declared inside the twin
    // mapped to the same-placed symbol of their own body.
    for body in skipped {
        let Some((twin, reads)) = analyzed
            .iter()
            .find(|(t, _)| body.instance_body_has_same_type(t))
        else {
            continue;
        };
        let items = sv_sim_sim::netlist::module_items(&body);
        for (ordinal, twin_reads) in reads {
            let Some(psym) = items.get(*ordinal) else {
                continue;
            };
            let ids = twin_reads
                .iter()
                .map(|r| match member_path(r, twin) {
                    Some(path) => resolve_member_path(&body, &path).unwrap_or(*r).uid(),
                    None => r.uid(),
                })
                .collect();
            map.insert((psym.uid(), *ordinal), ids);
        }
    }
    Ok(CombSensitivityIndex(map))
}

/// The variables and nets named in the action blocks (pass and fail
/// statements) of the immediate assertions of procedure `proc`: reads the
/// analysis' read set misses, but that wake an `always_comb` (LRM 9.2.2.2.1).
/// Names only: what a function called from an action block reads is not
/// followed here.
fn assertion_action_reads<'d>(proc: &Symbol<'d>) -> Vec<Symbol<'d>> {
    let mut out: Vec<Symbol<'d>> = Vec::new();
    let Some(code) = sv_sim_sim::process::cfg::proc_body(proc) else {
        return out;
    };
    let mut stack = vec![code.as_sem_node()];
    let mut in_assertion = vec![false];
    while let Some(n) = stack.pop() {
        let inside = in_assertion.pop().unwrap_or(false);
        let is_assertion = n
            .as_statement()
            .is_some_and(|s| s.kind() == StatementKind::ImmediateAssertion);
        if inside
            && let Some(e) = n.as_expression()
            && sv_sim_sim::symid::is_value_name(e.kind())
            && let Some(sym) = e.referenced_symbol()
            && matches!(sym.kind(), SymbolKind::Variable | SymbolKind::Net)
            && !out.contains(&sym)
        {
            out.push(sym);
        }
        // An assignment's plain target is written, not read (a fail action
        // `flag = 1` must not make the block sensitive to `flag`).
        let target = n
            .as_expression()
            .filter(|e| e.kind() == ExpressionKind::Assignment)
            .and_then(|e| e.left())
            .filter(|l| sv_sim_sim::symid::is_value_name(l.kind()));
        let mut skipped = target.is_none();
        for c in sv_sim_sim::process::cfg::live_children(&n) {
            // The target is the assignment's first child.
            if !skipped {
                skipped = true;
                continue;
            }
            // The condition is the assertion's first expression child: what it
            // reads (the analysis already has it) is not an action read, and
            // a sampled-value clocking event inside it is not a sensitivity.
            if is_assertion && c.as_expression().is_some() {
                continue;
            }
            stack.push(c);
            in_assertion.push(inside || is_assertion);
        }
    }
    out
}

/// The position of `sym` under `body`: the index of each enclosing scope
/// (and finally of `sym`) among its parent's members, outermost first.
/// `None` when `sym` is not declared inside `body`.
pub(crate) fn member_path(sym: &Symbol<'_>, body: &Symbol<'_>) -> Option<Vec<usize>> {
    let mut path = Vec::new();
    let mut cur = *sym;
    loop {
        let parent = cur.parent()?;
        let index = parent.members().position(|m| m == cur)?;
        path.push(index);
        if parent == *body {
            path.reverse();
            return Some(path);
        }
        cur = parent;
    }
}

/// The symbol at `path` ([`member_path`]) under `body`.
pub(crate) fn resolve_member_path<'d>(body: &Symbol<'d>, path: &[usize]) -> Option<Symbol<'d>> {
    let mut cur = *body;
    for &index in path {
        let next = cur.members().nth(index)?;
        cur = next;
    }
    Some(cur)
}

/// The variables the blocks of procedure `proc` declare (block-local
/// temporaries and `for` loop variables, of either lifetime).
fn block_locals(proc: &Symbol<'_>) -> HashSet<SymbolId> {
    let mut out = HashSet::new();
    let Some(code) = sv_sim_sim::process::cfg::proc_body(proc) else {
        return out;
    };
    let mut stack = vec![code.as_sem_node()];
    while let Some(n) = stack.pop() {
        if let Some(s) = n.as_statement() {
            for block in sv_sim_sim::process::cfg::block_scopes(&s) {
                out.extend(
                    block
                        .members()
                        .filter(|v| v.kind() == SymbolKind::Variable)
                        .map(|v| v.uid()),
                );
            }
        }
        stack.extend(sv_sim_sim::process::cfg::live_children(&n));
    }
    out
}

/// The CG-069 exhaustive-match gate over `sv_lang::ProceduralBlockKind`: no
/// wildcard arm, so a future `sv-lang` bump that adds a 7th procedural-block
/// kind fails this crate's **compile**, not merely a test (see
/// [`assert_kind_counts_match_pinned_slang`]'s doc comment for why this
/// enum's guard takes this shape instead of a runtime `::COUNT` comparison).
fn classify_procedure_kind<'d>(
    _sym: &Symbol<'d>,
    kind: ProceduralBlockKind,
) -> Result<SliceProcKind, LoweringError> {
    match kind {
        ProceduralBlockKind::Initial => Ok(SliceProcKind::Initial),
        ProceduralBlockKind::Always => Ok(SliceProcKind::Always),
        ProceduralBlockKind::AlwaysFF => Ok(SliceProcKind::AlwaysFF),
        ProceduralBlockKind::AlwaysComb => Ok(SliceProcKind::AlwaysComb),
        ProceduralBlockKind::AlwaysLatch => Ok(SliceProcKind::AlwaysLatch),
        ProceduralBlockKind::Final => Ok(SliceProcKind::Final),
    }
}

/// R-run Task 9 (NL-047/NL-048): `true` iff `full_body` (a `SliceProcKind::
/// Always` block's own body, always a `Statement` per `discover_processes`'s
/// own `m.body()` check) is a `Timed` statement whose head timing control is
/// `TimingControlKind::Delay` (`always #delay ...;`) or `TimingControlKind::
/// ImplicitEvent` (`always @*`/`always @(*)`) -- the two head shapes this
/// task newly accepts. `false` for every other shape (no timing control at
/// all, `SignalEvent`, `EventList`, ...), which keep routing through
/// [`require_single_edge_head`] and its own existing rejections, entirely
/// unchanged by this task.
///
/// Also accepted (the process body keeps its event control as a real,
/// looping suspend point, resolved through the program's multi-term wait
/// table -- `process_lower::resolve_suspend_point_tabled`): an `EventList`
/// head (`always @(a or posedge b)`) and an edge-less `SignalEvent` head
/// (`always @(a)`, any change of `a`).
/// Whether `block` is an `always @*` (implicit sensitivity, LRM 9.4.2.2):
/// such a process is registered ahead of the continuous assignments
/// (`sv-sim-bin`'s `run`), so it is already waiting when their time-zero
/// evaluation (port connections included) changes its inputs from X, and
/// its combinational outputs settle at time zero. The LRM leaves time-zero
/// order open (4.7); an explicit `@(a or b)` keeps the default order.
pub fn has_implicit_event_head(block: &Symbol<'_>) -> bool {
    block.kind() == SymbolKind::ProceduralBlock
        && block.procedural_block_procedure_kind() == ProceduralBlockKind::Always
        && sv_sim_sim::process::cfg::proc_body(block).is_some_and(|body| {
            body.kind() == StatementKind::Timed
                && body
                    .timing_control()
                    .is_some_and(|tc| tc.kind() == TimingControlKind::ImplicitEvent)
        })
}

fn is_implicit_or_delay_always_head<'d>(full_body: Statement<'d>) -> bool {
    if full_body.kind() != StatementKind::Timed {
        return false;
    }
    full_body.timing_control().is_some_and(|tc| {
        let kind = tc.kind();
        kind == TimingControlKind::Delay
            || kind == TimingControlKind::ImplicitEvent
            || kind == TimingControlKind::EventList
            || (kind == TimingControlKind::SignalEvent && tc.edge() == sv_lang::EdgeKind::None)
            // `always @(edge clk)` (LRM 9.4.2: any 0->x/1, x/1->0 transition): a looping
            // event wait on both edges, not a single-polarity clocked process.
            || (kind == TimingControlKind::SignalEvent && tc.edge() == sv_lang::EdgeKind::BothEdges)
            // `always @(posedge a & b)`: an edge of an expression (LRM
            // 1800-2023 9.4.2) names no single clock signal, so it is a
            // looping event wait like an event list, not a clocked process.
            || (kind == TimingControlKind::SignalEvent
                && tc
                    .children()
                    .into_iter()
                    .find_map(|n| n.as_expression())
                    .is_some_and(|e| e.referenced_symbol().is_none()))
    })
}

/// SD-C / T28: a plain `always` with NO head timing control whose body nevertheless suspends --
/// a timing control (`#d`, `@(...)`) on one of its own statements. LRM 32.4.3's worked clock
/// example is exactly this shape:
///
/// ```text
/// always begin #dhigh clk = 1; #dlow clk = 0; end
/// ```
///
/// Such a block is not an edge-triggered process (`clock` stays `None`, as for the delay-headed
/// shapes above) and it cannot spin at one time step: every pass through its body passes a
/// timing control, so the loop `process::cfg` builds for an `Always` is a time-driven one. A body
/// with no timing control anywhere -- `always x = ~x;` -- is a zero-delay infinite loop and
/// keeps the loud rejection from [`require_single_edge_head`]. Looks for a `Timed` statement
/// anywhere under the body (a nested one may sit on a path that is not taken -- `always if (c)
/// #1 x = 1;` -- which only makes the process a possible spin, exactly as in any simulator).
fn body_suspends_inside<'d>(full_body: Statement<'d>) -> bool {
    if full_body.kind() == StatementKind::Timed {
        return false;
    }
    // `always v = #10 5;`: a blocking assignment with an intra-assignment
    // delay/event control (LRM 1800-2023 9.4.5) suspends the process too.
    // (A nonblocking one only stages the write, so it does not.)
    let suspends = |s: &Statement<'d>| {
        // `wait (c)` and a task call (`always begin delay; end`) may also
        // suspend the body; a task that never does is the same legal
        // zero-delay loop the livelock guard reports.
        matches!(s.kind(), StatementKind::Timed | StatementKind::Wait)
            || (s.kind() == StatementKind::ExpressionStatement
                && s.expr().is_some_and(|e| {
                    (e.kind() == ExpressionKind::Assignment
                        && e.is_nonblocking() != Some(true)
                        && e.assignment_timing().is_some())
                        || (e.kind() == ExpressionKind::Call
                            && e.subroutine_kind() == Some(sv_lang::SubroutineKind::Task))
                }))
    };
    if suspends(&full_body) {
        return true;
    }
    let mut stack = sv_sim_sim::process::cfg::live_children(&full_body.as_sem_node());
    while let Some(n) = stack.pop() {
        if n.as_statement().is_some_and(|s| suspends(&s)) {
            return true;
        }
        stack.extend(sv_sim_sim::process::cfg::live_children(&n));
    }
    false
}

/// For `Always`/`AlwaysFF` only (the caller passes `what` as `"always"` or
/// `"always_ff"` accordingly -- never `"initial"`, which has no clock head):
/// requires the block's body be a `Timed` statement whose timing control is
/// exactly one `SignalEventControl` with a `posedge`/`negedge` edge, and
/// returns the clock signal it names. Every other shape (no timing control
/// at all, an `EventList`/level-sensitive control, an edge-less
/// `SignalEventControl`) is a named `LoweringError` whose message embeds
/// `what` so the two procedural-block kinds' rejections read distinctly from
/// one another (never the same generic string). **R-run Task 9 (NL-047/
/// NL-048):** a plain `always`'s own `Delay`/`ImplicitEvent` head is now
/// accepted -- but one level up, in `discover_processes`'s own
/// `is_implicit_or_delay_always_head` check, BEFORE this function is ever
/// called for that case; an `always_ff` with one of those two head shapes
/// still reaches this function (via `require_clock_and_optional_reset`'s own
/// non-`EventList` fallback) and is still rejected by it, unchanged -- this
/// task's own scope is the plain-`always` discovery gate only.
fn require_single_edge_head<'d>(
    sym: &Symbol<'d>,
    what: &'static str,
    full_body: Statement<'d>,
) -> Result<(Symbol<'d>, EdgeKind), LoweringError> {
    if full_body.kind() == StatementKind::Invalid {
        return Err(LoweringError::unsupported_at(
            &format!(
                "`{what}` block's body is an Invalid statement -- slang rejected something in \
                 it; an error inside a statically dead `if`/`case` arm (e.g. a reversed range \
                 select `v[7:8]` of a descending vector under a false parameter condition) is \
                 suppressed by slang but still invalidates the whole block"
            ),
            sym,
        ));
    }
    if full_body.kind() != StatementKind::Timed {
        return Err(LoweringError::unsupported_at(
            &format!(
                "`{what}` block has no `@(...)` timing control at its head -- a bare \
                 `{what}` whose body starts directly with a statement (no head timing \
                 control at all) is unsupported in the A2 slice"
            ),
            sym,
        ));
    }

    let tc = full_body.timing_control().ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!(
                "`{what}` block's `Timed` statement has no timing control (unexpected AST shape)"
            ),
            sym,
        )
    })?;

    if tc.kind() != TimingControlKind::SignalEvent {
        return Err(LoweringError::unsupported_at(
            &format!(
                "`{what}` block head timing control is `{:?}`, not a single `posedge`/\
                 `negedge` signal-event control -- `always @*`/implicit-sensitivity, \
                 event-list (`or`-joined), and level-sensitive heads are unsupported in \
                 the A2 slice (this is distinct from a `SignalEventControl` that merely \
                 lacks an edge -- see the sibling rejection below)",
                tc.kind()
            ),
            sym,
        ));
    }

    let edge = tc.edge();
    if edge != EdgeKind::PosEdge && edge != EdgeKind::NegEdge {
        return Err(LoweringError::unsupported_at(
            &format!(
                "`{what}` block's signal-event control has edge `{edge:?}`, not \
                 `posedge`/`negedge` -- a level-sensitive (no-edge) event control is \
                 unsupported in the A2 slice"
            ),
            sym,
        ));
    }

    let clock_sym = tc
        .children()
        .into_iter()
        .find_map(|n| n.as_expression())
        .and_then(|e| e.referenced_symbol())
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                &format!(
                    "`{what}` block's edge control does not directly reference a plain \
                     signal (unsupported clock expression shape)"
                ),
                sym,
            )
        })?;

    Ok((clock_sym, edge))
}

/// For `AlwaysFF` only (Task 2, CG-079's async-reset half): like
/// [`require_single_edge_head`], but additionally accepts a
/// `TimingControlKind::EventList` head whose `children()` are exactly 2
/// `SignalEvent` sub-controls -- clock and async reset, in EITHER order
/// (`@(posedge clk or negedge rst_n)` and `@(negedge rst_n or posedge clk)`
/// are equally legal per LRM 1800-2023, which imposes no ordering
/// requirement on an event list's members) -- each edge-qualified
/// (`posedge`/`negedge`, never a bare, level-sensitive entry). Which of the
/// two is the reset is decided STRUCTURALLY by [`identify_clock_and_reset`]
/// (never by which one came first in source/AST order -- see that
/// function's own doc comment for why and how). Any other `EventList`
/// shape (more than 2 entries, fewer than 2, a non-`SignalEvent`
/// sub-control, or a bare/level-sensitive entry) is still a named
/// [`LoweringError`], not a silent best-effort guess -- this function does
/// not attempt to support an arbitrary N-signal event list, only the
/// clock+single-async-reset idiom CG-079's acceptance text names.
///
/// `Always`'s own call site keeps calling [`require_single_edge_head`]
/// directly and unchanged (a plain `always @(a or b)` is a level-sensitive
/// combinational idiom, not a clock/reset pair, and is out of this task's
/// scope); this function delegates to that same function for its own
/// single-`SignalEvent` case (no second, independently-written copy of the
/// clock-extraction logic).
/// `(clock, reset)`, `reset` present only for a clock+async-reset
/// `EventList` head -- factored out purely to keep
/// [`require_clock_and_optional_reset`]'s own signature under clippy's
/// `type_complexity` threshold, never a semantic distinction of its own.
type ClockAndOptionalReset<'d> = ((Symbol<'d>, EdgeKind), Option<(Symbol<'d>, EdgeKind)>);

fn require_clock_and_optional_reset<'d>(
    sym: &Symbol<'d>,
    full_body: Statement<'d>,
    in_checker: bool,
) -> Result<ClockAndOptionalReset<'d>, LoweringError> {
    if full_body.kind() != StatementKind::Timed {
        return Err(LoweringError::unsupported_at(
            "`always_ff` block has no `@(...)` timing control at its head -- a bare \
             `always_ff` whose body starts directly with a statement (no head timing \
             control at all) is unsupported in the A2 slice",
            sym,
        ));
    }

    let tc = full_body.timing_control().ok_or_else(|| {
        LoweringError::unsupported_at(
            "`always_ff` block's `Timed` statement has no timing control (unexpected AST shape)",
            sym,
        )
    })?;

    if tc.kind() != TimingControlKind::EventList {
        // Not an event list -- the existing single-`SignalEvent` path
        // (and every one of its own named rejections) handles this shape,
        // never duplicated here.
        let clk = require_single_edge_head(sym, "always_ff", full_body)?;
        return Ok((clk, None));
    }

    let subs: Vec<TimingControl<'d>> = tc
        .children()
        .into_iter()
        .filter_map(|n| n.as_timing_control())
        .collect();

    if subs.len() != 2 {
        return Err(LoweringError::unsupported_at(
            &format!(
                "`always_ff` block's event-list head has {} sub-control(s), not exactly 2 -- \
                 this task's scope is exactly one clock + one async reset \
                 (`@(posedge clk or negedge rst_n)`); an arbitrary N-signal event list for \
                 `always_ff` is unsupported",
                subs.len()
            ),
            sym,
        ));
    }

    let mut edges: Vec<(Symbol<'d>, EdgeKind)> = Vec::with_capacity(2);
    for sub in &subs {
        if sub.kind() != TimingControlKind::SignalEvent {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "`always_ff` block's event-list head has a `{:?}` sub-control, not a \
                     `posedge`/`negedge` signal-event control",
                    sub.kind()
                ),
                sym,
            ));
        }
        let edge = sub.edge();
        if edge != EdgeKind::PosEdge && edge != EdgeKind::NegEdge {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "`always_ff` block's event-list head has a sub-control with edge \
                     `{edge:?}`, not `posedge`/`negedge` -- a bare, level-sensitive entry in \
                     an `always_ff` event list is not a valid async-reset idiom"
                ),
                sym,
            ));
        }
        let signal = sub
            .children()
            .into_iter()
            .find_map(|n| n.as_expression())
            .and_then(|e| e.referenced_symbol())
            .ok_or_else(|| {
                LoweringError::unsupported_at(
                    "`always_ff` block's event-list head has a sub-control that does not \
                     directly reference a plain signal (unsupported clock/reset expression \
                     shape)",
                    sym,
                )
            })?;
        edges.push((signal, edge));
    }

    if let Some(pair) = identify_clock_and_reset(full_body, edges[0], edges[1]) {
        return Ok(pair);
    }
    if in_checker {
        // No `if` singles out a reset (LRM 17.5's checker `always_ff @(posedge clk or
        // negedge rst)` tests `if (rst)`, the opposite polarity). The two entries are
        // then just an edge list, like the head of a plain `always`: the process's
        // own multi-term wait (`SuspendPoint::EdgeList`) wakes it on either, no reset
        // is registered statically, and `clock` is nominal (nothing reads it).
        return Ok((edges[0], None));
    }
    Err(LoweringError::unsupported_at(
        "`always_ff` block's event-list head has a clock+async-reset pair, but its body's \
         top-level `if` (looking only through `begin`/`end` wrapping) does not \
         unambiguously identify exactly one of the two entries as the reset -- by testing \
         a bare reference to it with a polarity matching its own declared edge -- so the \
         clock and reset cannot be told apart by source order alone (LRM 1800-2023 \
         imposes no ordering requirement on an event list's members)",
        sym,
    ))
}

/// Whether an `always_ff` head is a signal event or a flat list of them with
/// at least one entry that has no `posedge`/`negedge` (LRM 9.4.2: a plain
/// value-change event; LRM 9.2.2.4 does not forbid it).
fn has_value_change_entry(tc: TimingControl<'_>) -> bool {
    let entries: Vec<TimingControl<'_>> = if tc.kind() == TimingControlKind::SignalEvent {
        vec![tc]
    } else if tc.kind() == TimingControlKind::EventList {
        tc.children()
            .into_iter()
            .filter_map(|n| n.as_timing_control())
            .collect()
    } else {
        return false;
    };
    !entries.is_empty()
        && entries
            .iter()
            .all(|t| t.kind() == TimingControlKind::SignalEvent)
        && entries.iter().any(|t| t.edge() == EdgeKind::None)
}

/// Whether an `always_ff` head is an event list of MORE than two signal events
/// (LRM 9.2.2.4.1 allows any number): there is no single clock/reset pair in it.
fn is_wide_edge_list_head(full_body: Statement<'_>) -> bool {
    let Some(tc) = full_body.timing_control() else {
        return false;
    };
    if tc.kind() != TimingControlKind::EventList {
        return false;
    }
    let subs: Vec<TimingControl<'_>> = tc
        .children()
        .into_iter()
        .filter_map(|n| n.as_timing_control())
        .collect();
    subs.len() > 2
        && subs
            .iter()
            .all(|t| t.kind() == TimingControlKind::SignalEvent)
}

/// Whether an `always_ff` head is one [`require_clock_and_optional_reset`]
/// accepts: a single edge-qualified signal event, or exactly two of them, each
/// naming a plain signal.
fn is_clock_reset_idiom_head(full_body: Statement<'_>) -> bool {
    let Some(tc) = full_body.timing_control() else {
        return false;
    };
    let edge_entry = |t: &TimingControl<'_>| {
        t.kind() == TimingControlKind::SignalEvent
            && (t.edge() == EdgeKind::PosEdge || t.edge() == EdgeKind::NegEdge)
            && t.children()
                .into_iter()
                .find_map(|n| n.as_expression())
                .and_then(|e| e.referenced_symbol())
                .is_some()
    };
    if tc.kind() == TimingControlKind::SignalEvent {
        return edge_entry(&tc);
    }
    if tc.kind() == TimingControlKind::EventList {
        let subs: Vec<TimingControl<'_>> = tc
            .children()
            .into_iter()
            .filter_map(|n| n.as_timing_control())
            .collect();
        return subs.len() == 2 && subs.iter().all(edge_entry);
    }
    false
}

/// Distinguishes the clock from the async-reset entry of an `always_ff`
/// `EventList` head STRUCTURALLY -- by which of the two edge-qualified
/// signals the body's own top-level `if`/`else` tests against its declared
/// edge polarity -- never by the two entries' AST/source order. LRM
/// 1800-2023 places no ordering requirement on an event list's members, so
/// `@(posedge clk or negedge rst_n)` and `@(negedge rst_n or posedge clk)`
/// are equally legal and must resolve to the SAME `(clock, reset)` pair for
/// the same body (this fixes a review finding on this task's r1: a
/// position-based `edges[0]`-is-clock rule silently swapped the roles on
/// the reset-first form).
///
/// The reset is whichever of `a`/`b` the body's first top-level `if`
/// condition (found by [`find_top_level_conditional`], looking through
/// `begin`/`end`/bare-sequence wrapping only -- never into a `case`/loop/
/// other nested control construct) tests with a polarity consistent with
/// its own declared edge, per [`condition_polarity`]: a bare reference
/// (`if (rst)`) for a `PosEdge` entry, or a logical/bitwise negation of a
/// bare reference (`if (!rst_n)`/`if (~rst_n)`) for a `NegEdge` entry --
/// CG-079's own async-reset idiom (`docs/design/process.md`). The OTHER
/// entry is the clock; `clock` is never itself matched against the
/// condition, only ruled in by elimination once exactly one of `a`/`b` is
/// positively identified as the reset.
///
/// If the condition cannot be found, or matches neither entry, or
/// (degenerately) matches both, this returns `None` and the caller decides:
/// a plain module's `always_ff` is a named [`LoweringError`] rather than a
/// positional guess (this module's "never a silent skip" discipline, see the
/// top-of-file doc comment), while a checker's is a plain edge list (LRM 17.5's
/// `always_ff @(posedge clk or negedge rst)` with `if (rst)` is legal there).
fn identify_clock_and_reset<'d>(
    full_body: Statement<'d>,
    a: (Symbol<'d>, EdgeKind),
    b: (Symbol<'d>, EdgeKind),
) -> Option<ClockAndOptionalReset<'d>> {
    let cond = sv_sim_sim::process::cfg::live_statements(&full_body)
        .into_iter()
        .find_map(find_top_level_conditional)?;
    let conditions = cond.conditions();
    let polarity = if conditions.len() == 1 {
        condition_polarity(conditions[0].expr())
    } else {
        None
    };

    let matches = |sig: Symbol<'d>, edge: EdgeKind| {
        polarity.is_some_and(|(psym, active_high)| {
            psym.uid() == sig.uid() && active_high == (edge == EdgeKind::PosEdge)
        })
    };
    let a_matches = matches(a.0, a.1);
    let b_matches = matches(b.0, b.1);

    match (a_matches, b_matches) {
        (true, false) => Some((b, Some(a))),
        (false, true) => Some((a, Some(b))),
        _ => None,
    }
}

/// If `stmt` is a `Conditional` (`if`), returns it; if it is a `Block`/
/// `List` (a `begin`/`end` wrapper, or a bare statement sequence), looks
/// through it for the first such `Conditional` among its own immediate
/// children (recursing through further `Block`/`List` wrapping only);
/// anything else (a `case`, a loop, a single non-conditional statement,
/// ...) yields `None` -- this is deliberately shallow, matching only the
/// specific "an `if`, possibly `begin`/`end`-wrapped, at the top of the
/// body" shape CG-079's async-reset idiom uses, never a general search into
/// arbitrary nested control.
fn find_top_level_conditional<'d>(stmt: Statement<'d>) -> Option<Statement<'d>> {
    // slang demotes a statement holding a statically dead arm it could not
    // bind to `Invalid`; the live statement underneath is the real shape.
    let stmt = sv_sim_sim::process::cfg::unwrap_invalid(stmt);
    // Deliberately an `if`/`matches!` chain, not a `match` over
    // `StatementKind` -- this is a narrow shape probe ("does `stmt` look
    // like an `if`, possibly `begin`/`end`-wrapped?"), never an exhaustive
    // classification of every `StatementKind` variant, so a "not this
    // shape" `None` here is not the silent-fallback pattern `xtask
    // lint-unimplemented` polices for a real Kind-typed `match`.
    if stmt.kind() == StatementKind::Conditional {
        return Some(stmt);
    }
    if matches!(stmt.kind(), StatementKind::Block | StatementKind::List) {
        return sv_sim_sim::process::cfg::live_statements(&stmt)
            .into_iter()
            .find_map(find_top_level_conditional);
    }
    None
}

/// The `(signal, active_high)` this `if` condition expression tests, for
/// the two canonical CG-079 async-reset shapes: a bare reference
/// (`active_high = true`) or a logical/bitwise negation of one
/// (`active_high = false`). `None` for any other expression shape (a
/// comparison, a compound boolean, a call, ...) -- [`identify_clock_and_reset`]
/// treats that as "this condition does not identify a reset", never a
/// guess.
fn condition_polarity<'d>(expr: Expression<'d>) -> Option<(Symbol<'d>, bool)> {
    // Deliberately an `if`/`matches!` chain, not a `match` over
    // `ExpressionKind` -- a narrow shape probe over exactly the two
    // canonical async-reset condition shapes, never an exhaustive
    // classification of every `ExpressionKind` variant (see this
    // function's own doc comment); a "not one of these two shapes" `None`
    // is not the silent-fallback pattern `xtask lint-unimplemented` polices
    // for a real Kind-typed `match`.
    if sv_sim_sim::symid::is_value_name(expr.kind()) {
        return expr.referenced_symbol().map(|s| (s, true));
    }
    if expr.kind() == ExpressionKind::UnaryOp
        && matches!(
            expr.unary_op(),
            Some(UnaryOp::LogicalNot | UnaryOp::BitwiseNot)
        )
    {
        return expr
            .operand()
            .and_then(|op| op.referenced_symbol())
            .map(|s| (s, false));
    }
    None
}

/// XC-007: a generic depth-first walk of `root`'s semantic tree (statements,
/// expressions, timing controls -- every domain `SemNode::children()`
/// reaches) rejecting, with a named `LoweringError` wherever in the tree it
/// appears, a concurrent or immediate assertion statement (`StatementKind::
/// ConcurrentAssertion`/`ImmediateAssertion`) -- SVA is deferred (XC-007).
/// Two other constructs were rejected here until they became real:
/// `randomize` (XC-006, constraints plan C1: `obj.randomize()` is lowered by
/// `classes_randomize::lower_randomize_call`, which rejects the forms it
/// cannot yet solve with its own named errors) and `$sdf_annotate` (XC-008,
/// SD-B / T25: `systask::lower_sdf_annotate_call`).
///
/// A plain gate-primitive instance with no SDF (XC-008's positive half) is
/// not itself a statement/expression, so it never reaches this walk at all --
/// see `discover_processes`'s doc comment for why non-procedural members
/// (`PrimitiveInstance` included) are skipped outright, which is itself
/// XC-008's "does not crash" proof.
///
/// Every other statement/expression kind (loops, `case`, `wait`, fork/join,
/// ...) is deliberately NOT rejected here -- their own slice-scope
/// enforcement belongs to Task S3a's `build_cfg` (which does not exist in
/// this track's tree yet), and duplicating partial coverage of their
/// rejection here would risk a second, divergent "unsupported" message for
/// the same construct once S3a lands.
fn reject_unsupported_in_body<'d>(
    block_sym: &Symbol<'d>,
    root: Statement<'d>,
) -> Result<(), LoweringError> {
    reject_unsupported_in_body_with(block_sym, root, false)
}

/// [`reject_unsupported_in_body`], optionally letting a concurrent assertion
/// statement through (a procedural one, 16.14.6, checked and hosted by
/// [`collect_nested_assertions`]); its subtree is not walked here.
fn reject_unsupported_in_body_with<'d>(
    block_sym: &Symbol<'d>,
    root: Statement<'d>,
    nested_assertions_ok: bool,
) -> Result<(), LoweringError> {
    let mut stack = vec![root.as_sem_node()];
    while let Some(node) = stack.pop() {
        if let Some(stmt) = node.as_statement()
            && stmt.kind() == StatementKind::ConcurrentAssertion
        {
            if nested_assertions_ok {
                continue;
            }
            validate_assertion_leaves(block_sym, stmt)?;
            return Err(LoweringError::unsupported_at(
                &format!(
                    "{:?} statement (SVA concurrent assertions are deferred, XC-007)",
                    stmt.kind()
                ),
                block_sym,
            ));
        }
        stack.extend(sv_sim_sim::process::cfg::live_children(&node));
    }
    Ok(())
}

/// `full_body` of an `always` block, when it is exactly one concurrent
/// assertion statement (a bare `always assert property (...)`, also how
/// slang elaborates a module-level `assert property`): the static assertion
/// of 16.14, a new attempt at every leading-clock tick. An assertion under
/// an event control, in a conditional or in `initial` is procedural
/// (16.14.6) and is not recognised here.
pub fn static_assertion_statement<'d>(full_body: Statement<'d>) -> Option<Statement<'d>> {
    let stmt = through_single_statement_blocks(full_body)?;
    (stmt.kind() == StatementKind::ConcurrentAssertion).then_some(stmt)
}

/// `stmt` with every single-statement block wrapper around it removed (they
/// are transparent); `None` when a block holds more than one statement.
fn through_single_statement_blocks<'d>(mut stmt: Statement<'d>) -> Option<Statement<'d>> {
    while stmt.kind() == StatementKind::Block {
        let inner: Vec<Statement<'d>> = stmt
            .as_sem_node()
            .children()
            .into_iter()
            .filter_map(|n| n.as_statement())
            .collect();
        match inner.as_slice() {
            [one] => stmt = *one,
            _ => return None,
        }
    }
    Some(stmt)
}

/// Whether `block` is a static deferred assertion (LRM 16.4.3): an `always`
/// block (how slang elaborates a module-level `assert #0 (...)`) whose body is
/// exactly one deferred immediate assertion. "It is treated as if it were
/// contained in an always_comb procedure": it runs once at time zero and
/// again whenever a signal its condition or actions read changes.
pub(crate) fn is_static_deferred_assertion(block: &Symbol<'_>) -> bool {
    static_deferred_assertion_of(block).is_some()
}

/// The deferred immediate assertion `block` is ([`is_static_deferred_assertion`]).
pub fn static_deferred_assertion_of<'d>(block: &Symbol<'d>) -> Option<Statement<'d>> {
    if block.kind() != SymbolKind::ProceduralBlock
        || block.procedural_block_procedure_kind() != ProceduralBlockKind::Always
    {
        return None;
    }
    block
        .body()
        .and_then(through_single_statement_blocks)
        .filter(|s| {
            s.kind() == StatementKind::ImmediateAssertion && s.is_deferred_assertion() == Some(true)
        })
}

/// The block is evaluated like an `always_comb` (9.2.2.2): an `always_comb`,
/// an `always_latch`, or a static deferred assertion (16.4.3).
fn has_comb_semantics(block: &Symbol<'_>) -> bool {
    block.kind() == SymbolKind::ProceduralBlock
        && (matches!(
            block.procedural_block_procedure_kind(),
            ProceduralBlockKind::AlwaysComb | ProceduralBlockKind::AlwaysLatch
        ) || is_static_deferred_assertion(block))
}

/// Sibling check (T5, `docs/superpowers/plans/2026-10-03-sva.md`): every
/// Boolean leaf the assertion's `AssertionExpr` tree reaches is validated
/// against LRM 16.6 (`sva::validate_boolean_leaf`), so a leaf that violates
/// 16.6 is diagnosed with that specific, named error. The root
/// `AssertionExpr` is a direct semantic child of the statement.
fn validate_assertion_leaves<'d>(
    block_sym: &Symbol<'d>,
    stmt: Statement<'d>,
) -> Result<(), LoweringError> {
    if let Some(root) = stmt
        .as_sem_node()
        .children()
        .into_iter()
        .find_map(|n| n.as_assertion_expr())
    {
        let mut leaves = Vec::new();
        crate::sva::collect_boolean_leaves(root, &mut leaves);
        for leaf in leaves {
            crate::sva::leaf::validate_boolean_leaf(leaf, block_sym)?;
        }
    }
    Ok(())
}

/// A pinned kind-count no longer matches the pinned `sv-lang`/`sv-lang-kinds`
/// version this module's own matches (`classify_procedure_kind`'s
/// `ProceduralBlockKind` match, `require_single_edge_head`'s
/// `TimingControlKind` match, `reject_unsupported_in_body`'s `StatementKind`
/// match and `Expression::call_subroutine_name` use) were last reviewed
/// against. Deliberately a separate type from `sv-sim-sim::determinism::
/// kind_guard::KindCountDrift` -- that module guards a different subsystem's
/// matches over the same enums, and `sv-sim-codegen` must not gain a
/// dependency on `sv-sim-sim` just to share this comparator (the crates'
/// dependency edge runs the other way once Task S3c lands).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KindCountDrift {
    pub kind_name: &'static str,
    pub expected: u16,
    pub actual: u16,
}

impl fmt::Display for KindCountDrift {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}::COUNT drifted: expected {} (last reviewed value), found {} -- re-review \
             every exhaustive match over {} in crates/sv-sim-codegen/src/module.rs before \
             updating the expected count",
            self.kind_name, self.expected, self.actual, self.kind_name
        )
    }
}

impl std::error::Error for KindCountDrift {}

fn assert_kind_count(
    kind_name: &'static str,
    actual: u16,
    expected: u16,
) -> Result<(), KindCountDrift> {
    if actual == expected {
        Ok(())
    } else {
        Err(KindCountDrift {
            kind_name,
            expected,
            actual,
        })
    }
}

/// CG-069/DT-048 (TimingControlKind clause): the CI kind-count guard for
/// THIS file's own exhaustive matches. `sv-sim-sim::determinism::kind_guard`
/// already pins `ExpressionKind`/`StatementKind`/`SymbolKind` for a
/// *different* subsystem's matches (netlist elaboration, and this crate's
/// own pre-existing `expr.rs`/`func.rs`); this function is `sv-sim-codegen`'s
/// own copy of that same pinned-count discipline, scoped to the matches this
/// file adds. `TimingControlKind` in particular had ZERO match sites
/// anywhere in the tree before this file (`require_single_edge_head`'s
/// `match` over it is the first) -- this is the guard
/// `sv-sim-sim::determinism::kind_guard`'s own doc comment says must land
/// "in the same commit that adds the first `TimingControlKind` match".
/// `StatementKind`/`ExpressionKind` are re-checked here too (not only
/// `TimingControlKind`) because `reject_unsupported_in_body` matches on
/// `StatementKind` and calls an `ExpressionKind::Call`-only API
/// (`call_subroutine_name`) -- a version bump changing either count is a
/// review trigger for THIS file's matches independent of whether it also
/// changes something in `sv-sim-sim`'s guarded set.
///
/// `ProceduralBlockKind` (the sv-lang "procedure-kind enum" the A2-slice plan
/// asks this function to also guard) is deliberately NOT included as a
/// fourth numeric comparison here: unlike `sv_lang_kinds`'s slang-generated
/// enums, it is a small hand-authored Rust enum in `sv-lang` with no
/// `::COUNT`/reflection export to compare against. Manufacturing a numeric
/// "actual" for it would mean comparing two constants this file itself
/// defines, which can never disagree -- exactly the "gate that cannot fail"
/// this project's correctness posture forbids (see
/// `docs/superpowers/plans/2026-09-26-wave-A2-slice.md`'s global correctness
/// constraints). Its real, strictly stronger guard is
/// `classify_procedure_kind`'s exhaustive `match` (no wildcard arm): a
/// future `sv-lang` bump adding a 7th `ProceduralBlockKind` variant fails
/// this crate's **compile**, not merely a test run. See
/// `procedural_block_kind_routing_is_exhaustive_over_all_six_variants` in
/// `tests/module_discovery.rs` for the accompanying per-variant behavioral
/// proof that every one of today's 6 variants routes as this file expects.
pub fn assert_kind_counts_match_pinned_slang() -> Result<(), KindCountDrift> {
    assert_kind_count("TimingControlKind", TimingControlKind::COUNT, 10)?;
    assert_kind_count("StatementKind", StatementKind::COUNT, 32)?;
    assert_kind_count("ExpressionKind", ExpressionKind::COUNT, 41)?;
    Ok(())
}

/// The `SignalSlot` of every variable, net and port of one module body,
/// numbered in `state::layout::build_template_layout`'s own member order
/// (moved here from `sv-sim-bin::run` so a subroutine body can resolve its
/// declaring module's memories too).
pub fn signal_slots_of<'d>(
    body: &Symbol<'d>,
) -> Result<HashMap<SymbolId, SignalSlot>, LoweringError> {
    let mut map = HashMap::new();
    let mut slot_index: u32 = 0;
    for member in sv_sim_sim::netlist::state_items(body) {
        let kind = member.kind();
        if !matches!(
            kind,
            SymbolKind::Variable | SymbolKind::Net | SymbolKind::Port | SymbolKind::FormalArgument
        ) {
            continue;
        }
        if kind == SymbolKind::Port && member.port_internal_symbol().is_some() {
            continue;
        }
        if kind == SymbolKind::Port && member.port_is_null_port() {
            continue;
        }
        let ty = if kind == SymbolKind::Port {
            member.port_type()
        } else {
            member.value_type()
        };
        let Some(ty) = ty else {
            // `build_template_layout` itself would already have rejected
            // this design with `LayoutError::UnsupportedMemberKind` before
            // this function is ever called on it -- unreachable for any
            // design `run_design` gets this far with.
            continue;
        };
        let (width, signed, class) = if kind == SymbolKind::Net
            && sv_sim_sim::state::storage::interconnect_dims(&ty).is_some()
        {
            // An `interconnect` net (LRM 6.6.8): the layout's inert 1-bit
            // placeholder (`state::layout::build_template_layout`).
            (1, false, SignalSlotClass::Inline)
        } else if sv_sim_sim::state::storage::is_collection(&ty) {
            // A queue / dynamic / associative array: a collection handle.
            (64, false, SignalSlotClass::Inline)
        } else if ty.is_unpacked_array() {
            let shape = crate::arrays::array_shape(&ty).ok_or_else(|| {
                LoweringError::unsupported_at("a dynamically sized unpacked array member", &member)
            })?;
            let elem_ty = shape.elem;
            // Rows are integral values or the bits of a real/string/chandle
            // (state/layout.rs's memory branch accepts the same set).
            if !(elem_ty.is_integral()
                || elem_ty.is_floating()
                || elem_ty.is_string()
                || elem_ty.is_chandle()
                || elem_ty.is_covergroup()
                || elem_ty.is_class()
                || elem_ty.is_virtual_interface()
                || sv_sim_sim::state::storage::is_unpacked_aggregate(&elem_ty)
                || elem_ty.is_event()
                || sv_sim_sim::state::storage::is_collection(&elem_ty))
            {
                return Err(LoweringError::unsupported_at(
                    "unpacked-array element type is not a value type this simulator \
                     stores in a memory row",
                    &member,
                ));
            }
            // An event element is one named event's cell (state/layout.rs's
            // memory branch).
            let elem_width = if elem_ty.is_event() {
                sv_sim_sim::state::EVENT_CELL_WIDTH
            } else {
                elem_ty.value_width()
            };
            // A row wider than the LLVM-integer ceiling is an image
            // (`crate::huge::mem_elem_root`); whole-array operations on it
            // are refused by name (`crate::arrays::load_raw`).
            // Every dimension flattened (`crate::arrays`); `lower_index` is
            // the first dimension's (a 1-D memory's SV index of row 0).
            let range = ty.fixed_unpacked_array_range();
            (
                elem_width,
                elem_ty.is_signed(),
                SignalSlotClass::Memory {
                    num_rows: shape.rows() as u32,
                    lower_index: i64::from(range.lower()),
                },
            )
        } else if ty.is_event() {
            // A named event is state/layout.rs's 2-state Wide trigger cell.
            (
                sv_sim_sim::state::EVENT_CELL_WIDTH,
                false,
                SignalSlotClass::Wide,
            )
        } else {
            let width = ty.value_width();
            let class = if width > 64 {
                SignalSlotClass::Wide
            } else {
                SignalSlotClass::Inline
            };
            (width, ty.is_signed(), class)
        };
        map.insert(
            member.uid(),
            SignalSlot {
                slot: slot_index,
                width,
                signed,
                class,
            },
        );
        slot_index += 1;
    }
    // Clocking blocks (`sv_sim_sim::state::clocking_blocks`, the same
    // order as the layout): the block's event counter, keyed by the block,
    // then its input clock variables' samples.
    for (cb, vars) in sv_sim_sim::state::clocking_blocks(body) {
        map.insert(
            cb.uid(),
            SignalSlot {
                slot: slot_index,
                width: 32,
                signed: false,
                class: SignalSlotClass::Inline,
            },
        );
        slot_index += 1;
        for v in vars {
            let ty = v.value_type().ok_or_else(|| {
                LoweringError::unsupported_at("a clock variable with no type", &v)
            })?;
            let width = ty.value_width();
            map.insert(
                v.uid(),
                SignalSlot {
                    slot: slot_index,
                    width,
                    signed: ty.is_signed(),
                    class: if width > 64 {
                        SignalSlotClass::Wide
                    } else {
                        SignalSlotClass::Inline
                    },
                },
            );
            slot_index += 1;
        }
    }
    // The sampled value functions' hidden P/S cells
    // (`sv_sim_sim::sva::sampled::hidden_slots`, the same order as the
    // layout): each is a copy of its source signal's slot.
    let hidden = sv_sim_sim::sva::sampled::hidden_slots(body)
        .map_err(|e| LoweringError::unsupported(&e.to_string(), &body.hierarchical_path()))?;
    for cell in hidden.slots() {
        let src = if let Some(shape) = &cell.foreign {
            SignalSlot {
                slot: 0,
                width: shape.width,
                signed: shape.signed,
                class: if shape.width > 64 {
                    SignalSlotClass::Wide
                } else {
                    SignalSlotClass::Inline
                },
            }
        } else {
            map.get(&cell.source).copied().ok_or_else(|| {
                LoweringError::unsupported(
                    &format!(
                        "sampled value function over `{}`, which has no state slot",
                        cell.source
                    ),
                    &body.hierarchical_path(),
                )
            })?
        };
        map.insert(
            cell.id.clone(),
            SignalSlot {
                slot: slot_index,
                ..src
            },
        );
        slot_index += 1;
    }
    // The end-point watcher cells (`sv_sim_sim::sva::endpoint::watchers`, the
    // same order as the layout).
    for w in sv_sim_sim::sva::endpoint::watchers(body) {
        map.insert(
            w.id(),
            SignalSlot {
                slot: slot_index,
                width: sv_sim_sim::state::EVENT_CELL_WIDTH,
                signed: false,
                class: SignalSlotClass::Wide,
            },
        );
        slot_index += 1;
    }
    // The event pool (`sv_sim_sim::state::event_pool`, last in the layout):
    // the pool memory itself under `pool_key()`, and each static event
    // variable's id range as an entry on the same slot (`num_rows` its event
    // count, `lower_index` the id of its first event). `lower_index` of the
    // pool entry is `S`, the static count.
    if let Some(pool) = sv_sim_sim::state::event_pool::event_pool(body) {
        let entry = |num_rows: u32, lower_index: i64| SignalSlot {
            slot: slot_index,
            width: sv_sim_sim::state::EVENT_CELL_WIDTH,
            signed: false,
            class: SignalSlotClass::Memory {
                num_rows,
                lower_index,
            },
        };
        map.insert(
            sv_sim_sim::state::event_pool::pool_key(),
            entry(pool.total_rows(), i64::from(pool.static_rows)),
        );
        for s in &pool.statics {
            map.insert(
                sv_sim_sim::state::event_pool::static_key(&s.var.uid()),
                entry(s.count, i64::from(s.first)),
            );
            map.insert(
                sv_sim_sim::state::event_pool::pool_of_key(&s.var.uid()),
                entry(pool.total_rows(), i64::from(pool.static_rows)),
            );
        }
    }
    Ok(map)
}