vj-sim 0.1.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
//! Classes plan (`docs/superpowers/plans/2026-10-03-classes.md`) Task 3: the
//! object heap runtime (LRM 1800-2023 §8.29 memory management, §8.4 object
//! identity). Pure-Rust, zero sv-lang/codegen dependency (this task's own
//! acceptance text) — see `crate::netlist::ClassTemplateId`'s doc comment
//! for why that id, despite being produced by the `frontend`-gated
//! `netlist::classes` module, is itself defined unconditionally and usable
//! from here.
//!
//! **Why a second table, not `collections.rs`'s.** [`collections`] stores
//! SV *values*: `a = b` copies (copy-on-write via `Table::modify`), and an
//! overwritten handle is unconditionally freed. A class object is a
//! *reference* (§8.2: "the argument copied is the object handle, not the
//! contents of the object") — `h2 = h1` makes both variables alias the SAME
//! object, nothing is cloned, and an object is freed only when nothing
//! references it any more. So this module is a structurally parallel
//! generational handle table (same `version<<32 | index` shape, handle `0`
//! reserved for `null`, a `Mutex`-guarded table with a free list so a reused
//! slot never repeats a handle — directly modeled on `collections.rs`'s
//! `Table`/`index`/`alloc`) but with real reference counting instead of
//! copy-on-write.
//!
//! **Weak references fall out for free.** A stale `(version, index)` handle
//! can never alias a different, later object at the same index: `alloc`
//! always bumps that slot's `version` counter (never reused, only the index
//! is recycled), and every read ([`field_get`], [`is_a`],
//! [`dynamic_template`]) rejects a handle whose `version` does not match the
//! table's current entry at that index. The LRM's "the clearing operation
//! shall be performed atomically" (8.30.1) is satisfied by construction:
//! the staleness check and the table's own `Mutex` are the same operation,
//! so there is nothing to race.
//!
//! **Per-template metadata is a registry, not a call-site parameter.**
//! [`release`]'s recursive free walk (which fields of a freed object are
//! themselves class handles that must themselves be released) and [`is_a`]
//! (which `ClassTemplateId`s a given dynamic template satisfies — self,
//! every base, every flattened interface) both need information that is
//! fixed per `ClassTemplateId`, computed once at elaboration time, and
//! consumed by scattered call sites with no spare room to thread a `&[_]`/
//! `&HashMap` argument through (most of those call sites are
//! `#[no_mangle] extern "C"` ABI entry points reached from LLVM-emitted
//! code, which can only pass scalar/pointer arguments it already has in
//! hand — never a slice or map reference). So, exactly like
//! [`collections`]'s own `table()` global, this module keeps one more
//! process-wide `Mutex`-guarded table, [`registry`], populated once per
//! template by [`register_handle_fields`]/[`register_ancestors`] (Task 5
//! wires in the real `ObjectLayout`-derived field list; Task 10 wires in the
//! real `netlist::classes::base_chain`/`flattened_interfaces`-derived
//! ancestor set — this task's own tests call both directly with a hand-built
//! list/set, exactly as the plan's Task 3 entry specifies). An
//! unregistered template is simply treated as having no handle fields and
//! no ancestors beyond itself — never a panic, since a template legitimately
//! has nothing to register when, e.g., it declares no class-typed
//! properties at all.

use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};

use crate::constraints::randc::RandcState;
use crate::netlist::ClassTemplateId;

/// One non-static field's location in an object's flat `fields` buffer:
/// a word offset and a word count. `words` is always `1` for a field that
/// holds a class handle (a handle is a single `u64`); wider counts are for
/// ordinary (non-handle) SV data fields, which [`field_get`]/[`field_set`]
/// handle identically — this module does not interpret field contents
/// except where [`release`]'s recursive walk is told a slot is itself a
/// handle (see [`register_handle_fields`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct FieldSlot {
    pub offset: usize,
    pub words: usize,
}

/// A bit window of one property: a leaf (a member of an unpacked struct, an
/// element of a fixed-size unpacked array) addressed inside the property's one
/// flat 4-state value (`state::storage`). The property holds `field_width` value
/// bits then `field_width` unknown bits; the leaf is `width` bits at value bit
/// `bit`, with its unknown bits at `field_width + bit`.
#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct Window {
    /// The leaf's LSB within the property's value bits.
    pub bit: u32,
    /// The leaf's width in bits.
    pub width: u32,
    /// The whole property's width in bits (where its unknown half starts).
    pub field_width: u32,
}

/// `n` (at most 64) bits of `words` starting at bit `lo`; bits past the end
/// read 0.
fn get_bits(words: &[u64], lo: usize, n: usize) -> u64 {
    debug_assert!(n <= 64);
    if n == 0 {
        return 0;
    }
    let w = lo / 64;
    let sh = lo % 64;
    let a = words.get(w).copied().unwrap_or(0) >> sh;
    let v = if sh == 0 {
        a
    } else {
        a | (words.get(w + 1).copied().unwrap_or(0) << (64 - sh))
    };
    if n == 64 { v } else { v & ((1u64 << n) - 1) }
}

/// Overwrites `n` (at most 64) bits of `words` starting at bit `lo` with the low
/// bits of `v`; bits past the end are dropped.
fn set_bits(words: &mut [u64], lo: usize, n: usize, v: u64) {
    debug_assert!(n <= 64);
    if n == 0 {
        return;
    }
    let mask = if n == 64 { u64::MAX } else { (1u64 << n) - 1 };
    let v = v & mask;
    let w = lo / 64;
    let sh = lo % 64;
    if let Some(x) = words.get_mut(w) {
        *x = (*x & !(mask << sh)) | (v << sh);
    }
    if sh != 0
        && sh + n > 64
        && let Some(x) = words.get_mut(w + 1)
    {
        let hi_mask = mask >> (64 - sh);
        *x = (*x & !hi_mask) | (v >> (64 - sh));
    }
}

impl Window {
    /// The window's value (`ceil(width/64)` words) out of the property words
    /// `fields`, and its unknown bits in the same shape.
    fn read(&self, fields: &[u64], val: &mut [u64], unk: &mut [u64]) {
        for (i, (v, u)) in val.iter_mut().zip(unk.iter_mut()).enumerate() {
            let lo = i * 64;
            let n = (self.width as usize).saturating_sub(lo).min(64);
            *v = get_bits(fields, self.bit as usize + lo, n);
            *u = get_bits(fields, (self.field_width + self.bit) as usize + lo, n);
        }
    }

    /// Stores `val` into the window of `fields` as a fully known value.
    fn write(&self, fields: &mut [u64], val: &[u64]) {
        for i in 0..(self.width as usize).div_ceil(64) {
            let lo = i * 64;
            let n = (self.width as usize - lo).min(64);
            let v = val.get(i).copied().unwrap_or(0);
            set_bits(fields, self.bit as usize + lo, n, v);
            set_bits(fields, (self.field_width + self.bit) as usize + lo, n, 0);
        }
    }
}

/// A class-handle or collection-handle held INSIDE a larger property: a field
/// or element of an unpacked struct, or an element of a fixed-size unpacked
/// array, stored as part of the property's one flat value (LRM 1800-2023 7.2,
/// 7.4: `state::storage`). The handle is a 64-bit value at bit `bit` of the
/// property's value bits (the low half of the property's 4-state packed
/// words, which is where [`field_get`] hands them out).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct NestedHandle {
    /// The property holding the handle.
    pub slot: FieldSlot,
    /// The handle's LSB within the property's value bits.
    pub bit: u32,
    /// A collection handle (`crate::collections`) rather than an object's.
    pub coll: bool,
}

/// The 64 value bits at `nh`'s position of `fields`; `None` when the position
/// lies outside the buffer (a registration that does not fit the object).
fn nested_get(fields: &[u64], nh: &NestedHandle) -> Option<u64> {
    let w = nh.slot.offset + (nh.bit / 64) as usize;
    let sh = nh.bit % 64;
    let lo = *fields.get(w)? >> sh;
    if sh == 0 {
        return Some(lo);
    }
    Some(lo | (*fields.get(w + 1)? << (64 - sh)))
}

/// Overwrites the 64 value bits [`nested_get`] reads with `h`.
fn nested_set(fields: &mut [u64], nh: &NestedHandle, h: u64) {
    let w = nh.slot.offset + (nh.bit / 64) as usize;
    let sh = nh.bit % 64;
    if sh == 0 {
        if let Some(d) = fields.get_mut(w) {
            *d = h;
        }
        return;
    }
    if w + 1 >= fields.len() {
        return;
    }
    let lo_mask = u64::MAX << sh;
    fields[w] = (fields[w] & !lo_mask) | (h << sh);
    fields[w + 1] = (fields[w + 1] & lo_mask) | (h >> (64 - sh));
}

/// Whether a `rand` property is plain `rand` or cyclic `randc` (LRM 18.4).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RandKind {
    Rand,
    RandC,
}

/// One `rand`/`randc` property of a class template: where its value lives in
/// an object's `fields` buffer and which kind it is. Fixed by the class
/// declaration, so it lives on the template ([`register_rand_props`]), not on
/// each object.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RandProp {
    pub slot: FieldSlot,
    pub kind: RandKind,
}

/// Per-object `rand`/`randc` metadata (LRM §18.4, §18.8): the `rand_mode()`
/// on/off state of each `rand`/`randc` property, in the order
/// [`register_rand_props`] listed them (base-class properties first). Every
/// object starts with all of them `true` -- LRM 18.8: "Initially, all
/// `rand` variables are active". What is `rand` and what is `randc` is the
/// template's ([`rand_props`]); this vector is the only mutable part, so the
/// constraints plan's `randomize()` and `obj.x.rand_mode(0)` read/write it
/// here without a second per-object side table.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RandMeta {
    /// `rand_mode[i]` is whether the template's `i`th [`RandProp`] is active.
    pub rand_mode: Vec<bool>,
    /// Individual elements of a fixed-size array property switched off by
    /// `obj.a[i].rand_mode(0)` (LRM 18.8: "random_variable can specify
    /// individual elements using the corresponding index"), as `(index into
    /// rand_mode, bit offset of the element within the property)` pairs. Empty
    /// (the common case) costs nothing: a solve only rewrites its program when
    /// one is present.
    pub leaf_off: Vec<(usize, u32)>,
    /// The converse of [`Self::leaf_off`]: elements switched back on alone
    /// (`obj.a[i].rand_mode(1)`) while their array property is off, same pair
    /// encoding. A pair here is a deviation from the property's mode, so it only
    /// exists while that mode is off (LRM 18.8: a whole-property call sets every
    /// element too, which clears both lists for it).
    pub leaf_on: Vec<(usize, u32)>,
}

struct ObjEntry {
    version: u32,
    template: ClassTemplateId,
    refcount: u32,
    fields: Box<[u64]>,
    prng_seed: u64,
    rand_meta: RandMeta,
    /// The `randc` cycle state of each `randc` field this object *owns*, keyed
    /// by the field's word offset (LRM 18.4.2). An instance `randc` variable's
    /// state lives in its object; a `static randc` variable's lives in the
    /// class's static-property singleton object, so every instance shares it.
    /// Absent until the variable is first drawn.
    randc: HashMap<usize, RandcState>,
    /// The word offsets of this object's `static` `rand`/`randc` properties
    /// that `rand_mode(0)` switched off (LRM 18.8: a static variable's mode is
    /// static, shared by every instance). Meaningful on a class's
    /// static-property singleton object only; the rest of the program reads it
    /// there ([`static_rand_mode`]).
    static_rand_off: HashSet<usize>,
    /// The ordinals of the constraint blocks `constraint_mode(0)` switched off
    /// (LRM 18.9), in the numbering of the class's [`Program`] block table. On
    /// an instance, its non-static blocks; on a static-property singleton, the
    /// `static` blocks (whose mode is shared by every instance, 18.5.10).
    ///
    /// [`Program`]: crate::constraints::registry::Program
    constraint_off: HashSet<u32>,
}

struct Table {
    /// Index 0 is unused (handle 0 is the null object reference, §8.4).
    entries: Vec<Option<ObjEntry>>,
    /// Each slot's last version, so a reused slot never repeats a handle —
    /// this is the one field that makes a stale weak handle detectable
    /// (this module's own doc comment).
    versions: Vec<u32>,
    free: Vec<u32>,
}

fn table() -> &'static Mutex<Table> {
    static T: OnceLock<Mutex<Table>> = OnceLock::new();
    T.get_or_init(|| {
        Mutex::new(Table {
            entries: vec![None],
            versions: vec![0],
            free: Vec::new(),
        })
    })
}

/// Per-[`ClassTemplateId`] metadata [`release`]/[`is_a`] consult — see this
/// module's doc comment on why this is a registry, not a call-site
/// parameter.
#[derive(Default, Clone)]
struct TemplateInfo {
    handle_fields: Vec<FieldSlot>,
    /// The one-word fields that hold a queue / dynamic / associative array
    /// handle ([`register_collection_fields`]): freed with the object and
    /// cloned by [`copy`], through [`crate::collections`] outside this
    /// module's lock (that module's lock order is collections then objects).
    collection_fields: Vec<FieldSlot>,
    /// The handles held inside struct / fixed-array properties, at a bit offset
    /// of their property ([`register_nested_handles`]): released with the
    /// object, cloned or retained by [`copy`].
    nested_handles: Vec<NestedHandle>,
    /// Self + every ancestor ([`is_a`]'s backing set) — always contains at
    /// least the template's own id once registered; see
    /// [`register_ancestors`].
    ancestors: HashSet<ClassTemplateId>,
    /// The template's `rand`/`randc` properties ([`register_rand_props`]).
    rand_props: Vec<RandProp>,
}

fn registry() -> &'static Mutex<HashMap<ClassTemplateId, TemplateInfo>> {
    static R: OnceLock<Mutex<HashMap<ClassTemplateId, TemplateInfo>>> = OnceLock::new();
    R.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Registers (idempotently — a later call replaces, never merges, an
/// earlier one for the same template) the ordered list of `template`'s own
/// non-static fields that are themselves class handles, consumed by
/// [`release`]'s recursive free walk. Task 3 stub (this task's own tests
/// call it directly with a hand-built list); Task 5 wires in the real
/// `ObjectLayout`-derived list once that type exists.
pub fn register_handle_fields(template: ClassTemplateId, slots: Vec<FieldSlot>) {
    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
    r.entry(template).or_default().handle_fields = slots;
}

/// Registers (same discipline as [`register_handle_fields`]) the ordered
/// list of `template`'s own non-static fields that hold a collection handle
/// (a queue, dynamic array or associative array; ledger XC-059): [`release`]
/// frees each such collection when its object dies and [`copy`] gives the new
/// object its own copy-on-write clone (LRM 8.12: a shallow copy of a
/// collection property is a value copy, never an alias).
pub fn register_collection_fields(template: ClassTemplateId, slots: Vec<FieldSlot>) {
    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
    r.entry(template).or_default().collection_fields = slots;
}

/// Registers (same discipline as [`register_handle_fields`]) the handles
/// `template`'s struct and fixed-array properties hold at a bit offset of their
/// value (ledger XC-059): a class handle or collection nested in an unpacked
/// struct field or array element. [`release`] frees each when its object dies
/// and [`copy`] retains each object / clones each collection, exactly as for
/// a whole-property handle.
pub fn register_nested_handles(template: ClassTemplateId, nested: Vec<NestedHandle>) {
    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
    r.entry(template).or_default().nested_handles = nested;
}

/// Registers (idempotently, same discipline as
/// [`register_handle_fields`]) the ancestor-closure set [`is_a`] consults:
/// `template` itself plus every base class and every flattened interface.
/// Task 3 stub (this task's own tests call it directly with a hand-built
/// set); Task 10 wires in the real `netlist::classes::base_chain`/
/// `flattened_interfaces`-derived computation.
pub fn register_ancestors(template: ClassTemplateId, mut ancestors: HashSet<ClassTemplateId>) {
    ancestors.insert(template);
    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
    r.entry(template).or_default().ancestors = ancestors;
}

/// Registers (idempotently, same discipline as [`register_handle_fields`])
/// `template`'s `rand`/`randc` properties, base-class properties first. Every
/// object allocated afterwards starts with one active `rand_mode` bit per entry
/// ([`RandMeta`]).
pub fn register_rand_props(template: ClassTemplateId, props: Vec<RandProp>) {
    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
    r.entry(template).or_default().rand_props = props;
}

/// One class template's registered runtime metadata as plain data: what a design
/// image carries so a runner that never saw the class declarations can
/// register the same templates ([`template_snapshot`], [`preload_templates`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TemplateSnapshot {
    pub id: ClassTemplateId,
    pub handle_fields: Vec<FieldSlot>,
    pub collection_fields: Vec<FieldSlot>,
    pub nested_handles: Vec<NestedHandle>,
    /// [`register_ancestors`]'s set, ascending by id (a set has no order of its
    /// own; the image must encode deterministically).
    pub ancestors: Vec<ClassTemplateId>,
    pub rand_props: Vec<RandProp>,
}

/// The registered metadata of each template in `ids`, ascending by id and
/// without repeats. A template nothing was registered for is skipped: it has no
/// handle fields, no ancestors and no `rand` properties, which is what an
/// absent entry already means.
pub fn template_snapshot(ids: &[ClassTemplateId]) -> Vec<TemplateSnapshot> {
    let mut ids = ids.to_vec();
    ids.sort_by_key(|i| i.0);
    ids.dedup();
    let r = registry().lock().unwrap_or_else(|e| e.into_inner());
    ids.into_iter()
        .filter_map(|id| {
            let info = r.get(&id)?;
            let mut ancestors: Vec<ClassTemplateId> = info.ancestors.iter().copied().collect();
            ancestors.sort_by_key(|i| i.0);
            Some(TemplateSnapshot {
                id,
                handle_fields: info.handle_fields.clone(),
                collection_fields: info.collection_fields.clone(),
                nested_handles: info.nested_handles.clone(),
                ancestors,
                rand_props: info.rand_props.clone(),
            })
        })
        .collect()
}

/// Registers every template of `snapshot` ([`template_snapshot`]'s inverse), each
/// replacing what was registered for its id.
pub fn preload_templates(snapshot: &[TemplateSnapshot]) {
    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
    for t in snapshot {
        let info = r.entry(t.id).or_default();
        info.handle_fields = t.handle_fields.clone();
        info.collection_fields = t.collection_fields.clone();
        info.nested_handles = t.nested_handles.clone();
        info.ancestors = t.ancestors.iter().copied().collect();
        info.rand_props = t.rand_props.clone();
    }
}

/// `template`'s registered `rand`/`randc` properties (empty for a template
/// with none, or none registered).
pub fn rand_props(template: ClassTemplateId) -> Vec<RandProp> {
    registry()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&template)
        .map(|info| info.rand_props.clone())
        .unwrap_or_default()
}

fn index(h: u64) -> usize {
    (h & 0xffff_ffff) as usize
}

fn version_of(h: u64) -> u32 {
    (h >> 32) as u32
}

impl Table {
    fn alloc(&mut self, template: ClassTemplateId, field_words: usize) -> u64 {
        let i = match self.free.pop() {
            Some(i) => i as usize,
            None => {
                self.entries.push(None);
                self.versions.push(0);
                self.entries.len() - 1
            }
        };
        let version = self.versions[i].wrapping_add(1);
        self.versions[i] = version;
        // Lock order table -> registry, the same as `release`.
        let rand_mode = vec![
            true;
            registry()
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .get(&template)
                .map_or(0, |info| info.rand_props.len())
        ];
        self.entries[i] = Some(ObjEntry {
            version,
            template,
            refcount: 1,
            fields: vec![0u64; field_words].into(),
            prng_seed: 0,
            rand_meta: RandMeta {
                rand_mode,
                leaf_off: Vec::new(),
                leaf_on: Vec::new(),
            },
            randc: HashMap::new(),
            static_rand_off: HashSet::new(),
            constraint_off: HashSet::new(),
        });
        (u64::from(version) << 32) | i as u64
    }

    /// The live entry `h` addresses, or `None` if `h` is the null handle, an
    /// out-of-range index, a freed slot, or a stale version (the
    /// weak-reference staleness check — this module's doc comment).
    fn get(&self, h: u64) -> Option<&ObjEntry> {
        let i = index(h);
        if i == 0 {
            return None;
        }
        let e = self.entries.get(i)?.as_ref()?;
        (e.version == version_of(h)).then_some(e)
    }

    fn get_mut(&mut self, h: u64) -> Option<&mut ObjEntry> {
        let i = index(h);
        if i == 0 {
            return None;
        }
        let v = version_of(h);
        let e = self.entries.get_mut(i)?.as_mut()?;
        (e.version == v).then_some(e)
    }
}

/// Allocates a new object of `template` with `field_words` words of
/// zero-initialized field storage, refcount 1. §1.1's target signature takes
/// `layout: &ObjectLayout` instead of a bare word count — `ObjectLayout`
/// does not exist until Task 5, so this task takes the one piece of it
/// `alloc` itself actually needs; Task 5 adapts call sites to pass
/// `layout.total_words()` (or equivalent) once that type exists, with no
/// further change to this function's behavior.
pub fn alloc(template: ClassTemplateId, field_words: usize) -> u64 {
    ALLOCS_SINCE_GC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let h = table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .alloc(template, field_words);
    if let Some(hook) = CREATE_HOOK.get() {
        hook(h);
    }
    h
}

/// Observers of object lifetimes (the VPI's `cbCreateObj`, `cbReclaimObj`,
/// `cbEndOfObject`, IEEE 1800-2023 38.36.1): `create` hears every new object
/// (its constructor has yet to run: the observer reports it later), and
/// `reclaim` every object about to be freed, while it is still whole (no
/// table lock is held, so it may read the object). Set once; until then
/// alloc and release pay one atomic load.
static CREATE_HOOK: std::sync::OnceLock<fn(u64)> = std::sync::OnceLock::new();
static RECLAIM_HOOK: std::sync::OnceLock<fn(u64)> = std::sync::OnceLock::new();

/// Installs the lifetime observers (see [`CREATE_HOOK`]); a second call is a
/// no-op.
pub fn set_lifecycle_hooks(create: fn(u64), reclaim: fn(u64)) {
    let _ = CREATE_HOOK.set(create);
    let _ = RECLAIM_HOOK.set(reclaim);
}

/// `+1` reference. A null (`0`) or already-stale handle is silently a
/// no-op: `retain`/`release` are only ever called by codegen on a handle a
/// variable/field/collection element already holds, and a null handle holds
/// nothing to retain.
pub fn retain(h: u64) {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    if let Some(e) = t.get_mut(h) {
        // Saturating: a count that reached `u32::MAX` stays there (the object
        // is leaked, never freed early), rather than wrapping to 0.
        e.refcount = e.refcount.saturating_add(1);
    }
}

/// `-1` reference; at `0`, recursively [`release`]s every field
/// [`register_handle_fields`] named as itself a class handle, then frees the
/// slot (its index returns to the free list; its `version` counter is left
/// alone, so the NEXT `alloc` at that index bumps it again and no future
/// handle ever collides with this one — see this module's doc comment on
/// weak-reference staleness). A null or already-stale handle is a no-op, the
/// same as [`retain`].
pub fn release(h: u64) {
    // A worklist, not recursion: a long chain of objects (a linked list of
    // a million nodes) is freed by one release of its head, and must not
    // overflow the stack doing so.
    let mut pending = vec![h];
    let mut freed = false;
    // Collection handles of the freed objects, released after the loop: a
    // collection's drop releases the objects it holds, so freeing one while
    // holding this table's lock would invert the lock order (collections
    // first, then objects).
    let mut colls: Vec<u64> = Vec::new();
    while let Some(h) = pending.pop() {
        {
            let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
            let Some(e) = t.get_mut(h) else { continue };
            e.refcount = e.refcount.saturating_sub(1);
            if e.refcount > 0 {
                continue;
            }
        }
        // About to be reclaimed: an observer sees it whole, with no lock held.
        if let Some(hook) = RECLAIM_HOOK.get() {
            hook(h);
        }
        let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
        let Some(e) = t.get_mut(h) else { continue };
        // The observer took a reference: the object lives on.
        if e.refcount > 0 {
            continue;
        }
        let template = e.template;
        {
            let r = registry().lock().unwrap_or_else(|e| e.into_inner());
            if let Some(info) = r.get(&template) {
                for slot in &info.handle_fields {
                    if let Some(&w) = e.fields.get(slot.offset) {
                        pending.push(w);
                    }
                }
                for slot in &info.collection_fields {
                    if let Some(&w) = e.fields.get(slot.offset) {
                        colls.push(w);
                    }
                }
                for nh in &info.nested_handles {
                    if let Some(w) = nested_get(&e.fields, nh) {
                        if nh.coll {
                            colls.push(w);
                        } else {
                            pending.push(w);
                        }
                    }
                }
            }
        }
        let i = index(h);
        t.entries[i] = None;
        t.free.push(i as u32);
        freed = true;
    }
    for c in colls {
        crate::collections::release(c);
    }
    // A freed object is what makes a `weak_reference` to it read null (LRM
    // 8.30.3: `wait (weak.get() == null)`); wake the waiters on object state.
    // Every table lock is released here.
    if freed {
        crate::sched::notify_object_state_change();
    }
}

/// LRM 1800-2023 §8.12 shallow copy (`new obj`): a new object (refcount 1,
/// the caller's reference) of `h`'s DYNAMIC template -- not the handle's
/// static type -- holding a word-for-word copy of its fields, each field that
/// is itself a handle [`retain`]ed (the copy and the original now both name
/// the nested object: it is shared, not duplicated). The constructor is not
/// run. The copy's `randc` variables start a fresh cycle (a permutation in
/// progress is the original's history, not part of its value). `None` for a null or stale `h` (§8.12 leaves a null source
/// undefined; the caller decides).
pub fn copy(h: u64) -> Option<u64> {
    // Phase 1 (objects lock): what to copy. Collections are cloned in phase 2,
    // outside the lock, so the lock order stays collections -> objects.
    let (template, fields, rand_meta, constraint_off, prng_seed, colls, nested_hs) = {
        let t = table().lock().unwrap_or_else(|e| e.into_inner());
        let src = t.get(h)?;
        let (colls, nested_hs): (Vec<usize>, Vec<NestedHandle>) = registry()
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&src.template)
            .map(|info| {
                (
                    info.collection_fields.iter().map(|s| s.offset).collect(),
                    info.nested_handles.clone(),
                )
            })
            .unwrap_or_default();
        (
            src.template,
            src.fields.clone(),
            src.rand_meta.clone(),
            src.constraint_off.clone(),
            src.prng_seed,
            colls,
            nested_hs,
        )
    };
    let mut fields = fields;
    for off in colls {
        if let Some(w) = fields.get_mut(off) {
            *w = crate::collections::clone(*w);
        }
    }
    // A collection inside a struct or array property is cloned the same way,
    // written back at its bit offset; an object inside one is retained below.
    let mut nested_objs: Vec<u64> = Vec::new();
    for nh in &nested_hs {
        let Some(w) = nested_get(&fields, nh) else {
            continue;
        };
        if nh.coll {
            nested_set(&mut fields, nh, crate::collections::clone(w));
        } else {
            nested_objs.push(w);
        }
    }
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let mut nested: Vec<u64> = registry()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&template)
        .map(|info| {
            info.handle_fields
                .iter()
                .filter_map(|s| fields.get(s.offset).copied())
                .collect()
        })
        .unwrap_or_default();
    nested.extend(nested_objs);
    let new = t.alloc(template, fields.len());
    for n in nested {
        if let Some(e) = t.get_mut(n) {
            e.refcount = e.refcount.saturating_add(1);
        }
    }
    if let Some(e) = t.get_mut(new) {
        e.fields = fields;
        e.rand_meta = rand_meta;
        e.constraint_off = constraint_off;
        e.prng_seed = prng_seed;
    }
    drop(t);
    // A shallow copy is a new object too (38.36.1 cbCreateObj).
    if let Some(hook) = CREATE_HOOK.get() {
        hook(new);
    }
    Some(new)
}

/// The number of objects currently alive (allocated and not yet freed by
/// their last [`release`]) -- the observable of reference counting: a
/// design that drops every handle it took must bring this back to where it
/// started, and one that over-releases would already have printed a stale
/// read, so a leak and a use-after-free are both visible from outside.
pub fn live_count() -> usize {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .entries
        .iter()
        .filter(|e| e.is_some())
        .count()
}

/// `h`'s current reference count (`None` for a null or stale handle) --
/// test-only observation of the retain/release discipline.
pub fn refcount(h: u64) -> Option<u32> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| e.refcount)
}

/// Reads field `slot` of the live object `h` into `out` (as many words as
/// `slot.words`/`out` both have room for); `false` (leaving `out` alone) for
/// a null, stale, or out-of-range handle/slot.
pub fn field_get(h: u64, slot: FieldSlot, out: &mut [u64]) -> bool {
    let t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get(h) else { return false };
    if slot.offset + slot.words > e.fields.len() {
        return false;
    }
    let n = out.len().min(slot.words);
    out[..n].copy_from_slice(&e.fields[slot.offset..slot.offset + n]);
    true
}

/// Writes field `slot` of the live object `h` from `val`; a null, stale, or
/// out-of-range handle/slot is a no-op (no live storage exists to write) that
/// returns `false`, so the caller can report the access (LRM 1800-2023 8.4: a
/// member of a `null` handle is a run-time error). `true` when it wrote.
pub fn field_set(h: u64, slot: FieldSlot, val: &[u64]) -> bool {
    let changed = {
        let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
        let Some(e) = t.get_mut(h) else { return false };
        if slot.offset + slot.words > e.fields.len() {
            return false;
        }
        let n = val.len().min(slot.words);
        let dest = &mut e.fields[slot.offset..slot.offset + n];
        let changed = dest != &val[..n];
        dest.copy_from_slice(&val[..n]);
        changed
    };
    // A `wait (obj.prop == v)` / `wait (weak.get() == null)` sleeps on object
    // state, which no signal change reports. The table lock is released.
    if changed {
        crate::sched::notify_object_state_change();
    }
    true
}

/// Replaces the `mask` bits of the words at `offset` of the live object `h` with
/// those of `val` (a staged nonblocking write of a class property, LRM
/// 1800-2023 10.4.2); `false` for a dead handle or out-of-range span. Wakes
/// `wait`ers when the property changed, like [`field_set`].
pub fn field_merge(h: u64, offset: usize, val: &[u64], mask: &[u64]) -> bool {
    let changed = {
        let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
        let Some(e) = t.get_mut(h) else { return false };
        let n = val.len().min(mask.len());
        if offset + n > e.fields.len() {
            return false;
        }
        let mut changed = false;
        for i in 0..n {
            let old = e.fields[offset + i];
            let new = (old & !mask[i]) | (val[i] & mask[i]);
            changed |= new != old;
            e.fields[offset + i] = new;
        }
        changed
    };
    if changed {
        crate::sched::notify_object_state_change();
    }
    true
}

/// Reads the leaf `win` of property `slot` of the live object `h`: its value
/// into `val` and its unknown bits into `unk` (each `ceil(width/64)` words);
/// `false` (leaving both alone) for a null, stale or out-of-range handle/slot.
pub fn field_get_window(
    h: u64,
    slot: FieldSlot,
    win: Window,
    val: &mut [u64],
    unk: &mut [u64],
) -> bool {
    let t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get(h) else { return false };
    if slot.offset + slot.words > e.fields.len() {
        return false;
    }
    win.read(&e.fields[slot.offset..slot.offset + slot.words], val, unk);
    true
}

/// Writes the leaf `win` of property `slot` of the live object `h` as the known
/// value `val`, leaving the rest of the property alone; like [`field_set`] it is
/// a no-op returning `false` for a dead handle or bad slot, and it wakes
/// `wait`ers when the property changed.
pub fn field_set_window(h: u64, slot: FieldSlot, win: Window, val: &[u64]) -> bool {
    let changed = {
        let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
        let Some(e) = t.get_mut(h) else { return false };
        if slot.offset + slot.words > e.fields.len() {
            return false;
        }
        let dest = &mut e.fields[slot.offset..slot.offset + slot.words];
        let before = dest.to_vec();
        win.write(dest, val);
        before != dest
    };
    if changed {
        crate::sched::notify_object_state_change();
    }
    true
}

/// Whether `h` names a live object: not null, not freed, and not a stale
/// handle to a slot a later object now occupies (the version check of this
/// module's doc comment). This is the whole of `weak_reference#(T)::get()`
/// (LRM 1800-2023 8.30.3): a weak reference stores the referent's bare handle
/// bits without retaining it, and is "cleared" exactly when this turns false.
pub fn is_live(h: u64) -> bool {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .is_some()
}

/// The slot index of `h` -- `weak_reference#(T)::get_id`'s value (LRM
/// 8.30.5): nonzero for every real object (index 0 is the null handle's),
/// shared by every handle to one object whatever its static type, unique among
/// the objects alive at once (one slot each), and reusable after the object is
/// freed (which 8.30.5 explicitly allows). `0` for the null handle.
pub fn slot_index(h: u64) -> u64 {
    index(h) as u64
}

/// `h`'s dynamic (runtime) class — `None` for a null or stale handle.
pub fn dynamic_template(h: u64) -> Option<ClassTemplateId> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| e.template)
}

/// `$cast`'s runtime check (6.24.2/8.16): whether `h`'s dynamic class is
/// `dest` or one of `dest`'s descendants/implementors in the sense that
/// matters for a cast — concretely, whether `dest` is in `h`'s dynamic
/// template's own registered ancestor-or-self closure
/// ([`register_ancestors`]). A null/stale handle, or a dynamic template with
/// nothing registered for it yet, is never `is_a` anything (including
/// itself) — an unregistered template legitimately means "no class/interface
/// hierarchy information is available yet", not "matches everything".
pub fn is_a(h: u64, dest: ClassTemplateId) -> bool {
    let Some(template) = dynamic_template(h) else {
        return false;
    };
    template_is_a(template, dest)
}

/// [`is_a`] for a template rather than an object: whether `dest` is in
/// `template`'s registered ancestor-or-self closure. A compile-time query (a
/// call site asks which registered classes could be the dynamic class behind
/// a static one).
pub fn template_is_a(template: ClassTemplateId, dest: ClassTemplateId) -> bool {
    registry()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&template)
        .is_some_and(|info| info.ancestors.contains(&dest))
}

/// `h`'s object-stability PRNG seed (§18.14.3) — `None` for a null/stale
/// handle. [`alloc`] leaves it `0`; the runtime's `Alloc` op draws the real
/// value from the creating process's RNG cell at `new`-time (LRM 18.14.2) and
/// stores it here.
pub fn prng_seed(h: u64) -> Option<u64> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| e.prng_seed)
}

/// Sets `h`'s object-stability PRNG seed; a no-op on a null/stale handle.
pub fn set_prng_seed(h: u64, seed: u64) {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    if let Some(e) = t.get_mut(h) {
        e.prng_seed = seed;
    }
}

/// `h`'s `rand`/`randc` metadata (a clone — `None` for a null/stale handle).
pub fn rand_meta(h: u64) -> Option<RandMeta> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| e.rand_meta.clone())
}

/// Replaces `h`'s `rand`/`randc` metadata; a no-op on a null/stale handle.
pub fn set_rand_meta(h: u64, meta: RandMeta) {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    if let Some(e) = t.get_mut(h) {
        e.rand_meta = meta;
    }
}

/// Objects allocated since the last [`collect_cycles`] (see
/// [`maybe_collect_cycles`]).
static ALLOCS_SINCE_GC: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Frees every object that only other objects reference -- the reference
/// cycles reference counting alone never frees (LRM 1800-2023 §8.29: an
/// object no handle outside the heap can reach is reclaimed). Returns how
/// many objects were freed.
///
/// Trial deletion over the whole heap: an object's references from other
/// objects' handle fields are counted; one whose reference count exceeds
/// that is held from outside (a variable, a process, a collection, a
/// mailbox) and is a root; everything reachable from a root through handle
/// fields is live, and the rest is garbage. A garbage object's references to
/// live objects are dropped before it is freed, so every count stays exact.
/// A reference held by a collection element counts as outside the heap, so
/// a cycle through a collection is (conservatively) never freed.
pub fn collect_cycles() -> usize {
    let freed = collect_cycles_locked();
    COLLECTED.fetch_add(freed, std::sync::atomic::Ordering::Relaxed);
    freed
}

/// Every object [`collect_cycles`] has freed in this process.
static COLLECTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// How many objects [`collect_cycles`] has freed in this process.
pub fn collected_count() -> usize {
    COLLECTED.load(std::sync::atomic::Ordering::Relaxed)
}

fn collect_cycles_locked() -> usize {
    ALLOCS_SINCE_GC.store(0, std::sync::atomic::Ordering::Relaxed);
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let r = registry().lock().unwrap_or_else(|e| e.into_inner());
    let handle_fields = |e: &ObjEntry| -> Vec<u64> {
        r.get(&e.template)
            .map(|info| {
                info.handle_fields
                    .iter()
                    .filter_map(|s| e.fields.get(s.offset).copied())
                    .collect()
            })
            .unwrap_or_default()
    };
    let live: Vec<u64> = t
        .entries
        .iter()
        .enumerate()
        .filter_map(|(i, e)| e.as_ref().map(|e| (u64::from(e.version) << 32) | i as u64))
        .collect();
    let mut internal: HashMap<usize, u32> = HashMap::new();
    for &h in &live {
        let Some(e) = t.get(h) else { continue };
        for w in handle_fields(e) {
            if t.get(w).is_some() {
                *internal.entry(index(w)).or_default() += 1;
            }
        }
    }
    let mut marked: HashSet<usize> = HashSet::new();
    let mut stack: Vec<u64> = live
        .iter()
        .copied()
        .filter(|&h| {
            t.get(h)
                .is_some_and(|e| e.refcount > internal.get(&index(h)).copied().unwrap_or(0))
        })
        .collect();
    while let Some(h) = stack.pop() {
        if !marked.insert(index(h)) {
            continue;
        }
        if let Some(e) = t.get(h) {
            stack.extend(handle_fields(e).into_iter().filter(|&w| t.get(w).is_some()));
        }
    }
    let garbage: Vec<u64> = live
        .into_iter()
        .filter(|&h| !marked.contains(&index(h)))
        .collect();
    let mut drops: Vec<u64> = Vec::new();
    for &g in &garbage {
        if let Some(e) = t.get(g) {
            drops.extend(
                handle_fields(e)
                    .into_iter()
                    .filter(|w| marked.contains(&index(*w))),
            );
        }
    }
    for w in drops {
        if let Some(e) = t.get_mut(w) {
            e.refcount = e.refcount.saturating_sub(1);
        }
    }
    for &g in &garbage {
        let i = index(g);
        t.entries[i] = None;
        t.free.push(i as u32);
    }
    garbage.len()
}

/// Runs [`collect_cycles`] once enough objects have been allocated since the
/// last collection to make it worthwhile (at least 4096, and at least as
/// many as are alive), so its cost stays proportional to allocation.
pub fn maybe_collect_cycles() -> usize {
    let since = ALLOCS_SINCE_GC.load(std::sync::atomic::Ordering::Relaxed);
    // Against what the last collection left alive, not today's count: that
    // includes the garbage allocated since, and would never be caught up.
    if since < 4096 || since < LIVE_AFTER_GC.load(std::sync::atomic::Ordering::Relaxed) {
        return 0;
    }
    let freed = collect_cycles();
    LIVE_AFTER_GC.store(live_count(), std::sync::atomic::Ordering::Relaxed);
    freed
}

/// The live object count right after the last [`maybe_collect_cycles`]
/// collection.
static LIVE_AFTER_GC: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Whether the `rand`/`randc` property at word `offset` of `h` is active
/// (`rand_mode()`, LRM 18.8). `None` for a null/stale handle or an `offset` that
/// is no `rand` property of `h`'s class.
pub fn rand_mode_of(h: u64, offset: usize) -> Option<bool> {
    let t = table().lock().unwrap_or_else(|e| e.into_inner());
    let e = t.get(h)?;
    let i = rand_prop_index(e.template, offset)?;
    e.rand_meta.rand_mode.get(i).copied()
}

/// Sets the `rand_mode()` of the `rand`/`randc` property at word `offset` of
/// `h`. `false` (changing nothing) for a null/stale handle or an `offset` that
/// is no `rand` property of `h`'s class.
pub fn set_rand_mode_of(h: u64, offset: usize, on: bool) -> bool {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get_mut(h) else { return false };
    let Some(i) = rand_prop_index(e.template, offset) else {
        return false;
    };
    match e.rand_meta.rand_mode.get_mut(i) {
        Some(bit) => {
            *bit = on;
            // A whole-property call sets every element too (LRM 18.8).
            e.rand_meta.leaf_off.retain(|&(p, _)| p != i);
            e.rand_meta.leaf_on.retain(|&(p, _)| p != i);
            true
        }
        None => false,
    }
}

/// `obj.v[i].rand_mode()` (LRM 18.8): whether the element at value bit `bit` of
/// the `rand` array property at word `offset` of `h` is active, i.e. its
/// property is and the element was not switched off alone. `None` as
/// [`rand_mode_of`].
pub fn leaf_rand_mode_of(h: u64, offset: usize, bit: u32) -> Option<bool> {
    let t = table().lock().unwrap_or_else(|e| e.into_inner());
    let e = t.get(h)?;
    let i = rand_prop_index(e.template, offset)?;
    let on = *e.rand_meta.rand_mode.get(i)?;
    let m = &e.rand_meta;
    Some(if on {
        !m.leaf_off.contains(&(i, bit))
    } else {
        m.leaf_on.contains(&(i, bit))
    })
}

/// `obj.v[i].rand_mode(on)`: switches the one element at value bit `bit` of the
/// array property at word `offset` of `h`. `false` as [`set_rand_mode_of`].
pub fn set_leaf_rand_mode_of(h: u64, offset: usize, bit: u32, on: bool) -> bool {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get_mut(h) else { return false };
    let Some(i) = rand_prop_index(e.template, offset) else {
        return false;
    };
    let m = &mut e.rand_meta;
    if i >= m.rand_mode.len() {
        return false;
    }
    m.leaf_off.retain(|&k| k != (i, bit));
    m.leaf_on.retain(|&k| k != (i, bit));
    // Only a deviation from the property's own mode is recorded.
    if m.rand_mode[i] && !on {
        m.leaf_off.push((i, bit));
    } else if !m.rand_mode[i] && on {
        m.leaf_on.push((i, bit));
    }
    true
}

/// `obj.rand_mode(on)` with no variable (LRM 18.8): every `rand`/`randc`
/// property of `h` (its own, not those of the objects it holds). `false` for a
/// null/stale handle.
pub fn set_all_rand_modes(h: u64, on: bool) -> bool {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get_mut(h) else { return false };
    e.rand_meta.rand_mode.iter_mut().for_each(|b| *b = on);
    e.rand_meta.leaf_off.clear();
    e.rand_meta.leaf_on.clear();
    true
}

/// The index of the property at word `offset` among `template`'s `rand`
/// properties (the index into [`RandMeta::rand_mode`]).
fn rand_prop_index(template: ClassTemplateId, offset: usize) -> Option<usize> {
    registry()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&template)?
        .rand_props
        .iter()
        .position(|p| p.slot.offset == offset)
}

/// Whether the `static` `rand` property at word `offset` of the static-property
/// object `h` is active (LRM 18.8: its mode is shared by every instance).
/// `None` for a null/stale handle.
pub fn static_rand_mode(h: u64, offset: usize) -> Option<bool> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| !e.static_rand_off.contains(&offset))
}

/// Sets the mode of the `static` `rand` property at word `offset` of the
/// static-property object `h`; `false` for a null/stale handle.
pub fn set_static_rand_mode(h: u64, offset: usize, on: bool) -> bool {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get_mut(h) else { return false };
    if on {
        e.static_rand_off.remove(&offset);
    } else {
        e.static_rand_off.insert(offset);
    }
    true
}

/// Whether constraint block `ordinal` held by `h` (an instance's own block, or a
/// static-property object's `static` block) is active (LRM 18.9: all start
/// active). `None` for a null/stale handle.
pub fn constraint_mode_of(h: u64, ordinal: u32) -> Option<bool> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| !e.constraint_off.contains(&ordinal))
}

/// The class-key -> static-singleton template map, filled by the compiler as
/// it hands out each class's static-property singleton id, so a run-time
/// observer (VPI) can find a class's singleton without the compiler's state.
fn static_singleton_keys() -> &'static Mutex<HashMap<String, ClassTemplateId>> {
    static K: OnceLock<Mutex<HashMap<String, ClassTemplateId>>> = OnceLock::new();
    K.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Records that class specialization `key` (`class_specialization_key`) keeps
/// its `static` properties and blocks in singleton objects of `template`.
pub fn register_static_singleton_key(key: &str, template: ClassTemplateId) {
    static_singleton_keys()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .insert(key.to_owned(), template);
}

/// Every registered `(class key, singleton template id)` pair, sorted by key:
/// what an AOT image carries so a precompiled run can answer
/// [`static_singleton_of`] without the compiler having run.
pub fn static_singleton_key_pairs() -> Vec<(String, u32)> {
    let mut v: Vec<(String, u32)> = static_singleton_keys()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .map(|(k, t)| (k.clone(), t.0))
        .collect();
    v.sort();
    v
}

/// The live static-property singleton of the class with specialization `key`:
/// `None` when the compiler never registered the key, `Some(None)` when no
/// singleton has been allocated yet (nothing has touched the class's statics,
/// so every static mode still has its default). LRM 18.5.10, 18.9.
pub fn static_singleton_of(key: &str) -> Option<Option<u64>> {
    let template = *static_singleton_keys()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(key)?;
    let t = table().lock().unwrap_or_else(|e| e.into_inner());
    Some(t.entries.iter().enumerate().find_map(|(i, e)| {
        let e = e.as_ref()?;
        (e.template == template).then(|| (u64::from(e.version) << 32) | i as u64)
    }))
}

/// Sets the mode of constraint block `ordinal` held by `h`; `false` for a
/// null/stale handle.
pub fn set_constraint_mode_of(h: u64, ordinal: u32, on: bool) -> bool {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get_mut(h) else { return false };
    if on {
        e.constraint_off.remove(&ordinal);
    } else {
        e.constraint_off.insert(ordinal);
    }
    true
}

/// The `randc` cycle state of the field at word `offset` of `h` (a clone; the
/// default, not-yet-drawn state if it has none). `None` for a null/stale
/// handle.
pub fn randc_state(h: u64, offset: usize) -> Option<RandcState> {
    table()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(h)
        .map(|e| e.randc.get(&offset).cloned().unwrap_or_default())
}

/// Stores `h`'s `randc` cycle states, `(word offset, state)` each; `false`
/// (storing nothing) for a null/stale handle.
pub fn set_randc_states(h: u64, states: Vec<(usize, RandcState)>) -> bool {
    let mut t = table().lock().unwrap_or_else(|e| e.into_inner());
    let Some(e) = t.get_mut(h) else { return false };
    e.randc.extend(states);
    true
}

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

    // Every test below that touches the module-wide `registry()` (via
    // `register_handle_fields`/`register_ancestors`) or whose assertions
    // depend on exact handle/index values uses its own disjoint
    // `ClassTemplateId` range, never reused by another test in this file:
    // `table()`/`registry()` are process-wide statics shared by every test
    // in this module, and `cargo test` runs them concurrently by default.
    // Plain alloc/retain/release/field round-trips that only assert on
    // their OWN handle's contents are safe to share an id, since the
    // `Mutex` makes each individual table operation atomic and no test
    // reads another test's handle -- but nothing here does that, to keep
    // the independence obvious at a glance.

    #[test]
    fn is_live_tracks_release_and_rejects_a_stale_handle_after_slot_reuse() {
        assert!(!is_live(0), "the null handle is never live");
        let a = alloc(ClassTemplateId(1100), 0);
        assert!(is_live(a));
        release(a);
        assert!(!is_live(a), "a freed handle is not live");
        // Whatever other test allocates into the freed slot, the old handle's
        // version no longer matches.
        let b = alloc(ClassTemplateId(1101), 0);
        assert!(is_live(b));
        assert!(!is_live(a), "a stale handle must not alias the newcomer");
        release(b);
    }

    #[test]
    fn slot_index_is_nonzero_distinct_and_zero_for_null() {
        assert_eq!(slot_index(0), 0);
        let a = alloc(ClassTemplateId(1102), 0);
        let b = alloc(ClassTemplateId(1103), 0);
        assert_ne!(slot_index(a), 0);
        assert_ne!(slot_index(a), slot_index(b));
        release(a);
        release(b);
    }

    #[test]
    fn alloc_field_set_field_get_round_trips() {
        let h = alloc(ClassTemplateId(1000), 2);
        let slot0 = FieldSlot {
            offset: 0,
            words: 1,
        };
        let slot1 = FieldSlot {
            offset: 1,
            words: 1,
        };
        field_set(h, slot0, &[42]);
        field_set(h, slot1, &[7]);
        let mut out = [0u64];
        assert!(field_get(h, slot0, &mut out));
        assert_eq!(out, [42]);
        assert!(field_get(h, slot1, &mut out));
        assert_eq!(out, [7]);
        assert_eq!(dynamic_template(h), Some(ClassTemplateId(1000)));
    }

    #[test]
    fn two_retains_need_two_releases_before_the_slot_frees() {
        // A sentinel field value distinguishes "still a live slot with its
        // data intact" from "freed" (a freed slot's `field_get` fails
        // outright, never silently reading zeroed/reused memory).
        let h = alloc(ClassTemplateId(1001), 1);
        let slot = FieldSlot {
            offset: 0,
            words: 1,
        };
        field_set(h, slot, &[0xdead_beef]);
        retain(h); // refcount 2
        release(h); // refcount 1 -- still alive
        let mut out = [0u64];
        assert!(
            field_get(h, slot, &mut out),
            "one release of two retains must not free the slot"
        );
        assert_eq!(
            out,
            [0xdead_beef],
            "a leaked (still-referenced) slot's data is intact"
        );
        release(h); // refcount 0 -- now freed
        assert!(
            !field_get(h, slot, &mut out),
            "the second release must free the slot"
        );
    }

    #[test]
    fn releasing_an_object_recursively_releases_a_handle_field_it_points() {
        let pointee_template = ClassTemplateId(1002);
        let pointer_template = ClassTemplateId(1003);
        let pointee = alloc(pointee_template, 1);
        let pointer = alloc(pointer_template, 1);
        let handle_slot = FieldSlot {
            offset: 0,
            words: 1,
        };
        field_set(pointer, handle_slot, &[pointee]);
        register_handle_fields(pointer_template, vec![handle_slot]);

        retain(pointee); // the field store retained it: refcount 2 (alloc's 1 + this)
        assert_eq!(dynamic_template(pointee), Some(pointee_template));

        release(pointer); // refcount 0 -- frees pointer, and recursively releases pointee once
        let mut out = [0u64];
        assert!(
            field_get(pointee, handle_slot, &mut out),
            "pointee still has one more reference after the recursive release"
        );

        // Drop the remaining, direct reference: now it must actually free.
        release(pointee);
        assert!(!field_get(pointee, handle_slot, &mut out));
        assert_eq!(dynamic_template(pointee), None);
    }

    /// The single most important test in this task (plan's own words):
    /// built against a freshly constructed, test-local [`Table`] rather
    /// than the module-wide [`table`] singleton, so the free-list reuse this
    /// test depends on ("the index just freed is the next one `alloc`
    /// hands out") is deterministic and never raced by another test's
    /// concurrent allocations against the same shared global.
    #[test]
    fn a_stale_handle_after_its_slot_is_recycled_fails_field_get() {
        // Mirrors `table()`'s own initialization (index 0 pre-reserved for
        // the null handle) rather than a bare `Table::default()`, so this
        // local table obeys the same index-0-is-never-allocated invariant
        // the module-wide singleton does.
        let mut t = Table {
            entries: vec![None],
            versions: vec![0],
            free: Vec::new(),
        };
        let h1 = t.alloc(ClassTemplateId(0), 1);
        t.get_mut(h1).unwrap().fields[0] = 1;

        // Free h1's slot by hand (the public `release()` free-function also
        // does the recursive-children walk, which needs nothing here).
        let i = index(h1);
        t.entries[i] = None;
        t.free.push(i as u32);

        let h2 = t.alloc(ClassTemplateId(1), 1);
        assert_eq!(
            index(h1),
            index(h2),
            "the only freed slot in a fresh table is always the next one `alloc` reuses"
        );
        assert_ne!(
            h1, h2,
            "alloc must bump the recycled index's version, or the stale handle would still match"
        );
        assert!(
            t.get(h1).is_none(),
            "a stale (old_version, index) handle must fail to resolve once its slot is recycled"
        );
        let e2 = t
            .get(h2)
            .expect("the new object at the recycled index is live");
        assert_eq!(
            e2.fields[0], 0,
            "the new object's fields start zeroed -- never carrying over the old occupant's data"
        );
    }

    #[test]
    fn is_a_matches_self_and_registered_ancestors_only() {
        let base = ClassTemplateId(100);
        let derived = ClassTemplateId(101);
        let unrelated = ClassTemplateId(102);
        register_ancestors(derived, HashSet::from([base]));
        register_ancestors(base, HashSet::new());

        let h = alloc(derived, 0);
        assert!(
            is_a(h, derived),
            "an object is always is_a its own dynamic class"
        );
        assert!(is_a(h, base), "a derived object is_a its registered base");
        assert!(
            !is_a(h, unrelated),
            "is_a must not match a template that was never registered as an ancestor"
        );

        let base_h = alloc(base, 0);
        assert!(
            !is_a(base_h, derived),
            "is_a is one-directional: a base object is never is_a its derived class"
        );
    }

    #[test]
    fn retain_release_and_field_access_on_the_null_handle_are_safe_no_ops() {
        assert_eq!(dynamic_template(0), None);
        assert!(!is_a(0, ClassTemplateId(1004)));
        retain(0);
        release(0);
        let slot = FieldSlot {
            offset: 0,
            words: 1,
        };
        let mut out = [0u64];
        assert!(!field_get(0, slot, &mut out));
        field_set(0, slot, &[1]); // must not panic
    }

    #[test]
    fn prng_seed_and_rand_meta_round_trip_and_are_none_once_freed() {
        let h = alloc(ClassTemplateId(1005), 0);
        assert_eq!(
            prng_seed(h),
            Some(0),
            "freshly allocated, before any seeding hook runs"
        );
        set_prng_seed(h, 0x1234_5678);
        assert_eq!(prng_seed(h), Some(0x1234_5678));

        assert_eq!(
            rand_meta(h),
            Some(RandMeta::default()),
            "a template with no registered rand properties has no rand_mode bits"
        );
        set_rand_meta(
            h,
            RandMeta {
                rand_mode: vec![true, false],
                ..Default::default()
            },
        );
        assert_eq!(
            rand_meta(h),
            Some(RandMeta {
                rand_mode: vec![true, false],
                ..Default::default()
            })
        );

        release(h);
        assert_eq!(prng_seed(h), None);
        assert_eq!(rand_meta(h), None);
    }

    #[test]
    fn rand_props_are_template_level_and_every_object_starts_all_active() {
        let t = ClassTemplateId(1040);
        let a = RandProp {
            slot: FieldSlot {
                offset: 0,
                words: 1,
            },
            kind: RandKind::Rand,
        };
        let b = RandProp {
            slot: FieldSlot {
                offset: 2,
                words: 2,
            },
            kind: RandKind::RandC,
        };
        assert_eq!(rand_props(t), Vec::new(), "nothing registered yet");
        register_rand_props(t, vec![a, b]);
        assert_eq!(rand_props(t), vec![a, b]);
        let h1 = alloc(t, 4);
        let h2 = alloc(t, 4);
        let all_on = RandMeta {
            rand_mode: vec![true, true],
            ..Default::default()
        };
        assert_eq!(rand_meta(h1), Some(all_on.clone()));
        // The mutable part is per object: turning one property off on `h1`
        // does not touch `h2`, and a shallow copy carries it along.
        set_rand_meta(
            h1,
            RandMeta {
                rand_mode: vec![true, false],
                ..Default::default()
            },
        );
        assert_eq!(rand_meta(h2), Some(all_on));
        let dup = copy(h1).unwrap();
        assert_eq!(rand_meta(dup).unwrap().rand_mode, vec![true, false]);
        // Re-registering replaces, never merges.
        register_rand_props(t, vec![a]);
        assert_eq!(rand_props(t), vec![a]);
        let h3 = alloc(t, 4);
        assert_eq!(rand_meta(h3).unwrap().rand_mode, vec![true]);
        for h in [h1, h2, h3, dup] {
            release(h);
        }
    }

    fn one_word(offset: usize) -> FieldSlot {
        FieldSlot { offset, words: 1 }
    }

    #[test]
    fn refcount_tracks_retain_and_release_and_is_none_when_dead() {
        let h = alloc(ClassTemplateId(1006), 1);
        assert_eq!(refcount(h), Some(1));
        retain(h);
        assert_eq!(refcount(h), Some(2));
        release(h);
        assert_eq!(refcount(h), Some(1));
        release(h);
        assert_eq!(refcount(h), None, "a freed handle has no count");
        assert_eq!(refcount(0), None, "null has no count");
    }

    #[test]
    fn live_count_sees_an_allocation_until_its_last_release() {
        // Process-global and other tests allocate concurrently, so only the
        // direction is asserted: with this object alive the count is at
        // least 1, and `refcount` (per handle, race-free) shows it freed.
        let h = alloc(ClassTemplateId(1007), 1);
        assert!(live_count() >= 1);
        release(h);
        assert_eq!(refcount(h), None);
    }

    #[test]
    fn copy_is_shallow_of_the_dynamic_class_and_retains_nested_handles() {
        // LRM 8.12: properties are copied (a handle copied, not the object it
        // names) into a NEW object of the source's dynamic class.
        let inner_t = ClassTemplateId(1008);
        let outer_t = ClassTemplateId(1009);
        register_handle_fields(outer_t, vec![one_word(1)]);
        let inner = alloc(inner_t, 1);
        field_set(inner, one_word(0), &[5]);
        let src = alloc(outer_t, 2);
        field_set(src, one_word(0), &[77]);
        field_set(src, one_word(1), &[inner]); // src's reference to inner: the alloc's 1
        assert_eq!(refcount(inner), Some(1));

        let dup = copy(src).expect("a live source copies");
        assert_ne!(dup, src, "a copy is a distinct object");
        assert_eq!(dynamic_template(dup), Some(outer_t));
        assert_eq!(refcount(dup), Some(1), "the caller owns the copy");
        assert_eq!(refcount(src), Some(1), "the source is untouched");
        assert_eq!(
            refcount(inner),
            Some(2),
            "the nested object is shared: both owners hold a reference"
        );
        let mut out = [0u64];
        assert!(field_get(dup, one_word(0), &mut out));
        assert_eq!(out, [77], "scalar properties are copied by value");
        assert!(field_get(dup, one_word(1), &mut out));
        assert_eq!(out, [inner], "the handle is copied, not the object");

        // The copy is independent of the original from here on.
        field_set(dup, one_word(0), &[88]);
        assert!(field_get(src, one_word(0), &mut out));
        assert_eq!(out, [77]);

        // Freeing the original leaves the copy's reference to the nested
        // object; freeing the copy then frees it.
        release(src);
        assert_eq!(refcount(inner), Some(1));
        release(dup);
        assert_eq!(refcount(inner), None);
    }

    #[test]
    fn copy_keeps_the_prng_seed_and_rand_meta() {
        let src = alloc(ClassTemplateId(1010), 0);
        set_prng_seed(src, 99);
        set_rand_meta(
            src,
            RandMeta {
                rand_mode: vec![false, true],
                ..Default::default()
            },
        );
        let dup = copy(src).unwrap();
        assert_eq!(prng_seed(dup), Some(99));
        assert_eq!(
            rand_meta(dup),
            Some(RandMeta {
                rand_mode: vec![false, true],
                ..Default::default()
            })
        );
        release(src);
        release(dup);
    }

    /// LRM 18.8: one array element switched off alone reads back off, leaves its
    /// neighbours and the property on, and a whole-property call sets it again.
    #[test]
    fn leaf_rand_mode_is_per_element_and_reset_by_the_whole_property() {
        let t = ClassTemplateId(1031);
        register_rand_props(
            t,
            vec![RandProp {
                slot: one_word(0),
                kind: RandKind::Rand,
            }],
        );
        let h = alloc(t, 2);
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(true));
        assert!(set_leaf_rand_mode_of(h, 0, 8, false));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(false));
        assert_eq!(leaf_rand_mode_of(h, 0, 0), Some(true));
        assert_eq!(rand_mode_of(h, 0), Some(true));
        assert!(
            !set_leaf_rand_mode_of(h, 1, 8, false),
            "offset 1 is no rand property"
        );
        assert!(set_rand_mode_of(h, 0, true));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(true));
        assert!(set_leaf_rand_mode_of(h, 0, 8, false));
        assert!(set_all_rand_modes(h, true));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(true));
        // LRM 18.8: with the whole property off, one element can be switched back on alone.
        assert!(set_rand_mode_of(h, 0, false));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(false));
        assert!(set_leaf_rand_mode_of(h, 0, 8, true));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(true));
        assert_eq!(leaf_rand_mode_of(h, 0, 0), Some(false));
        assert!(set_leaf_rand_mode_of(h, 0, 8, false));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(false));
        assert!(set_leaf_rand_mode_of(h, 0, 8, true));
        assert!(set_rand_mode_of(h, 0, false));
        assert_eq!(leaf_rand_mode_of(h, 0, 8), Some(false), "whole call resets");
        release(h);
    }

    /// C20 (LRM 18.8): `rand_mode()` is addressed by the property's word
    /// offset, switches one property and no other, and refuses an offset that
    /// is no `rand` property rather than flipping some other bit.
    #[test]
    fn rand_mode_is_addressed_by_property_offset() {
        let t = ClassTemplateId(1030);
        register_rand_props(
            t,
            vec![
                RandProp {
                    slot: one_word(0),
                    kind: RandKind::Rand,
                },
                RandProp {
                    slot: one_word(3),
                    kind: RandKind::RandC,
                },
            ],
        );
        let h = alloc(t, 4);
        assert_eq!(rand_mode_of(h, 0), Some(true));
        assert_eq!(rand_mode_of(h, 3), Some(true));
        assert!(set_rand_mode_of(h, 3, false));
        assert_eq!(rand_mode_of(h, 0), Some(true));
        assert_eq!(rand_mode_of(h, 3), Some(false));
        // offset 1 is a plain field: no bit to read or flip
        assert_eq!(rand_mode_of(h, 1), None);
        assert!(!set_rand_mode_of(h, 1, false));
        assert_eq!(rand_meta(h).unwrap().rand_mode, vec![true, false]);
        assert!(set_all_rand_modes(h, false));
        assert_eq!(rand_meta(h).unwrap().rand_mode, vec![false, false]);
        assert!(set_all_rand_modes(h, true));
        assert_eq!(rand_meta(h).unwrap().rand_mode, vec![true, true]);
        release(h);
        // a freed handle is dead for every form
        assert_eq!(rand_mode_of(h, 0), None);
        assert!(!set_rand_mode_of(h, 0, true));
        assert!(!set_all_rand_modes(h, true));
    }

    /// C20 (LRM 18.8, 18.9): a static property's mode and a constraint
    /// block's mode live on the object that holds them, start on, and survive
    /// a shallow copy only where the LRM says an object's own state does.
    #[test]
    fn static_rand_and_constraint_modes_are_kept_per_holding_object() {
        let t = ClassTemplateId(1031);
        let h = alloc(t, 2);
        assert_eq!(static_rand_mode(h, 1), Some(true));
        assert_eq!(constraint_mode_of(h, 2), Some(true));
        assert!(set_static_rand_mode(h, 1, false));
        assert!(set_constraint_mode_of(h, 2, false));
        assert_eq!(static_rand_mode(h, 1), Some(false));
        assert_eq!(static_rand_mode(h, 0), Some(true));
        assert_eq!(constraint_mode_of(h, 2), Some(false));
        assert_eq!(constraint_mode_of(h, 1), Some(true));
        let dup = copy(h).unwrap();
        assert_eq!(constraint_mode_of(dup, 2), Some(false));
        assert!(set_constraint_mode_of(h, 2, true));
        assert_eq!(constraint_mode_of(h, 2), Some(true));
        assert_eq!(constraint_mode_of(dup, 2), Some(false));
        assert!(set_static_rand_mode(h, 1, true));
        assert_eq!(static_rand_mode(h, 1), Some(true));
        release(h);
        release(dup);
        assert_eq!(static_rand_mode(h, 1), None);
        assert_eq!(constraint_mode_of(h, 2), None);
        assert!(!set_static_rand_mode(h, 1, false));
        assert!(!set_constraint_mode_of(h, 2, false));
    }

    /// XC-059: a collection property is freed with its object and cloned (not
    /// aliased) by a shallow copy.
    #[test]
    fn a_collection_field_is_freed_with_its_object_and_cloned_by_copy() {
        use crate::collections::{self, KeyKind, Shape};
        let shape = Shape {
            elem_words: 1,
            assoc: false,
            key: KeyKind::Int {
                width: 32,
                signed: true,
            },
            obj: false,
        };
        let t = ClassTemplateId(1060);
        register_collection_fields(t, vec![one_word(1)]);
        let src = alloc(t, 2);
        let q = collections::set(&shape, 0, 0, &[7], true);
        let q = collections::set(&shape, q, 1, &[8], true);
        assert_eq!(collections::size(q), 2);
        field_set(src, one_word(1), &[q]);

        let dup = copy(src).expect("copies");
        let mut out = [0u64];
        assert!(field_get(dup, one_word(1), &mut out));
        let q2 = out[0];
        assert_ne!(q2, q, "the copy has its own collection handle");
        assert_eq!(collections::size(q2), 2);
        // Changing the copy's collection leaves the original's alone.
        let q2b = collections::set(&shape, q2, 0, &[99], true);
        let mut e = [0u64];
        assert!(collections::get(q, 0, &mut e));
        assert_eq!(e, [7]);
        assert!(collections::get(q2b, 0, &mut e));
        assert_eq!(e, [99]);
        field_set(dup, one_word(1), &[q2b]);

        release(src);
        assert!(!collections::is_live(q), "freed with the owning object");
        assert_eq!(collections::size(q2b), 2, "the copy's collection survives");
        release(dup);
        assert!(!collections::is_live(q2b));
    }

    /// XC-059: a handle held at a (word-unaligned) bit offset of a struct or
    /// array property is released with the object, retained by a copy, and a
    /// nested collection is cloned and written back at its bit offset.
    #[test]
    fn nested_handles_at_unaligned_bit_offsets_follow_the_object() {
        use crate::collections::{self, KeyKind, Shape};
        let shape = Shape {
            elem_words: 1,
            assoc: false,
            key: KeyKind::Int {
                width: 32,
                signed: true,
            },
            obj: false,
        };
        // One 5-word property (value bits 0..160 in words 0-2, unk above): an
        // object handle at bit 8 and a collection handle at bit 72.
        let t = ClassTemplateId(1021);
        let slot = FieldSlot {
            offset: 0,
            words: 5,
        };
        let obj_at = NestedHandle {
            slot,
            bit: 8,
            coll: false,
        };
        let coll_at = NestedHandle {
            slot,
            bit: 72,
            coll: true,
        };
        register_nested_handles(t, vec![obj_at, coll_at]);
        let leaf = alloc(ClassTemplateId(1022), 1);
        let q = collections::set(&shape, 0, 0, &[5], true);
        let src = alloc(t, 5);
        let mut fields = vec![0u64; 5];
        // Write through the same helpers the heap reads with.
        nested_set(&mut fields, &obj_at, leaf);
        nested_set(&mut fields, &coll_at, q);
        assert_eq!(nested_get(&fields, &obj_at), Some(leaf));
        assert_eq!(nested_get(&fields, &coll_at), Some(q), "no overlap clobber");
        assert!(field_set(src, slot, &fields));

        let dup = copy(src).expect("copies");
        assert_eq!(
            refcount(leaf),
            Some(2),
            "the copy retains the nested object"
        );
        let mut out = vec![0u64; 5];
        assert!(field_get(dup, slot, &mut out));
        let q2 = nested_get(&out, &coll_at).expect("in range");
        assert_ne!(q2, q, "the copy owns a clone of the nested collection");
        assert_eq!(collections::size(q2), 1);
        assert_eq!(nested_get(&out, &obj_at), Some(leaf));

        release(src);
        assert_eq!(
            refcount(leaf),
            Some(1),
            "the original dropped its reference"
        );
        assert!(
            !collections::is_live(q),
            "the nested collection died with it"
        );
        release(dup);
        assert_eq!(refcount(leaf), None, "the last holder freed it");
        assert!(!collections::is_live(q2));
    }

    /// XC-059: a leaf window reads and writes only its own value and unknown
    /// bits of the property, across word boundaries, and a write makes the
    /// leaf known without touching its neighbours.
    #[test]
    fn windows_read_and_write_only_their_own_bits() {
        // A 100-bit property: 100 value bits then 100 unknown bits (4 words).
        let slot = FieldSlot {
            offset: 1,
            words: 4,
        };
        let h = alloc(ClassTemplateId(1031), 5);
        // Everything unknown and set: val bits all 1, unk bits all 1.
        assert!(field_set(h, slot, &[u64::MAX; 4]));
        // A 70-bit leaf at bit 5 (straddles two value words and the unk half).
        let wide = Window {
            bit: 5,
            width: 70,
            field_width: 100,
        };
        let mut val = [0u64; 2];
        let mut unk = [0u64; 2];
        assert!(field_get_window(h, slot, wide, &mut val, &mut unk));
        assert_eq!(val, [u64::MAX, 0x3f]);
        assert_eq!(unk, [u64::MAX, 0x3f]);

        assert!(field_set_window(
            h,
            slot,
            wide,
            &[0x0123_4567_89ab_cdef, 0x15]
        ));
        assert!(field_get_window(h, slot, wide, &mut val, &mut unk));
        assert_eq!(val, [0x0123_4567_89ab_cdef, 0x15]);
        assert_eq!(unk, [0, 0], "a write makes the leaf known");

        // The neighbours below (bits 0..5) and above (75..100) are untouched.
        let low = Window {
            bit: 0,
            width: 5,
            field_width: 100,
        };
        let high = Window {
            bit: 75,
            width: 25,
            field_width: 100,
        };
        let (mut v, mut u) = ([0u64; 1], [0u64; 1]);
        assert!(field_get_window(h, slot, low, &mut v, &mut u));
        assert_eq!((v[0], u[0]), (0x1f, 0x1f));
        assert!(field_get_window(h, slot, high, &mut v, &mut u));
        assert_eq!((v[0], u[0]), ((1 << 25) - 1, (1 << 25) - 1));

        // A narrow aligned leaf, and an unchanged write does not disturb it.
        let one = Window {
            bit: 64,
            width: 8,
            field_width: 100,
        };
        assert!(field_set_window(h, slot, one, &[0xa5]));
        assert!(field_get_window(h, slot, one, &mut v, &mut u));
        assert_eq!((v[0], u[0]), (0xa5, 0));

        // A dead handle is reported, not written.
        release(h);
        assert!(!field_set_window(h, slot, one, &[1]));
        assert!(!field_get_window(h, slot, one, &mut v, &mut u));
    }

    #[test]
    fn copy_of_null_or_a_stale_handle_is_none() {
        assert_eq!(copy(0), None);
        let h = alloc(ClassTemplateId(1011), 1);
        release(h);
        assert_eq!(copy(h), None);
    }

    #[test]
    fn releasing_the_head_of_a_long_chain_frees_it_without_recursion() {
        // 100k nodes, each owning the next through a registered handle field:
        // a recursive free would overflow the test thread's stack.
        let t = ClassTemplateId(1012);
        register_handle_fields(t, vec![one_word(0)]);
        let head = alloc(t, 1);
        let mut prev = head;
        let mut all = vec![head];
        for _ in 0..100_000 {
            let next = alloc(t, 1);
            field_set(prev, one_word(0), &[next]);
            all.push(next);
            prev = next;
        }
        release(head);
        assert!(all.iter().all(|&h| refcount(h).is_none()));
    }

    /// Two objects pointing at each other, and a third one they both point
    /// at that something outside still holds: dropping the outside handles
    /// to the pair leaks them under reference counting alone; the cycle
    /// collector frees exactly the pair, and leaves the shared object with
    /// only the outside reference.
    #[test]
    fn a_dropped_cycle_is_collected_and_what_it_shared_survives() {
        let t = ClassTemplateId(1900);
        let next = FieldSlot {
            offset: 0,
            words: 1,
        };
        let other = FieldSlot {
            offset: 1,
            words: 1,
        };
        register_handle_fields(t, vec![next, other]);
        let a = alloc(t, 2);
        let b = alloc(t, 2);
        let shared = alloc(t, 2);
        // a.next = b; b.next = a; a.other = b.other = shared.
        field_set(a, next, &[b]);
        retain(b);
        field_set(b, next, &[a]);
        retain(a);
        field_set(a, other, &[shared]);
        retain(shared);
        field_set(b, other, &[shared]);
        retain(shared);
        // The outside drops a and b.
        release(a);
        release(b);
        assert_eq!(refcount(a), Some(1), "reference counting alone leaks");
        assert_eq!(refcount(shared), Some(3));
        // A cycle still held from outside is not garbage.
        let c = alloc(t, 2);
        let d = alloc(t, 2);
        field_set(c, next, &[d]);
        retain(d);
        field_set(d, next, &[c]);
        retain(c);
        release(d);
        assert!(collect_cycles() >= 2);
        assert_eq!(refcount(a), None);
        assert_eq!(refcount(b), None);
        assert_eq!(refcount(shared), Some(1));
        assert_eq!(refcount(c), Some(2));
        assert_eq!(refcount(d), Some(1));
        release(c);
        assert!(collect_cycles() >= 2);
        assert_eq!(refcount(c), None);
        assert_eq!(refcount(d), None);
        release(shared);
        assert_eq!(refcount(shared), None);
    }

    /// C5: an object owns the `randc` cycle state of its own fields, keyed by
    /// word offset; a copy starts a fresh cycle, and a dead handle has none.
    #[test]
    fn randc_state_is_per_object_per_offset_and_a_copy_starts_fresh() {
        let t = ClassTemplateId(1013);
        let a = alloc(t, 2);
        let b = alloc(t, 2);
        assert_eq!(randc_state(a, 0), Some(RandcState::default()));
        let st = RandcState {
            live: true,
            fingerprint: 7,
            remaining: vec![3, 1],
        };
        assert!(set_randc_states(a, vec![(1, st.clone())]));
        assert_eq!(randc_state(a, 1), Some(st));
        assert_eq!(randc_state(a, 0), Some(RandcState::default()));
        assert_eq!(randc_state(b, 1), Some(RandcState::default()), "per object");
        let c = copy(a).unwrap();
        assert_eq!(randc_state(c, 1), Some(RandcState::default()), "fresh copy");
        release(a);
        assert_eq!(randc_state(a, 1), None);
        assert!(!set_randc_states(a, vec![(1, RandcState::default())]));
        release(b);
        release(c);
    }
}