vj-sim 0.3.0

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

use super::dist::{DefaultWeight, Dist, Item, SELECTOR_BASE, Span};
use super::func::{Func, Stmt};
use super::ir::{ArrayNode, Expr};
use super::priority::{self, SOFT_BASE, Soft, SoftKey};
use super::real_domain::{Real, RealCond, RealDist, RealDistItem, RealExpr, RealSpan, RealVarId};
use super::reduce::ItemOffsets;
use super::registry::{
    Home, Outcome, ProgArray, ProgBlock, ProgHandle, ProgState, ProgVar, Program, Target, owner,
};
use crate::objects::{self, FieldSlot, Window};
use num_bigint::BigUint;
use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::Arc;

/// One object of a joint solve.
pub(super) struct Member {
    /// The object.
    pub handle: u64,
    /// Its dynamic class's program.
    pub program: Arc<Result<Program, String>>,
    /// Its `rand_mode` bits.
    pub rand_mode: Vec<bool>,
}

impl Member {
    fn prog(&self) -> Result<&Program, Outcome> {
        self.program
            .as_ref()
            .as_ref()
            .map_err(|_| Outcome::NoProgram)
    }
}

/// The active random objects of one call (18.5.8 a).
pub(super) struct Closure {
    /// The object `randomize()` was called on, then every other one, in
    /// discovery order.
    pub members: Vec<Member>,
    /// Each member's rank for soft-constraint priority: contained objects rank
    /// below their container.
    rank: Vec<u32>,
}

/// The handle stored in `slot` of `obj`: `Ok(None)` for `null`.
pub(super) fn read_handle(obj: u64, slot: FieldSlot, bit: u32) -> Result<Option<u64>, Outcome> {
    let mut buf = vec![0u64; slot.words];
    if !objects::field_get(obj, slot, &mut buf) {
        return Err(Outcome::DeadHandle);
    }
    // A handle is one 64-bit word of the property's value half; an element of a
    // fixed array of handles sits at `bit` (a multiple of 64, ProgHandle::bit)
    // and its unknown bits at the same offset of the upper half.
    let w = (bit / 64) as usize;
    let half = slot.words / 2;
    let (val, unk) = if bit == 0 && slot.words == 2 {
        (buf[0], buf[1])
    } else {
        (
            *buf.get(w).ok_or(Outcome::Failed)?,
            *buf.get(half + w).ok_or(Outcome::Failed)?,
        )
    };
    if unk != 0 {
        return Err(Outcome::StateUnknown);
    }
    Ok((val != 0).then_some(val))
}

/// The objects `root` randomizes together with itself (18.5.8 a): `root`, and
/// every object reached from it through an active `rand` handle member that is
/// not null, each exactly once.
pub(super) fn closure(
    root: u64,
    root_program: &Arc<Result<Program, String>>,
    root_mode: &[bool],
    statics: &[(u32, u64)],
) -> Result<Closure, Outcome> {
    let mut members = vec![Member {
        handle: root,
        program: Arc::clone(root_program),
        rand_mode: root_mode.to_vec(),
    }];
    let mut children: HashMap<u64, Vec<u64>> = HashMap::new();
    let mut next = 0;
    while next < members.len() {
        let me = members[next].handle;
        let handles: Vec<ProgHandle> = members[next].prog()?.rand_handles.clone();
        let mut kids = Vec::new();
        for ph in &handles {
            let active = match ph.prop_index {
                Some(i) => members[next]
                    .rand_mode
                    .get(i)
                    .copied()
                    .ok_or(Outcome::Failed)?,
                None => true,
            };
            if !active {
                continue;
            }
            let o = owner(ph.home, me, statics)?;
            let Some(child) = read_handle(o, ph.slot, ph.bit)? else {
                continue;
            };
            let template = objects::dynamic_template(child).ok_or(Outcome::DeadHandle)?;
            kids.push(child);
            if members.iter().any(|m| m.handle == child) {
                continue;
            }
            let program = super::registry::program(template).ok_or(Outcome::NoProgram)?;
            let meta = objects::rand_meta(child).ok_or(Outcome::DeadHandle)?;
            members.push(Member {
                handle: child,
                program,
                rand_mode: meta.rand_mode,
            });
        }
        children.insert(me, kids);
        next += 1;
    }
    // Lowest priority first: a contained object ranks below its container.
    let order = priority::object_order(&root, &|o: &u64| {
        children.get(o).cloned().unwrap_or_default()
    });
    let rank = members
        .iter()
        .map(|m| order.iter().position(|o| *o == m.handle).unwrap_or(0) as u32)
        .collect();
    Ok(Closure { members, rank })
}

/// The merged problem of a [`Closure`].
pub(super) struct Merged {
    /// One program over every variable of every member. Its `Instance` home is
    /// the root; every other member's variables are [`Home::Object`]s.
    pub program: Program,
    /// The members' `rand_mode` vectors, concatenated in member order; the
    /// merged variables' `prop_index` indexes it.
    pub rand_mode: Vec<bool>,
}

/// Where one member's tables start in the merged tables.
struct Offsets {
    var: u32,
    state: u32,
    array: u32,
    func: u32,
    dist: u32,
    soft: u32,
    conj: usize,
    prop: usize,
    disable: u32,
}

/// What a state of an [`overlay`]ed fragment becomes in the program it is laid
/// over.
pub(super) enum StateTo {
    /// A state of the result (an existing one it matched, or one appended).
    State(u32),
    /// A value fixed when the call was made (a local variable the inline
    /// constraint captured, LRM 18.7).
    Const(BigUint),
}

/// A renumbering of one member's expressions into the merged tables.
struct Remap<'a> {
    off: &'a Offsets,
    /// State `s` becomes this merged variable, if it is the random variable of
    /// another object a path reads (`None` for the whole table: leave states).
    sub: Option<&'a [Option<u32>]>,
    /// Whether `Var` is a program variable (`false` in a function body, where
    /// it is a frame slot).
    vars: bool,
    /// Program variable `v` becomes `var_map[v]` (an overlay matches its
    /// variables to the base program's) instead of `v + off.var`.
    var_map: Option<&'a [u32]>,
    /// The same for arrays.
    array_map: Option<&'a [u32]>,
    /// State `s` becomes `state_to[s]` instead of `s + off.state`.
    state_to: Option<&'a [StateTo]>,
}

impl<'a> Remap<'a> {
    /// The plain offset renumbering a [`merge`] uses.
    fn offset(off: &'a Offsets, sub: Option<&'a [Option<u32>]>, vars: bool) -> Self {
        Remap {
            off,
            sub,
            vars,
            var_map: None,
            array_map: None,
            state_to: None,
        }
    }

    fn expr(&self, e: &Expr) -> Expr {
        let mapped = e
            .try_map_children::<Infallible>(&mut |c| Ok(self.expr(c)))
            .unwrap_or_else(|never| match never {});
        match mapped {
            Expr::Var(v, t) if self.vars => Expr::Var(self.var(v), t),
            Expr::State(s, t) => {
                match self
                    .sub
                    .and_then(|sub| sub.get(s as usize).copied().flatten())
                {
                    Some(v) => Expr::Var(v, t),
                    None => match self.state_to.and_then(|m| m.get(s as usize)) {
                        Some(StateTo::State(n)) => Expr::State(*n, t),
                        Some(StateTo::Const(c)) => Expr::Const(t, c.clone()),
                        None => Expr::State(s + self.off.state, t),
                    },
                }
            }
            Expr::Array(n) => Expr::Array(self.node(n)),
            other => other,
        }
    }

    /// A variable id of any of the three spaces (program variables, `dist`
    /// selectors, soft discard flags).
    fn var(&self, v: u32) -> u32 {
        if v >= SOFT_BASE {
            v + self.off.soft
        } else if v >= SELECTOR_BASE {
            v + self.off.dist
        } else {
            self.prog_var(v)
        }
    }

    /// The new id of program variable `v`.
    fn prog_var(&self, v: u32) -> u32 {
        match self.var_map {
            Some(m) => m[v as usize],
            None => v + self.off.var,
        }
    }

    /// The new id of array `a`.
    fn arr(&self, a: u32) -> u32 {
        match self.array_map {
            Some(m) => m[a as usize],
            None => a + self.off.array,
        }
    }

    fn node(&self, n: ArrayNode) -> ArrayNode {
        match n {
            ArrayNode::Size(x) => ArrayNode::Size(self.arr(x)),
            // Its operands were renumbered with the rest of the tree.
            ArrayNode::Loop(..) | ArrayNode::Pick { .. } => n,
            ArrayNode::Elem { array, index, ty } => ArrayNode::Elem {
                array: self.arr(array),
                index,
                ty,
            },
            ArrayNode::Foreach { array, var, body } => ArrayNode::Foreach {
                array: self.arr(array),
                var,
                body,
            },
            ArrayNode::Reduce {
                op,
                array,
                var,
                index_var,
                body,
            } => ArrayNode::Reduce {
                op,
                array: self.arr(array),
                var,
                index_var,
                body,
            },
            ArrayNode::Distinct { scalars, arrays } => ArrayNode::Distinct {
                scalars,
                arrays: arrays.into_iter().map(|a| self.arr(a)).collect(),
            },
            ArrayNode::RowScope {
                template,
                row,
                body,
            } => ArrayNode::RowScope {
                template: self.arr(template),
                row,
                body,
            },
            ArrayNode::Call { func, args, ty } => ArrayNode::Call {
                func: func + self.off.func,
                args,
                ty,
            },
        }
    }

    fn stmts(&self, body: &[Stmt]) -> Vec<Stmt> {
        body.iter().map(|s| self.stmt(s)).collect()
    }

    fn stmt(&self, s: &Stmt) -> Stmt {
        match s {
            Stmt::Assign(slot, e) => Stmt::Assign(*slot, self.expr(e)),
            Stmt::If(c, t, o) => Stmt::If(self.expr(c), self.stmts(t), self.stmts(o)),
            Stmt::Loop {
                cond,
                body,
                step,
                test_first,
            } => Stmt::Loop {
                cond: cond.as_ref().map(|c| self.expr(c)),
                body: self.stmts(body),
                step: self.stmts(step),
                test_first: *test_first,
            },
            Stmt::Break => Stmt::Break,
            Stmt::Continue => Stmt::Continue,
            Stmt::Return => Stmt::Return,
        }
    }
}

/// Calls `f` on every expression of `body`.
fn stmt_exprs<'a>(body: &'a [Stmt], f: &mut impl FnMut(&'a Expr)) {
    for s in body {
        match s {
            Stmt::Assign(_, e) => f(e),
            Stmt::If(c, t, o) => {
                f(c);
                stmt_exprs(t, f);
                stmt_exprs(o, f);
            }
            Stmt::Loop {
                cond, body, step, ..
            } => {
                if let Some(c) = cond {
                    f(c);
                }
                stmt_exprs(body, f);
                stmt_exprs(step, f);
            }
            Stmt::Break | Stmt::Continue | Stmt::Return => {}
        }
    }
}

/// The member of the closure and the last member slot that the handle-path
/// state `s` of member `j` reads (LRM 18.5.12), if it is a path through live
/// objects that ends at a member of the closure. A null or dead handle on the
/// way gives `None`: the state stays a state and its read then fails the way
/// every unreadable state does.
fn resolve_via(
    c: &Closure,
    j: usize,
    s: &ProgState,
    statics: &[(u32, u64)],
) -> Option<(usize, FieldSlot)> {
    if s.class_of {
        return None;
    }
    let (last, hops) = s.via.split_last()?;
    let mut obj = owner(s.home, c.members[j].handle, statics).ok()?;
    for (i, slot) in std::iter::once(&s.slot).chain(hops).enumerate() {
        obj = read_handle(obj, *slot, if i == 0 { s.root_bit } else { 0 }).ok()??;
    }
    let k = c.members.iter().position(|m| m.handle == obj)?;
    Some((k, *last))
}

/// The merged variable the state `s` of member `j` designates, if it is a path
/// through live objects that ends at a random variable of a member of the
/// closure. A null or dead handle on the way leaves the state a state (its
/// read then fails the way every unreadable state does, LRM 18.5.12).
fn substitution(
    c: &Closure,
    progs: &[&Program],
    offs: &[Offsets],
    j: usize,
    s: &ProgState,
    statics: &[(u32, u64)],
) -> Result<Option<u32>, Outcome> {
    let Some((k, last)) = resolve_via(c, j, s, statics) else {
        return Ok(None);
    };
    let found = progs[k].vars.iter().position(|v| {
        v.home == Home::Instance
            && v.slot.offset == last.offset
            && v.slot.words == last.words
            && v.window == s.window
    });
    let Some(i) = found else { return Ok(None) };
    if progs[k].vars[i].ty != s.ty {
        // The same declaration seen from two sides; a disagreement is a bug in
        // the program builder, not something to guess through.
        return Err(Outcome::Failed);
    }
    Ok(Some(offs[k].var + i as u32))
}

/// What a lone object's handle-path states (`me.x`, LRM 18.5.12) do when a
/// handle leads back to the object itself.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum SelfAlias {
    /// No such state reads a random variable: the program is solved as it is.
    None,
    /// One reads a random integral variable: the program must go through
    /// [`merge`] so the read becomes the variable.
    Integral,
}

/// Whether a path through a handle of the lone object `c` reads one of its own
/// random variables. One that reads a random `real` is
/// [`Outcome::GlobalUnsupported`] (the merge cannot carry real problems), never
/// a silently stale read.
pub(super) fn self_alias(
    c: &Closure,
    prog: &Program,
    statics: &[(u32, u64)],
) -> Result<SelfAlias, Outcome> {
    let mut out = SelfAlias::None;
    for s in &prog.states {
        let Some((_, last)) = resolve_via(c, 0, s, statics) else {
            continue;
        };
        if prog.real_vars.iter().any(|v| {
            v.home == Home::Instance
                && v.slot.offset == last.offset
                && v.slot.words == last.words
                && v.window == s.window
        }) {
            return Err(Outcome::GlobalUnsupported);
        }
        if prog.vars.iter().any(|v| {
            v.home == Home::Instance
                && v.slot.offset == last.offset
                && v.slot.words == last.words
                && v.window == s.window
        }) {
            out = SelfAlias::Integral;
        }
    }
    Ok(out)
}

/// Concatenates the programs of `c` into one problem (18.5.8 b, c).
pub(super) fn merge(c: &Closure, statics: &[(u32, u64)]) -> Result<Merged, Outcome> {
    let progs: Vec<&Program> = c
        .members
        .iter()
        .map(Member::prog)
        .collect::<Result<_, _>>()?;
    // A `static` random variable is one cell shared by every instance of its
    // class (LRM 18.6.3): a contained object may own one as long as no other
    // member of the closure reaches the same static-property object, or the
    // cell would be drawn twice.
    let mut seen_statics: Vec<u32> = Vec::new();
    for p in &progs {
        if !p.real_vars.is_empty() {
            return Err(Outcome::GlobalUnsupported);
        }
        let mut mine: Vec<u32> = p
            .vars
            .iter()
            .map(|v| v.home)
            .chain(p.arrays.iter().map(|a| a.home))
            .filter_map(|h| match h {
                Home::Static(id) => Some(id),
                _ => None,
            })
            .collect();
        mine.sort_unstable();
        mine.dedup();
        if mine.iter().any(|id| seen_statics.contains(id)) {
            return Err(Outcome::GlobalUnsupported);
        }
        seen_statics.extend(mine);
    }
    let mut offs: Vec<Offsets> = Vec::with_capacity(progs.len());
    let mut at = Offsets {
        var: 0,
        state: 0,
        array: 0,
        func: 0,
        dist: 0,
        soft: 0,
        conj: 0,
        prop: 0,
        disable: 0,
    };
    for (m, p) in c.members.iter().zip(&progs) {
        offs.push(Offsets { ..at });
        at.var += p.vars.len() as u32;
        // Every state is kept (a substituted one is merely unused), so the
        // table stays addressable by `state + offset`.
        at.state += p.states.len() as u32;
        at.array += p.arrays.len() as u32;
        at.func += p.funcs.len() as u32;
        at.dist += p.dists.len() as u32;
        at.soft += p.softs.len() as u32;
        at.conj += p.conjuncts.len();
        at.prop += m.rand_mode.len();
        at.disable += p.n_disables as u32;
    }

    let mut out = Program::default();
    let mut rand_mode = Vec::with_capacity(at.prop);
    for (j, m) in c.members.iter().enumerate() {
        let p = progs[j];
        let off = &offs[j];
        let mut sub = Vec::with_capacity(p.states.len());
        for s in &p.states {
            sub.push(substitution(c, &progs, &offs, j, s, statics)?);
        }
        let with_sub = Remap::offset(off, Some(&sub), true);
        let plain = Remap::offset(off, None, true);
        let frame = Remap::offset(off, None, false);
        let reads_random = |e: &Expr| {
            let mut hit = false;
            e.for_each_state(&mut |s| hit |= sub.get(s as usize).copied().flatten().is_some());
            hit
        };
        let home = |h: Home| match h {
            Home::Instance if j > 0 => Home::Object(m.handle),
            other => other,
        };
        let prop = |i: Option<usize>| i.map(|i| i + off.prop);
        let item_off = ItemOffsets {
            dists: off.dist as usize,
            softs: off.soft as usize,
            before: out.before.len(),
            disables: off.disable as usize,
        };

        out.vars.extend(p.vars.iter().map(|v| ProgVar {
            home: home(v.home),
            prop_index: prop(v.prop_index),
            domain_conjunct: v.domain_conjunct.map(|d| d + off.conj),
            ..v.clone()
        }));
        out.states.extend(p.states.iter().map(|s| ProgState {
            home: home(s.home),
            ..s.clone()
        }));
        out.arrays.extend(p.arrays.iter().map(|a| ProgArray {
            home: home(a.home),
            prop_index: prop(a.prop_index),
            template_of: a.template_of.map(|t| t + off.array),
            ..a.clone()
        }));
        out.blocks.extend(p.blocks.iter().map(|b| ProgBlock {
            home: home(b.home),
            conjuncts: b.conjuncts.start + off.conj..b.conjuncts.end + off.conj,
            items: b.items.shifted(&item_off),
            ..b.clone()
        }));
        out.conjuncts
            .extend(p.conjuncts.iter().map(|e| with_sub.expr(e)));
        out.before.extend(
            p.before
                .iter()
                .map(|&(a, b)| (plain.prog_var(a), plain.prog_var(b))),
        );
        for d in &p.dists {
            out.dists.push(remap_dist(d, &plain, &reads_random)?);
        }
        for f in &p.funcs {
            let mut hit = false;
            stmt_exprs(&f.body, &mut |e| hit |= reads_random(e));
            if hit {
                return Err(Outcome::GlobalUnsupported);
            }
            out.funcs.push(Func {
                body: frame.stmts(&f.body),
                ..f.clone()
            });
        }
        out.softs.extend(p.softs.iter().map(|s| Soft {
            priority: priority::Priority {
                object: c.rank[j],
                ..s.priority
            },
            dists: s.dists.iter().map(|d| d + off.dist).collect(),
            keys: s.keys.iter().map(|k| remap_key(&plain, *k)).collect(),
            disabled: s.disabled,
            disabled_by: s.disabled_by.iter().map(|d| d + off.disable).collect(),
        }));
        out.n_disables += p.n_disables;
        rand_mode.extend_from_slice(&m.rand_mode);
    }
    // A contained object's `static` variable switched off with `rand_mode(0)`
    // (LRM 18.8) is state, as for the root ([`apply_static_modes`]).
    if let Some(p) = apply_static_modes(&out, &mut rand_mode, statics) {
        out = p;
    }
    Ok(Merged {
        program: out,
        rand_mode,
    })
}

/// `frag` laid over `base`: the constraints of an inline `randomize() with {}`
/// (a [`Program`] over the *static* class of the receiver, built at the call
/// site) added to the program of the object's *dynamic* class (LRM 18.7: "the
/// inline constraints ... are in addition to the object's constraints").
///
/// The fragment's variables, arrays and states are identified with the base
/// program's by where their values live (home, slot, window), never by number,
/// so one fragment lays over the program of any class derived from the one it
/// was built for. What it names that the base does not read (a state, a
/// non-`rand` array) is appended. `consts[s]` is the value fixed for fragment
/// state `s` when the call was made (a captured local, LRM 18.7: "the local
/// scope"); such a state is replaced by that constant everywhere and never
/// becomes a state of the result. The fragment's enum-domain conjuncts are
/// dropped: the base already carries each variable's own.
///
/// A fragment variable the base lacks is a property the call promotes to a
/// random variable (`randomize(v)` of a non-`rand` `v`, LRM 18.11): it is
/// appended, and every state of the base that reads the same property becomes
/// that variable, so the base's own constraints on it constrain the draw. A
/// `dist` or function of the base that reads such a property is
/// [`Outcome::GlobalUnsupported`] (their values are fixed before the solve). A
/// variable the base has with a different type is [`Outcome::Failed`]: the two
/// were built from the same declarations, so it is a malformed program. The
/// fragment's real variables and constraints are merged the same way
/// ([`merge_real`]).
pub(super) fn overlay(
    base: &Program,
    frag: &Program,
    consts: &[Option<BigUint>],
) -> Result<Program, Outcome> {
    let mut out = base.clone();
    let mut var_map = Vec::with_capacity(frag.vars.len());
    // Per fragment variable: whether the base already had it.
    let mut known = Vec::with_capacity(frag.vars.len());
    let mut promoted: Vec<u32> = Vec::new();
    for v in &frag.vars {
        let found = base
            .vars
            .iter()
            .position(|b| b.home == v.home && b.slot == v.slot && b.window == v.window);
        match found {
            Some(j) => {
                if base.vars[j].ty != v.ty {
                    return Err(Outcome::Failed);
                }
                var_map.push(j as u32);
                known.push(true);
            }
            None => {
                promoted.push(out.vars.len() as u32);
                var_map.push(out.vars.len() as u32);
                known.push(false);
                out.vars.push(ProgVar {
                    domain_conjunct: None,
                    ..v.clone()
                });
            }
        }
    }
    if !promoted.is_empty() {
        promote_states(&mut out, base, &promoted)?;
    }
    let mut array_map: Vec<u32> = vec![u32::MAX; frag.arrays.len()];
    for (k, a) in frag.arrays.iter().enumerate() {
        if a.template_of.is_some() {
            // Mapped below, once the array of arrays it stands for has been.
            continue;
        }
        let j = match out.arrays.iter().position(|b| {
            b.template_of.is_none() && b.home == a.home && b.slot == a.slot && b.window == a.window
        }) {
            Some(j) => {
                // `randomize(a)` of an array the class merely reads (LRM 18.11):
                // the call makes the base's state array random.
                if a.rand && !out.arrays[j].rand {
                    out.arrays[j].rand = true;
                    out.arrays[j].prop_index = a.prop_index;
                }
                j
            }
            None => {
                out.arrays.push(a.clone());
                out.arrays.len() - 1
            }
        };
        array_map[k] = j as u32;
    }
    for (k, a) in frag.arrays.iter().enumerate() {
        let Some(outer) = a.template_of else { continue };
        let outer = array_map[outer as usize];
        let j = match out.arrays.iter().position(|b| b.template_of == Some(outer)) {
            Some(j) => j,
            None => {
                let mut t = a.clone();
                t.template_of = Some(outer);
                out.arrays.push(t);
                out.arrays.len() - 1
            }
        };
        array_map[k] = j as u32;
    }
    let mut state_to = Vec::with_capacity(frag.states.len());
    for (k, s) in frag.states.iter().enumerate() {
        if let Some(Some(c)) = consts.get(k) {
            state_to.push(StateTo::Const(c.clone()));
            continue;
        }
        let j = match out.states.iter().position(|b| b == s) {
            Some(j) => j,
            None => {
                out.states.push(s.clone());
                out.states.len() - 1
            }
        };
        state_to.push(StateTo::State(j as u32));
    }
    let off = Offsets {
        var: 0,
        state: 0,
        array: 0,
        func: base.funcs.len() as u32,
        dist: base.dists.len() as u32,
        soft: base.softs.len() as u32,
        conj: base.conjuncts.len(),
        prop: 0,
        disable: base.n_disables as u32,
    };
    let mk = |vars: bool| Remap {
        off: &off,
        sub: None,
        vars,
        var_map: Some(&var_map),
        array_map: Some(&array_map),
        state_to: Some(&state_to),
    };
    let (plain, frame) = (mk(true), mk(false));
    // The enum-domain conjunct of a variable the base already had is the
    // base's own; a promoted variable keeps the fragment's.
    let dropped: Vec<usize> = frag
        .vars
        .iter()
        .zip(&known)
        .filter(|&(_, &k)| k)
        .filter_map(|(v, _)| v.domain_conjunct)
        .collect();
    let mut conj_at: Vec<Option<usize>> = vec![None; frag.conjuncts.len()];
    for (i, c) in frag.conjuncts.iter().enumerate() {
        if !dropped.contains(&i) {
            conj_at[i] = Some(out.conjuncts.len());
            out.conjuncts.push(plain.expr(c));
        }
    }
    for (v, new) in frag.vars.iter().zip(&var_map) {
        if promoted.contains(new) {
            out.vars[*new as usize].domain_conjunct = v
                .domain_conjunct
                .and_then(|d| conj_at.get(d).copied().flatten());
        }
    }
    out.before.extend(
        frag.before
            .iter()
            .map(|&(a, b)| (plain.prog_var(a), plain.prog_var(b))),
    );
    for d in &frag.dists {
        out.dists.push(remap_dist(d, &plain, &|_: &Expr| false)?);
    }
    for f in &frag.funcs {
        out.funcs.push(Func {
            body: frame.stmts(&f.body),
            ..f.clone()
        });
    }
    for s in &frag.softs {
        out.softs.push(Soft {
            priority: s.priority,
            dists: s.dists.iter().map(|d| d + off.dist).collect(),
            keys: s.keys.iter().map(|k| remap_key(&plain, *k)).collect(),
            disabled: s.disabled,
            disabled_by: s.disabled_by.iter().map(|d| d + off.disable).collect(),
        });
    }
    // An inline `disable soft` outranks every soft of the object's class (the
    // fragment's priority scope is the highest), so it discards the base
    // softs that directly mention its target (18.5.13.2, 18.7).
    let first = off.disable + (frag.n_disables - frag.disable_keys.len()) as u32;
    for (k, key) in frag.disable_keys.iter().enumerate() {
        let key = remap_key(&plain, *key);
        for s in out.softs.iter_mut().take(base.softs.len()) {
            if s.keys.iter().any(|&m| key.disables(m)) {
                s.disabled_by.push(first + k as u32);
                s.disabled = true;
            }
        }
    }
    out.n_disables += frag.n_disables;
    merge_real(&mut out, frag, &plain, &state_to)?;
    Ok(out)
}

/// Adds the fragment's real variables and real constraints (LRM 18.5, 18.7) to
/// `out`: a real variable the base already has (same home and slot) is shared,
/// so an inline constraint narrows the object's own; the others are appended.
/// A captured local read by a real condition is the value it had at the call.
fn merge_real(
    out: &mut Program,
    frag: &Program,
    plain: &Remap<'_>,
    state_to: &[StateTo],
) -> Result<(), Outcome> {
    if frag.real_vars.len() != frag.real.kinds.len() {
        return Err(Outcome::Failed);
    }
    let base_real_vars = out.real_vars.len();
    let mut map: Vec<RealVarId> = Vec::with_capacity(frag.real_vars.len());
    for v in &frag.real_vars {
        let found = out
            .real_vars
            .iter()
            .position(|b| b.home == v.home && b.slot == v.slot && b.window == v.window);
        match found {
            Some(j) => {
                if out.real_vars[j].kind != v.kind {
                    return Err(Outcome::Failed);
                }
                map.push(j as RealVarId);
            }
            None => {
                map.push(out.real_vars.len() as RealVarId);
                out.real_vars.push(v.clone());
                out.real.kinds.push(v.kind);
            }
        }
    }
    let rr = RealRemap {
        plain,
        map: &map,
        state_to,
    };
    for c in &frag.real.conds {
        out.real.conds.push(rr.cond(c));
    }
    for d in &frag.real.dists {
        let span = |s: &RealSpan| match s {
            RealSpan::Point(e) => RealSpan::Point(rr.expr(e)),
            RealSpan::Range { lo, hi } => RealSpan::Range {
                lo: lo.as_ref().map(|e| rr.expr(e)),
                hi: hi.as_ref().map(|e| rr.expr(e)),
            },
        };
        out.real.dists.push(RealDist {
            var: map[d.var as usize],
            items: d
                .items
                .iter()
                .map(|i| RealDistItem {
                    span: span(&i.span),
                    weight: plain.expr(&i.weight),
                })
                .collect(),
            default: d.default.as_ref().map(|w| plain.expr(w)),
        });
    }
    out.real.before.extend(
        frag.real
            .before
            .iter()
            .map(|&(a, b)| (map[a as usize], map[b as usize])),
    );
    promote_real_states(out, base_real_vars)
}

/// Makes every real condition and `dist` of `out` that reads, as state, the
/// property of a real variable the fragment added (one `randomize(r)` made
/// random, LRM 18.11; the variables from `first` on) read that variable
/// instead, so the class's own constraints on it constrain the solved value.
/// An integral expression, weight or function that reads such a property is
/// [`Outcome::GlobalUnsupported`]: its value would be fixed before the solve.
fn promote_real_states(out: &mut Program, first: usize) -> Result<(), Outcome> {
    let sub: Vec<Option<RealVarId>> = out
        .states
        .iter()
        .map(|s| {
            (first..out.real_vars.len())
                .find(|&j| {
                    let v = &out.real_vars[j];
                    s.via.is_empty() && s.home == v.home && s.slot == v.slot && s.window == v.window
                })
                .map(|j| j as RealVarId)
        })
        .collect();
    if sub.iter().all(Option::is_none) {
        return Ok(());
    }
    let reads = |e: &Expr| {
        let mut hit = false;
        e.for_each_state(&mut |s| hit |= sub.get(s as usize).copied().flatten().is_some());
        hit
    };
    if out.conjuncts.iter().any(&reads) || out.dists.iter().any(|d| dist_reads(d, &reads)) {
        return Err(Outcome::GlobalUnsupported);
    }
    for f in &out.funcs {
        let mut hit = false;
        stmt_exprs(&f.body, &mut |e| hit |= reads(e));
        if hit {
            return Err(Outcome::GlobalUnsupported);
        }
    }
    fn expr(e: &mut RealExpr, sub: &[Option<RealVarId>], reads: &dyn Fn(&Expr) -> bool) -> bool {
        match e {
            RealExpr::Const(..) => false,
            RealExpr::Var(_) => false,
            RealExpr::State(s, _) => {
                if let Some(Some(v)) = sub.get(*s as usize) {
                    *e = RealExpr::Var(*v);
                }
                false
            }
            RealExpr::FromInt(x) => reads(x),
            RealExpr::Neg(x) | RealExpr::ToShort(x) => expr(x, sub, reads),
            RealExpr::Add(x, y)
            | RealExpr::Sub(x, y)
            | RealExpr::Mul(x, y)
            | RealExpr::Div(x, y) => expr(x, sub, reads) | expr(y, sub, reads),
        }
    }
    fn cond(c: &mut RealCond, sub: &[Option<RealVarId>], reads: &dyn Fn(&Expr) -> bool) -> bool {
        match c {
            RealCond::Const(_) => false,
            RealCond::Int(e) => reads(e),
            RealCond::Cmp(_, x, y) => expr(x, sub, reads) | expr(y, sub, reads),
            RealCond::Not(x) => cond(x, sub, reads),
            RealCond::And(v) | RealCond::Or(v) => {
                v.iter_mut().fold(false, |h, x| h | cond(x, sub, reads))
            }
            RealCond::Guard(p, t, e) => {
                cond(p, sub, reads) | cond(t, sub, reads) | cond(e, sub, reads)
            }
        }
    }
    let mut bad = false;
    for c in &mut out.real.conds {
        bad |= cond(c, &sub, &reads);
    }
    for d in &mut out.real.dists {
        for i in &mut d.items {
            bad |= reads(&i.weight);
            match &mut i.span {
                RealSpan::Point(e) => bad |= expr(e, &sub, &reads),
                RealSpan::Range { lo, hi } => {
                    for e in lo.iter_mut().chain(hi.iter_mut()) {
                        bad |= expr(e, &sub, &reads);
                    }
                }
            }
        }
        bad |= d.default.as_ref().is_some_and(&reads);
    }
    if bad {
        return Err(Outcome::GlobalUnsupported);
    }
    Ok(())
}

/// The renumbering of a fragment's real problem into an overlay's.
struct RealRemap<'a> {
    plain: &'a Remap<'a>,
    map: &'a [RealVarId],
    state_to: &'a [StateTo],
}

impl RealRemap<'_> {
    fn expr(&self, e: &RealExpr) -> RealExpr {
        let b = |x: &RealExpr| Box::new(self.expr(x));
        match e {
            RealExpr::Const(..) => e.clone(),
            RealExpr::Var(v) => RealExpr::Var(self.map[*v as usize]),
            RealExpr::State(s, k) => match self.state_to.get(*s as usize) {
                Some(StateTo::State(n)) => RealExpr::State(*n, *k),
                Some(StateTo::Const(c)) => RealExpr::Const(Real::new(k.from_bits(c)), *k),
                None => RealExpr::State(*s, *k),
            },
            RealExpr::FromInt(x) => RealExpr::FromInt(Box::new(self.plain.expr(x))),
            RealExpr::Neg(x) => RealExpr::Neg(b(x)),
            RealExpr::ToShort(x) => RealExpr::ToShort(b(x)),
            RealExpr::Add(x, y) => RealExpr::Add(b(x), b(y)),
            RealExpr::Sub(x, y) => RealExpr::Sub(b(x), b(y)),
            RealExpr::Mul(x, y) => RealExpr::Mul(b(x), b(y)),
            RealExpr::Div(x, y) => RealExpr::Div(b(x), b(y)),
        }
    }

    fn cond(&self, c: &RealCond) -> RealCond {
        let b = |x: &RealCond| Box::new(self.cond(x));
        match c {
            RealCond::Const(_) => c.clone(),
            RealCond::Int(e) => RealCond::Int(self.plain.expr(e)),
            RealCond::Cmp(op, x, y) => RealCond::Cmp(*op, self.expr(x), self.expr(y)),
            RealCond::Not(x) => RealCond::Not(b(x)),
            RealCond::And(v) => RealCond::And(v.iter().map(|x| self.cond(x)).collect()),
            RealCond::Or(v) => RealCond::Or(v.iter().map(|x| self.cond(x)).collect()),
            RealCond::Guard(p, t, e) => RealCond::Guard(b(p), b(t), b(e)),
        }
    }
}

/// Makes every state of `out` (a copy of `base`) that reads the property of one
/// of the `promoted` variables read that variable instead. The variables are
/// the last ones of `out`.
fn promote_states(out: &mut Program, base: &Program, promoted: &[u32]) -> Result<(), Outcome> {
    let mut sub: Vec<Option<u32>> = Vec::with_capacity(base.states.len());
    for s in &base.states {
        sub.push(promoted.iter().copied().find(|&p| {
            let v = &out.vars[p as usize];
            s.via.is_empty() && s.home == v.home && s.slot == v.slot && s.window == v.window
        }));
    }
    if sub.iter().all(Option::is_none) {
        return Ok(());
    }
    let zero = Offsets {
        var: 0,
        state: 0,
        array: 0,
        func: 0,
        dist: 0,
        soft: 0,
        conj: 0,
        prop: 0,
        disable: 0,
    };
    let with_sub = Remap::offset(&zero, Some(&sub), true);
    let plain = Remap::offset(&zero, None, true);
    let reads_random = |e: &Expr| {
        let mut hit = false;
        e.for_each_state(&mut |s| hit |= sub.get(s as usize).copied().flatten().is_some());
        hit
    };
    for c in &mut out.conjuncts {
        *c = with_sub.expr(c);
    }
    let mut dists = Vec::with_capacity(base.dists.len());
    for d in &base.dists {
        dists.push(remap_dist(d, &plain, &reads_random)?);
    }
    out.dists = dists;
    for f in &base.funcs {
        let mut hit = false;
        stmt_exprs(&f.body, &mut |e| hit |= reads_random(e));
        if hit {
            return Err(Outcome::GlobalUnsupported);
        }
    }
    Ok(())
}

/// Makes the variables of `p` that `only` names (LRM 18.11) the call's active
/// random variables and every other one inactive (state), whatever `rand_mode`
/// says: the call "is conceptually equivalent to making a set of calls to the
/// `rand_mode()` method". Every variable, array, real variable and object handle
/// gets its own fresh `rand_mode` bit appended to `rand_mode`, so a `static`
/// variable (which has none of its own) can be taken out of the solve too, and
/// the object's own `rand_mode` bits are left alone.
///
/// A target that no variable, array, real variable or handle of `p` has was
/// never declared to the solver, which the call site must have done: it is
/// [`Outcome::Failed`].
pub(super) fn restrict(
    p: &mut Program,
    rand_mode: &mut Vec<bool>,
    only: &[Target],
) -> Result<(), Outcome> {
    let names = |t: &Target, home: Home, slot: FieldSlot, window: Option<Window>| {
        t.home == home && t.slot == slot && (t.window.is_none() || t.window == window)
    };
    let mut hit = vec![false; only.len()];
    let mut bit = |on: bool| -> usize {
        rand_mode.push(on);
        rand_mode.len() - 1
    };
    for v in &mut p.vars {
        let mut on = false;
        for (k, t) in only.iter().enumerate() {
            if names(t, v.home, v.slot, v.window) {
                on = true;
                hit[k] = true;
            }
        }
        v.prop_index = Some(bit(on));
    }
    for a in &mut p.arrays {
        let mut on = false;
        for (k, t) in only.iter().enumerate() {
            if names(t, a.home, a.slot, None) {
                on = true;
                hit[k] = true;
            }
        }
        a.prop_index = Some(bit(on));
    }
    for r in &mut p.real_vars {
        let mut on = false;
        for (k, t) in only.iter().enumerate() {
            if names(t, r.home, r.slot, r.window) {
                on = true;
                hit[k] = true;
            }
        }
        r.prop_index = Some(bit(on));
    }
    for h in &mut p.rand_handles {
        let mut on = false;
        for (k, t) in only.iter().enumerate() {
            if names(t, h.home, h.slot, None) {
                on = true;
                hit[k] = true;
            }
        }
        h.prop_index = Some(bit(on));
    }
    if hit.iter().all(|&h| h) {
        Ok(())
    } else {
        Err(Outcome::Failed)
    }
}

/// `p` with every `static` variable, array, real variable and object handle that
/// `rand_mode(0)` switched off (through any instance; the mode is the class's,
/// LRM 18.8) made inactive, or `None` when none is. A static has no `rand_mode`
/// bit of its own, so each switched-off one gets a fresh `false` bit appended to
/// `rand_mode`, exactly as [`restrict`] does; one that already has a bit (the call
/// named it, or the object's own) is left alone. A static whose property object
/// the call site did not pass stays active: the mode lives there.
pub(super) fn apply_static_modes(
    p: &Program,
    rand_mode: &mut Vec<bool>,
    statics: &[(u32, u64)],
) -> Option<Program> {
    let is_off = |home: Home, slot: FieldSlot, bit: Option<usize>| -> bool {
        if bit.is_some() {
            return false;
        }
        let Home::Static(id) = home else { return false };
        statics
            .iter()
            .find(|&&(i, _)| i == id)
            .and_then(|&(_, s)| objects::static_rand_mode(s, slot.offset))
            == Some(false)
    };
    let any = p.vars.iter().any(|v| is_off(v.home, v.slot, v.prop_index))
        || p.arrays
            .iter()
            .any(|a| is_off(a.home, a.slot, a.prop_index))
        || p.real_vars
            .iter()
            .any(|r| is_off(r.home, r.slot, r.prop_index))
        || p.rand_handles
            .iter()
            .any(|h| is_off(h.home, h.slot, h.prop_index));
    if !any {
        return None;
    }
    let mut out = p.clone();
    let mut bit = || -> Option<usize> {
        rand_mode.push(false);
        Some(rand_mode.len() - 1)
    };
    for v in &mut out.vars {
        if is_off(v.home, v.slot, v.prop_index) {
            v.prop_index = bit();
        }
    }
    for a in &mut out.arrays {
        if is_off(a.home, a.slot, a.prop_index) {
            a.prop_index = bit();
        }
    }
    for r in &mut out.real_vars {
        if is_off(r.home, r.slot, r.prop_index) {
            r.prop_index = bit();
        }
    }
    for h in &mut out.rand_handles {
        if is_off(h.home, h.slot, h.prop_index) {
            h.prop_index = bit();
        }
    }
    Some(out)
}

/// `p` with every element of an instance array property whose mode differs
/// from its property's made so (LRM 18.8): `obj.a[i].rand_mode(0)` on an active
/// array (`leaf_off`) or `obj.a[i].rand_mode(1)` on an inactive one (`leaf_on`);
/// each pairs the property's `rand_mode` index with the element's value bit.
/// `None` when no element deviates. Like [`apply_static_modes`], each such leaf
/// variable gets a fresh bit appended to `rand_mode` (`false` for `leaf_off`,
/// `true` for `leaf_on`), so the solve reads it as state or as random. Only the
/// root object's leaves are honoured.
pub(super) fn apply_leaf_modes(
    p: &Program,
    rand_mode: &mut Vec<bool>,
    leaf_off: &[(usize, u32)],
    leaf_on: &[(usize, u32)],
) -> Option<Program> {
    // `Some(forced mode)` when the element deviates from its property.
    let forced = |home: Home, bit: Option<usize>, w: Option<objects::Window>| -> Option<bool> {
        match (home, bit, w) {
            (Home::Instance, Some(i), Some(w)) if leaf_off.contains(&(i, w.bit)) => Some(false),
            (Home::Instance, Some(i), Some(w)) if leaf_on.contains(&(i, w.bit)) => Some(true),
            _ => None,
        }
    };
    let any = p
        .vars
        .iter()
        .any(|v| forced(v.home, v.prop_index, v.window).is_some())
        || p.real_vars
            .iter()
            .any(|r| forced(r.home, r.prop_index, r.window).is_some());
    if !any {
        return None;
    }
    let mut out = p.clone();
    let mut bit = |on: bool| -> Option<usize> {
        rand_mode.push(on);
        Some(rand_mode.len() - 1)
    };
    for v in &mut out.vars {
        if let Some(on) = forced(v.home, v.prop_index, v.window) {
            v.prop_index = bit(on);
        }
    }
    for r in &mut out.real_vars {
        if let Some(on) = forced(r.home, r.prop_index, r.window) {
            r.prop_index = bit(on);
        }
    }
    Some(out)
}

/// The soft-constraint key `k` renumbered by `r`.
fn remap_key(r: &Remap<'_>, k: SoftKey) -> SoftKey {
    match k {
        SoftKey::Var(v) => SoftKey::Var(r.prog_var(v)),
        SoftKey::Array(a) => SoftKey::Array(r.arr(a)),
        SoftKey::ArraySize(a) => SoftKey::ArraySize(r.arr(a)),
    }
}

/// Whether any member, bound or weight of `d` satisfies `reads`.
fn dist_reads(d: &Dist, reads: &impl Fn(&Expr) -> bool) -> bool {
    let mut hit = false;
    let mut check = |e: &Expr| hit |= reads(e);
    for item in &d.items {
        check(&item.member);
        check(&item.weight);
        match &item.span {
            Span::Point(e) => check(e),
            Span::Range { lo, hi } => {
                lo.iter().chain(hi).for_each(&mut check);
            }
        }
    }
    if let Some(def) = &d.default {
        check(&def.weight);
    }
    hit
}

/// `d` renumbered into the merged tables. A bound, weight or subject that reads
/// a random variable of another object has no value before the solve.
fn remap_dist(
    d: &Dist,
    plain: &Remap<'_>,
    reads_random: &impl Fn(&Expr) -> bool,
) -> Result<Dist, Outcome> {
    // A template (a `dist` inside a `foreach` over a dynamic array) is expanded
    // against the object's own arrays; a global randomize has none.
    if d.subject.is_some() || dist_reads(d, reads_random) {
        return Err(Outcome::GlobalUnsupported);
    }
    let opt = |e: &Option<Expr>| e.as_ref().map(|e| plain.expr(e));
    Ok(Dist {
        subject_ty: d.subject_ty,
        plain_var: d.plain_var.map(|v| plain.prog_var(v)),
        vars: d.vars.iter().map(|&v| plain.prog_var(v)).collect(),
        items: d
            .items
            .iter()
            .map(|i| Item {
                member: plain.expr(&i.member),
                ty: i.ty,
                span: match &i.span {
                    Span::Point(e) => Span::Point(plain.expr(e)),
                    Span::Range { lo, hi } => Span::Range {
                        lo: opt(lo),
                        hi: opt(hi),
                    },
                },
                weight: plain.expr(&i.weight),
                per_range: i.per_range,
            })
            .collect(),
        default: d.default.as_ref().map(|w| DefaultWeight {
            weight: plain.expr(&w.weight),
            per_range: w.per_range,
        }),
        subject: None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constraints::ir::{BinOp, Ty};
    use crate::constraints::real_domain::{CmpOp, FloatKind, RealProblem};
    use crate::constraints::registry::{self, ProgRealVar};
    use crate::netlist::ClassTemplateId;
    use crate::objects::{RandKind, RandProp, alloc, register_rand_props};

    const HANDLE: FieldSlot = FieldSlot {
        offset: 0,
        words: 2,
    };
    const V: FieldSlot = FieldSlot {
        offset: 2,
        words: 1,
    };

    fn u8t() -> Ty {
        Ty::unsigned(8)
    }
    fn bin(op: BinOp, a: Expr, b: Expr) -> Expr {
        Expr::Binary(op, Box::new(a), Box::new(b), Ty::BIT)
    }
    fn k(v: u64) -> Expr {
        Expr::constant(u8t(), v)
    }

    /// A class `{ rand Node peer; rand bit [7:0] v; }`: the handle at words
    /// 0..2 (rand-prop 0), `v` at word 2 (rand-prop 1), with `conjuncts` over
    /// `Var(0)` (= `v`) and `State(0)` (= `peer.v`).
    fn node_class(id: u32, conjuncts: Vec<Expr>) -> ClassTemplateId {
        let t = ClassTemplateId(id);
        register_rand_props(
            t,
            vec![
                RandProp {
                    slot: HANDLE,
                    kind: RandKind::Rand,
                },
                RandProp {
                    slot: V,
                    kind: RandKind::Rand,
                },
            ],
        );
        registry::register_program(
            t,
            Ok(Program {
                vars: vec![ProgVar {
                    ty: u8t(),
                    slot: V,
                    home: Home::Instance,
                    prop_index: Some(1),
                    domain_conjunct: None,
                    randc: false,
                    window: None,
                }],
                states: vec![ProgState {
                    class_of: false,
                    root_bit: 0,
                    ty: u8t(),
                    slot: HANDLE,
                    window: None,
                    home: Home::Instance,
                    via: vec![V],
                }],
                conjuncts,
                rand_handles: vec![ProgHandle {
                    slot: HANDLE,
                    home: Home::Instance,
                    prop_index: Some(0),
                    bit: 0,
                }],
                ..Program::default()
            }),
        );
        t
    }

    /// A class with just `rand bit [7:0] v` at word 2 (the same layout, no handle).
    fn leaf_class(id: u32, conjuncts: Vec<Expr>) -> ClassTemplateId {
        let t = ClassTemplateId(id);
        register_rand_props(
            t,
            vec![RandProp {
                slot: V,
                kind: RandKind::Rand,
            }],
        );
        registry::register_program(
            t,
            Ok(Program {
                vars: vec![ProgVar {
                    ty: u8t(),
                    slot: V,
                    home: Home::Instance,
                    prop_index: Some(0),
                    domain_conjunct: None,
                    randc: false,
                    window: None,
                }],
                conjuncts,
                ..Program::default()
            }),
        );
        t
    }

    fn set(h: u64, slot: FieldSlot, words: &[u64]) {
        assert!(objects::field_set(h, slot, words));
    }
    fn v_of(h: u64) -> u64 {
        let mut b = [0u64];
        assert!(objects::field_get(h, V, &mut b));
        b[0]
    }
    fn closure_of(h: u64) -> Result<Closure, Outcome> {
        let t = objects::dynamic_template(h).expect("live");
        let entry = registry::program(t).expect("program");
        closure(
            h,
            &entry,
            &objects::rand_meta(h).expect("meta").rand_mode,
            &[],
        )
    }
    fn handles(c: &Closure) -> Vec<u64> {
        c.members.iter().map(|m| m.handle).collect()
    }

    /// `peer.v != v`, read from either side of the pair.
    fn differ() -> Vec<Expr> {
        vec![bin(BinOp::Ne, Expr::State(0, u8t()), Expr::Var(0, u8t()))]
    }

    #[test]
    fn a_cyclic_pair_of_objects_is_collected_once_each_and_merged_into_one_problem() {
        let t = node_class(0x7b00_0001, differ());
        let (p, q) = (alloc(t, 3), alloc(t, 3));
        set(p, HANDLE, &[q, 0]);
        set(q, HANDLE, &[p, 0]);
        let c = closure_of(p).expect("closure");
        assert_eq!(handles(&c), vec![p, q], "p first, q once, p not re-entered");
        let m = merge(&c, &[]).expect("merge");
        assert_eq!(m.program.vars.len(), 2);
        assert_eq!(m.program.conjuncts.len(), 2, "one `differ` per object");
        assert_eq!(m.rand_mode.len(), 4, "two rand props each");
        assert_eq!(m.program.vars[0].home, Home::Instance);
        assert_eq!(m.program.vars[1].home, Home::Object(q));
        assert_eq!(m.program.vars[1].prop_index, Some(3));
        // p's `peer.v` became q's variable; q's `peer.v` became p's.
        assert_eq!(
            m.program.conjuncts[0],
            bin(BinOp::Ne, Expr::Var(1, u8t()), Expr::Var(0, u8t()))
        );
        assert_eq!(
            m.program.conjuncts[1],
            bin(BinOp::Ne, Expr::Var(0, u8t()), Expr::Var(1, u8t()))
        );
        // And the solve is joint: they always differ, and both vary.
        let mut seen = std::collections::BTreeSet::new();
        for _ in 0..200 {
            assert_eq!(registry::randomize(p, &[]), Outcome::Solved);
            assert_ne!(v_of(p), v_of(q));
            seen.insert((v_of(p), v_of(q)));
        }
        assert!(seen.len() > 100, "{}", seen.len());
    }

    #[test]
    fn a_chain_is_walked_to_its_end_and_a_null_handle_ends_it() {
        // root -> a -> c, and b -> c: each object holds one handle in this class.
        let t = node_class(0x7b00_0002, Vec::new());
        let (root, a, b, c) = (alloc(t, 3), alloc(t, 3), alloc(t, 3), alloc(t, 3));
        set(root, HANDLE, &[a, 0]);
        set(a, HANDLE, &[c, 0]);
        set(b, HANDLE, &[c, 0]);
        assert_eq!(handles(&closure_of(root).unwrap()), vec![root, a, c]);
        assert_eq!(handles(&closure_of(b).unwrap()), vec![b, c]);
        // a null handle ends the walk
        set(c, HANDLE, &[0, 0]);
        assert_eq!(handles(&closure_of(c).unwrap()), vec![c]);
    }

    #[test]
    fn an_inactive_rand_handle_leaves_its_object_out_and_its_members_are_state() {
        let t = node_class(0x7b00_0003, differ());
        let (p, q) = (alloc(t, 3), alloc(t, 3));
        set(p, HANDLE, &[q, 0]);
        set(q, V, &[5]);
        let mut meta = objects::rand_meta(p).expect("meta");
        meta.rand_mode[0] = false; // p.peer.rand_mode(0)
        objects::set_rand_meta(p, meta);
        assert_eq!(handles(&closure_of(p).unwrap()), vec![p]);
        // q.v stays 5, and is the constant `p.v != 5` is solved against
        for _ in 0..50 {
            assert_eq!(registry::randomize(p, &[]), Outcome::Solved);
            assert_ne!(v_of(p), 5);
            assert_eq!(v_of(q), 5);
        }
    }

    #[test]
    fn a_global_constraint_with_no_solution_is_unsatisfiable_and_writes_nothing() {
        // parent: peer.v > v; the child (a leaf) is pinned to 255.
        let leaf = leaf_class(
            0x7b00_0004,
            vec![bin(BinOp::Eq, Expr::Var(0, u8t()), k(255))],
        );
        let parent = node_class(
            0x7b00_0005,
            vec![bin(BinOp::Gt, Expr::State(0, u8t()), Expr::Var(0, u8t()))],
        );
        let (p, q) = (alloc(parent, 3), alloc(leaf, 3));
        set(p, HANDLE, &[q, 0]);
        set(p, V, &[9]);
        set(q, V, &[7]);
        // satisfiable: v < 255 is all that is asked of the parent
        assert_eq!(registry::randomize(p, &[]), Outcome::Solved);
        assert_eq!(v_of(q), 255);
        assert!(v_of(p) < 255);
        // pin the parent too: `255 > v` has no solution once v == 255 is forced
        let parent2 = node_class(
            0x7b00_0006,
            vec![
                bin(BinOp::Gt, Expr::State(0, u8t()), Expr::Var(0, u8t())),
                bin(BinOp::Eq, Expr::Var(0, u8t()), k(255)),
            ],
        );
        let p2 = alloc(parent2, 3);
        set(p2, HANDLE, &[q, 0]);
        set(p2, V, &[9]);
        set(q, V, &[7]);
        assert_eq!(registry::randomize(p2, &[]), Outcome::Unsatisfiable);
        assert_eq!((v_of(p2), v_of(q)), (9, 7));
    }

    #[test]
    fn the_joint_solve_is_uniform_over_the_combinations_of_all_objects() {
        // (v < 4) && (peer.v < 4) && (v <= peer.v): 10 combinations
        let two = |e: Expr| bin(BinOp::Lt, e, k(4));
        let leaf = leaf_class(0x7b00_0007, vec![two(Expr::Var(0, u8t()))]);
        let parent = node_class(
            0x7b00_0008,
            vec![
                two(Expr::Var(0, u8t())),
                bin(BinOp::Le, Expr::Var(0, u8t()), Expr::State(0, u8t())),
            ],
        );
        let (p, q) = (alloc(parent, 3), alloc(leaf, 3));
        set(p, HANDLE, &[q, 0]);
        let mut counts = std::collections::BTreeMap::new();
        for _ in 0..5000 {
            assert_eq!(registry::randomize(p, &[]), Outcome::Solved);
            *counts.entry((v_of(p), v_of(q))).or_insert(0u32) += 1;
        }
        // 10 pairs with p.v <= q.v, each 500 on average
        assert_eq!(counts.len(), 10, "{counts:?}");
        for (pair, n) in &counts {
            assert!(pair.0 <= pair.1);
            assert!((380..=620).contains(n), "{pair:?}: {n}");
        }
    }

    #[test]
    fn a_real_random_variable_in_a_contained_object_is_a_loud_limit() {
        let leaf = leaf_class(0x7b00_0009, Vec::new());
        // re-register the leaf with a real variable
        registry::register_program(
            leaf,
            Ok(Program {
                real_vars: vec![ProgRealVar {
                    kind: FloatKind::F64,
                    slot: FieldSlot {
                        offset: 2,
                        words: 2,
                    },
                    home: Home::Instance,
                    prop_index: Some(0),
                    window: None,
                }],
                ..Program::default()
            }),
        );
        let parent = node_class(0x7b00_000a, Vec::new());
        let (p, q) = (alloc(parent, 4), alloc(leaf, 4));
        set(p, HANDLE, &[q, 0]);
        assert_eq!(registry::randomize(p, &[]), Outcome::GlobalUnsupported);
    }

    const A: FieldSlot = FieldSlot {
        offset: 2,
        words: 1,
    };
    const B: FieldSlot = FieldSlot {
        offset: 3,
        words: 1,
    };
    const C: FieldSlot = FieldSlot {
        offset: 4,
        words: 1,
    };

    fn pvar(slot: FieldSlot, prop: Option<usize>) -> ProgVar {
        ProgVar {
            ty: u8t(),
            slot,
            home: Home::Instance,
            prop_index: prop,
            domain_conjunct: None,
            randc: false,
            window: None,
        }
    }
    fn pstate(slot: FieldSlot) -> ProgState {
        ProgState {
            class_of: false,
            root_bit: 0,
            ty: u8t(),
            slot,
            window: None,
            home: Home::Instance,
            via: Vec::new(),
        }
    }
    fn lt(a: Expr, b: Expr) -> Expr {
        bin(BinOp::Lt, a, b)
    }

    /// The base: `rand a, b` with `a != b`.
    fn base_ab() -> Program {
        Program {
            vars: vec![pvar(A, Some(0)), pvar(B, Some(1))],
            conjuncts: vec![bin(BinOp::Ne, Expr::Var(0, u8t()), Expr::Var(1, u8t()))],
            ..Program::default()
        }
    }

    #[test]
    fn overlay_identifies_a_fragment_variable_by_where_it_lives_not_by_its_number() {
        // The fragment numbers `b` as variable 0; in the base it is variable 1.
        let frag = Program {
            vars: vec![pvar(B, None)],
            conjuncts: vec![lt(Expr::Var(0, u8t()), k(5))],
            ..Program::default()
        };
        let out = overlay(&base_ab(), &frag, &[]).expect("overlay");
        assert_eq!(out.vars.len(), 2, "no variable was added");
        assert_eq!(out.conjuncts.len(), 2);
        assert_eq!(out.conjuncts[0], base_ab().conjuncts[0], "the base is kept");
        assert_eq!(out.conjuncts[1], lt(Expr::Var(1, u8t()), k(5)));
    }

    #[test]
    fn overlay_makes_a_captured_local_a_constant_and_never_a_state() {
        let frag = Program {
            vars: vec![pvar(A, None)],
            states: vec![pstate(C)],
            conjuncts: vec![lt(Expr::Var(0, u8t()), Expr::State(0, u8t()))],
            ..Program::default()
        };
        let out = overlay(&base_ab(), &frag, &[Some(BigUint::from(7u32))]).expect("overlay");
        assert!(out.states.is_empty(), "the capture is not a state");
        assert_eq!(out.conjuncts[1], lt(Expr::Var(0, u8t()), k(7)));
    }

    #[test]
    fn overlay_shares_a_state_the_base_already_reads_and_appends_a_new_one() {
        let mut base = base_ab();
        base.states = vec![pstate(C)];
        let frag = Program {
            states: vec![pstate(A), pstate(C)],
            conjuncts: vec![lt(Expr::State(0, u8t()), Expr::State(1, u8t()))],
            ..Program::default()
        };
        let out = overlay(&base, &frag, &[]).expect("overlay");
        assert_eq!(out.states, vec![pstate(C), pstate(A)]);
        // frag state 0 (A) was appended as 1; frag state 1 (C) is the base's 0.
        assert_eq!(
            out.conjuncts[1],
            lt(Expr::State(1, u8t()), Expr::State(0, u8t()))
        );
    }

    #[test]
    fn overlay_promotes_a_property_the_base_reads_as_state_to_a_variable() {
        // `randomize(c)` of a non-rand `c` the base's constraint reads: the base's
        // own constraint on it must constrain the draw.
        let mut base = base_ab();
        base.states = vec![pstate(C)];
        base.conjuncts.push(lt(Expr::State(0, u8t()), k(3)));
        let frag = Program {
            vars: vec![pvar(C, None)],
            ..Program::default()
        };
        let out = overlay(&base, &frag, &[]).expect("overlay");
        assert_eq!(out.vars.len(), 3);
        assert_eq!(out.vars[2].slot, C);
        assert_eq!(out.conjuncts[1], lt(Expr::Var(2, u8t()), k(3)));
    }

    #[test]
    fn overlay_refuses_what_it_cannot_lay_over_loudly() {
        // a variable the base has with another type is a malformed program
        let wide = ProgVar {
            ty: Ty::unsigned(16),
            ..pvar(A, None)
        };
        let frag = Program {
            vars: vec![wide],
            ..Program::default()
        };
        assert_eq!(overlay(&base_ab(), &frag, &[]), Err(Outcome::Failed));
        // a real variable the base has with another type is a malformed program
        let real_var = |kind| registry::ProgRealVar {
            kind,
            slot: A,
            home: Home::Instance,
            prop_index: None,
            window: None,
        };
        let mut base = base_ab();
        base.real_vars = vec![real_var(FloatKind::F64)];
        base.real.kinds = vec![FloatKind::F64];
        let frag = Program {
            real_vars: vec![real_var(FloatKind::F32)],
            real: RealProblem {
                kinds: vec![FloatKind::F32],
                ..Default::default()
            },
            ..Program::default()
        };
        assert_eq!(overlay(&base, &frag, &[]), Err(Outcome::Failed));
    }

    #[test]
    fn overlay_merges_real_constraints_sharing_a_variable_the_base_has() {
        // The base constrains real `r` (at slot A) to < 10; the fragment says
        // `r > 2` (its variable 0) and `r < lim` where `lim` is a captured
        // local, so the merged problem has ONE variable and three conditions
        // with the capture folded to its value.
        let rv = registry::ProgRealVar {
            kind: FloatKind::F64,
            slot: A,
            home: Home::Instance,
            prop_index: None,
            window: None,
        };
        let c = |x: f64| RealExpr::Const(Real::new(x), FloatKind::F64);
        let mut base = base_ab();
        base.real_vars = vec![rv.clone()];
        base.real = RealProblem {
            kinds: vec![FloatKind::F64],
            conds: vec![RealCond::Cmp(CmpOp::Lt, RealExpr::Var(0), c(10.0))],
            ..Default::default()
        };
        let frag = Program {
            real_vars: vec![rv],
            states: vec![pstate(C)],
            real: RealProblem {
                kinds: vec![FloatKind::F64],
                conds: vec![
                    RealCond::Cmp(CmpOp::Gt, RealExpr::Var(0), c(2.0)),
                    RealCond::Cmp(
                        CmpOp::Lt,
                        RealExpr::Var(0),
                        RealExpr::State(0, FloatKind::F64),
                    ),
                ],
                ..Default::default()
            },
            ..Program::default()
        };
        let bits = BigUint::from(3.0f64.to_bits());
        let out = overlay(&base, &frag, &[Some(bits)]).expect("overlay");
        assert_eq!(out.real_vars.len(), 1, "the variable is shared");
        assert_eq!(out.real.kinds.len(), 1);
        assert_eq!(out.real.conds.len(), 3);
        assert_eq!(
            out.real.conds[2],
            RealCond::Cmp(CmpOp::Lt, RealExpr::Var(0), c(3.0)),
            "the captured local is its value"
        );
    }

    #[test]
    fn overlay_promotes_a_real_property_the_base_reads_as_state_to_a_variable() {
        // `randomize(r)` of a non-rand real (LRM 18.11): the base's own
        // `r < 10` reads r's stored value as state; once the fragment makes r
        // random, the base condition must constrain the solved variable.
        let rv = registry::ProgRealVar {
            kind: FloatKind::F64,
            slot: C,
            home: Home::Instance,
            prop_index: None,
            window: None,
        };
        let c = |x: f64| RealExpr::Const(Real::new(x), FloatKind::F64);
        let mut base = base_ab();
        let r_state = base.states.len() as u32;
        base.states.push(pstate(C));
        base.real = RealProblem {
            conds: vec![RealCond::Cmp(
                CmpOp::Lt,
                RealExpr::State(r_state, FloatKind::F64),
                c(10.0),
            )],
            ..Default::default()
        };
        let frag = Program {
            real_vars: vec![rv],
            real: RealProblem {
                kinds: vec![FloatKind::F64],
                ..Default::default()
            },
            ..Program::default()
        };
        let out = overlay(&base, &frag, &[]).expect("overlay");
        assert_eq!(out.real_vars.len(), 1);
        assert_eq!(
            out.real.conds[0],
            RealCond::Cmp(CmpOp::Lt, RealExpr::Var(0), c(10.0)),
            "the base condition reads the promoted variable"
        );
        // an integral constraint reading the promoted real's bits cannot be
        // honoured: loud, not silently fixed
        let mut base2 = base.clone();
        base2.conjuncts.push(Expr::State(r_state, u8t()));
        assert_eq!(overlay(&base2, &frag, &[]), Err(Outcome::GlobalUnsupported));
    }

    #[test]
    fn restrict_keeps_only_the_named_variables_active_and_leaves_the_objects_bits_alone() {
        let mut p = base_ab();
        let mut mode = vec![true, true];
        let only = [Target {
            home: Home::Instance,
            slot: B,
            window: None,
        }];
        restrict(&mut p, &mut mode, &only).expect("restrict");
        assert_eq!(
            mode[..2],
            [true, true],
            "the object's own bits are untouched"
        );
        let on = |v: &ProgVar| mode[v.prop_index.expect("bit")];
        assert!(!on(&p.vars[0]), "a is state");
        assert!(on(&p.vars[1]), "b is the random set");
    }

    #[test]
    fn restrict_activates_a_variable_the_object_has_switched_off() {
        // LRM 18.11: the list wins over rand_mode(0) of the same call.
        let mut p = base_ab();
        let mut mode = vec![false, false];
        let only = [Target {
            home: Home::Instance,
            slot: A,
            window: None,
        }];
        restrict(&mut p, &mut mode, &only).expect("restrict");
        assert!(mode[p.vars[0].prop_index.unwrap()]);
        assert!(!mode[p.vars[1].prop_index.unwrap()]);
    }

    #[test]
    fn restrict_with_no_targets_is_a_checker_and_an_unknown_target_is_loud() {
        let mut p = base_ab();
        let mut mode = vec![true, true];
        restrict(&mut p, &mut mode, &[]).expect("randomize(null)");
        assert!(p.vars.iter().all(|v| !mode[v.prop_index.unwrap()]));
        let nowhere = [Target {
            home: Home::Instance,
            slot: C,
            window: None,
        }];
        assert_eq!(
            restrict(&mut base_ab(), &mut vec![true, true], &nowhere),
            Err(Outcome::Failed)
        );
    }

    fn spec_frag_lt_capture(id: u32) -> (ClassTemplateId, u32) {
        let t = leaf_class(id, Vec::new());
        let frag = Program {
            vars: vec![pvar(V, None)],
            states: vec![pstate(C)],
            conjuncts: vec![lt(Expr::Var(0, u8t()), Expr::State(0, u8t()))],
            ..Program::default()
        };
        let spec = registry::register_spec(registry::Spec {
            frag,
            captures: vec![registry::Capture { state: 0, width: 8 }],
            only: None,
        });
        (t, spec)
    }

    #[test]
    fn a_spec_call_constrains_the_draw_by_the_value_captured_at_that_call() {
        let (t, spec) = spec_frag_lt_capture(0x7b00_0011);
        let o = alloc(t, 3);
        for limit in [1u64, 5, 200] {
            for _ in 0..50 {
                assert_eq!(
                    registry::randomize_spec(o, &[], spec, &[limit]),
                    Outcome::Solved
                );
                assert!(v_of(o) < limit, "{} < {limit}", v_of(o));
            }
        }
        // the class's program is not changed by a call: a plain call is free again
        let mut seen_high = false;
        for _ in 0..100 {
            assert_eq!(registry::randomize(o, &[]), Outcome::Solved);
            seen_high |= v_of(o) >= 200;
        }
        assert!(seen_high);
    }

    #[test]
    fn a_spec_that_cannot_hold_fails_and_leaves_the_object_untouched() {
        let (t, spec) = spec_frag_lt_capture(0x7b00_0012);
        let o = alloc(t, 3);
        set(o, V, &[42]);
        // v < 0 has no solution
        assert_eq!(
            registry::randomize_spec(o, &[], spec, &[0]),
            Outcome::Unsatisfiable
        );
        assert_eq!(v_of(o), 42);
        // an unknown bit in the captured local is an error, never a silent 0
        assert_eq!(
            registry::randomize_spec(o, &[], spec, &[9 | (1 << 8)]),
            Outcome::StateUnknown
        );
        assert_eq!(v_of(o), 42);
        // too few capture words, and an unregistered spec
        assert_eq!(registry::randomize_spec(o, &[], spec, &[]), Outcome::Failed);
        assert_eq!(
            registry::randomize_spec(o, &[], u32::MAX, &[]),
            Outcome::Failed
        );
    }

    #[test]
    fn randomize_null_is_a_checker_that_changes_nothing() {
        let t = leaf_class(0x7b00_0013, Vec::new());
        let make = |bound: u64| {
            registry::register_spec(registry::Spec {
                frag: Program {
                    vars: vec![pvar(V, None)],
                    conjuncts: vec![bin(BinOp::Eq, Expr::Var(0, u8t()), k(bound))],
                    ..Program::default()
                },
                captures: Vec::new(),
                only: Some(Vec::new()),
            })
        };
        let o = alloc(t, 3);
        set(o, V, &[3]);
        assert_eq!(
            registry::randomize_spec(o, &[], make(3), &[]),
            Outcome::Solved
        );
        assert_eq!(v_of(o), 3);
        assert_eq!(
            registry::randomize_spec(o, &[], make(4), &[]),
            Outcome::Unsatisfiable
        );
        assert_eq!(v_of(o), 3);
    }

    fn block(home: Home, conjuncts: std::ops::Range<usize>) -> ProgBlock {
        ProgBlock {
            home,
            ordinal: 0,
            conjuncts,
            items: Default::default(),
        }
    }

    /// Each object's constraint blocks come along into the merged problem: the
    /// conjunct ranges shift by the conjuncts before them, and an instance block
    /// of a contained object is homed at that object (its mode is its own).
    #[test]
    fn merge_keeps_every_objects_blocks_with_shifted_ranges_and_homes() {
        let t = node_class(0x7b00_0031, differ());
        let mut prog = registry::program(t)
            .expect("program")
            .as_ref()
            .clone()
            .expect("built");
        prog.blocks = vec![block(Home::Instance, 0..1), block(Home::Static(4), 1..1)];
        registry::register_program(t, Ok(prog));
        let (p, q) = (alloc(t, 3), alloc(t, 3));
        set(p, HANDLE, &[q, 0]);
        set(q, HANDLE, &[p, 0]);
        let m = merge(&closure_of(p).expect("closure"), &[]).expect("merge");
        let homes: Vec<Home> = m.program.blocks.iter().map(|b| b.home).collect();
        assert_eq!(
            homes,
            vec![
                Home::Instance,
                Home::Static(4),
                Home::Object(q),
                Home::Static(4)
            ]
        );
        let ranges: Vec<_> = m
            .program
            .blocks
            .iter()
            .map(|b| b.conjuncts.clone())
            .collect();
        assert_eq!(
            ranges,
            vec![0..1, 1..1, 1..2, 2..2],
            "q's conjunct follows p's"
        );
    }

    /// LRM 18.8: a static random variable switched off through its class's
    /// property object is state in every call that passes that object; one the
    /// call did not pass, or that already has a bit of its own, is untouched.
    #[test]
    fn apply_static_modes_turns_a_switched_off_static_into_state() {
        let st = alloc(ClassTemplateId(0x7b00_0032), 1);
        let var = |home: Home, prop: Option<usize>| ProgVar {
            home,
            ..pvar(
                FieldSlot {
                    offset: 0,
                    words: 1,
                },
                prop,
            )
        };
        let p = Program {
            vars: vec![var(Home::Static(7), None), var(Home::Static(8), None)],
            ..Program::default()
        };
        let mut mode = vec![true];
        let statics = [(7u32, st)];
        // active: nothing to change
        assert!(apply_static_modes(&p, &mut mode, &statics).is_none());
        assert!(objects::set_static_rand_mode(st, 0, false));
        let out = apply_static_modes(&p, &mut mode, &statics).expect("switched off");
        assert_eq!(mode, vec![true, false], "one fresh inactive bit");
        assert_eq!(out.vars[0].prop_index, Some(1));
        assert_eq!(out.vars[1].prop_index, None, "static 8 was not passed");
        // a variable that already has a bit keeps it
        let mut owned = p.clone();
        owned.vars[0].prop_index = Some(0);
        let mut mode = vec![true];
        assert!(apply_static_modes(&owned, &mut mode, &statics).is_none());
        assert_eq!(mode, vec![true]);
    }
}