keleusma 0.2.0

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

extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use rkyv::{Archive, Deserialize, Serialize};

use crate::kstring::KString;

/// A compile-time constant, the variant of [`Value`] that the compiler
/// emits into the bytecode's constant pool.
///
/// Strict subset of [`Value`]. Only variants that the rkyv archive can
/// faithfully serialize and deserialize. The runtime-only variant
/// [`Value::KStr`] is intentionally absent because it is produced
/// exclusively by native functions and runtime string operations,
/// never as a compile-time constant.
///
/// The runtime executes against the archived form
/// [`ArchivedConstValue`]. Each operand-stack push from a constant
/// goes through [`Value::from_const_archived`], which lifts the
/// archived form into a runtime `Value`.
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
#[rkyv(
    serialize_bounds(__S: rkyv::ser::Writer + rkyv::ser::Allocator, __S::Error: rkyv::rancor::Source),
    deserialize_bounds(__D::Error: rkyv::rancor::Source),
    bytecheck(bounds(__C: rkyv::validation::ArchiveContext, <__C as rkyv::rancor::Fallible>::Error: rkyv::rancor::Source)),
    attr(allow(missing_docs))
)]
pub enum ConstValue {
    /// Unit value `()`.
    Unit,
    /// Boolean.
    Bool(bool),
    /// 64-bit signed integer.
    Int(i64),
    /// Eight-bit unsigned integer. Surface type is `Byte`.
    Byte(u8),
    /// Signed Q-format fixed-point. The wrapped `i64` holds the
    /// fixed-point bits; the fraction-bit count is target-scaled
    /// and is carried by the opcodes that consume the value
    /// rather than stored alongside.
    Fixed(i64),
    /// 64-bit floating-point number. Gated behind the `floats`
    /// cargo feature so flash-constrained targets that do not use
    /// floating-point arithmetic can compile the variant out.
    #[cfg(feature = "floats")]
    Float(f64),
    /// Immutable static string referenced from the rodata region.
    /// Source-level string literals compile to this variant.
    StaticStr(String),
    /// Tuple of constant values.
    Tuple(#[rkyv(omit_bounds)] Vec<ConstValue>),
    /// Fixed-size array of constant values.
    Array(#[rkyv(omit_bounds)] Vec<ConstValue>),
    /// Named struct with ordered fields.
    Struct {
        /// Name of the struct type.
        type_name: String,
        /// Ordered (field-name, field-value) pairs.
        #[rkyv(omit_bounds)]
        fields: Vec<(String, ConstValue)>,
    },
    /// Enum variant with optional payload.
    Enum {
        /// Name of the enum type.
        type_name: String,
        /// Name of the variant.
        variant: String,
        /// Positional payload values for tuple-variant constructions.
        /// Empty for unit variants.
        #[rkyv(omit_bounds)]
        fields: Vec<ConstValue>,
    },
    /// Option::None.
    None,
}

/// Runtime value in the Keleusma VM.
///
/// Superset of [`ConstValue`] that adds the runtime-only string
/// variant [`Value::KStr`] for arena-allocated strings with
/// epoch-tagged stale-pointer detection. KStr does not participate
/// in rkyv serialization. The constant-pool boundary is the
/// [`Value::from_const_archived`] lift and the
/// `ConstValue::try_from(&Value)` lower direction is intentionally
/// absent because runtime values cannot become compile-time
/// constants.
/// Type alias for the default 64-bit `GenericValue` shape.
/// Existing call sites continue to write `Value` (no angle
/// brackets); the alias expands to `GenericValue<i64, f64>` so
/// pattern matching, construction, and trait impls all resolve
/// to the concrete 64-bit specialization.
///
/// Sub-64-bit runtimes constructed via `Vm<W, A, F>` use a
/// different specialization (e.g. `GenericValue<i16, f32>`).
/// Hosts that ship narrow runtimes are encouraged to introduce a
/// local type alias for ergonomic call sites; see the
/// "Parametric VM" recipe in the Cookbook.
///
/// `Address` is intentionally not a `GenericValue` parameter
/// because no runtime-value variant carries an address payload;
/// addresses appear as opcode immediate operands and on the
/// `Vm` itself, not on the values flowing through the operand
/// stack.
pub type Value = GenericValue<i64, f64>;

/// Parametric runtime-value type. The bundled `Vm` uses
/// `GenericValue<i64, f64>` aliased as `Value`; sub-64-bit
/// runtimes use a different specialization. The `W: Word` and
/// `F: Float` constraints match the bytecode header's
/// `word_bits_log2` and `float_bits_log2` declared widths.
#[derive(Debug, Clone)]
pub enum GenericValue<W: crate::word::Word, F: crate::float::Float> {
    /// Unit value `()`.
    Unit,
    /// Boolean.
    Bool(bool),
    /// Script-visible signed integer. Surface type is `Word`.
    /// The bit width is determined by the `W` parameter and
    /// matches the bytecode header's `word_bits_log2`.
    Int(W),
    /// Eight-bit unsigned integer. Surface type is `Byte`. Arithmetic
    /// uses wrapping `u8` semantics; conversions to and from `Word`
    /// go through `Op::WordToByte` and `Op::ByteToWord`.
    Byte(u8),
    /// Signed Q-format fixed-point. The wrapped `W` holds the
    /// fixed-point bits; the fraction-bit count is carried by the
    /// opcodes that produce or consume the value.
    Fixed(W),
    /// Script-visible floating-point number. The width is
    /// determined by the `F` parameter and matches the bytecode
    /// header's `float_bits_log2`. Gated behind the `floats`
    /// cargo feature alongside the rest of the floating-point
    /// runtime surface.
    #[cfg(feature = "floats")]
    Float(F),
    /// Immutable static string referenced from the rodata region. Source-level
    /// string literals compile to this variant. Permitted to flow through the
    /// dialogue type B and across hot updates subject to the host attestation
    /// for rodata pointer validity. See R31, R32, R33 and B5.
    StaticStr(String),
    /// Dynamic string allocated in the host-owned arena's top region.
    /// Carries a [`crate::kstring::KString`] handle that becomes
    /// [`keleusma_arena::Stale`] on access if the arena has been reset
    /// since the handle was issued. Subject to the cross-yield
    /// prohibition because the underlying storage does not survive a
    /// reset. The boundary type for native callers and the host that
    /// want bounded-memory accounting and stale-pointer detection.
    KStr(KString),
    /// Tuple of values.
    Tuple(Vec<GenericValue<W, F>>),
    /// Fixed-size array of values.
    Array(Vec<GenericValue<W, F>>),
    /// Named struct with ordered fields.
    Struct {
        /// Name of the struct type.
        type_name: String,
        /// Ordered (field-name, field-value) pairs.
        fields: Vec<(String, GenericValue<W, F>)>,
    },
    /// Enum variant with optional payload.
    Enum {
        /// Name of the enum type.
        type_name: String,
        /// Name of the variant.
        variant: String,
        /// Positional payload values for tuple-variant constructions.
        /// Empty for unit variants.
        fields: Vec<GenericValue<W, F>>,
    },
    /// Option::None.
    None,
    /// Opaque host-managed value referenced through a shared
    /// reference-counted pointer. Produced by host-registered native
    /// functions that operate on Rust types the script does not
    /// introspect. The pointee implements the
    /// [`crate::opaque::HostOpaque`] marker trait; the script-side
    /// type is the opaque name registered through the type checker.
    ///
    /// Lifetime is independent of the arena: opaque values may
    /// cross the yield boundary in the dialogue type, persist across
    /// arena resets, and survive hot code swaps. Equality is by
    /// pointer identity, matching the convention for host-managed
    /// references.
    ///
    /// WCMU contribution is zero from the script side because the
    /// allocation is host-managed. Hosts that want to bound their
    /// own opaque heap supply a per-native attestation through
    /// [`crate::vm::Vm::set_native_bounds`].
    Opaque(alloc::sync::Arc<dyn crate::opaque::HostOpaque>),

    /// Phantom variant kept only when the `floats` feature is
    /// disabled, so the `F` type parameter is referenced non-
    /// recursively. Never constructed at runtime; pattern
    /// matches over `GenericValue` use a wildcard arm to absorb
    /// this case under either feature combination.
    #[cfg(not(feature = "floats"))]
    #[doc(hidden)]
    _PhantomFloat(core::marker::PhantomData<F>),
}

impl<W: crate::word::Word, F: crate::float::Float> PartialEq for GenericValue<W, F> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Unit, Self::Unit) | (Self::None, Self::None) => true,
            (Self::Bool(a), Self::Bool(b)) => a == b,
            (Self::Int(a), Self::Int(b)) => a == b,
            (Self::Byte(a), Self::Byte(b)) => a == b,
            (Self::Fixed(a), Self::Fixed(b)) => a == b,
            #[cfg(feature = "floats")]
            (Self::Float(a), Self::Float(b)) => a == b,
            // Static strings compare equal if their contents match.
            (Self::StaticStr(a), Self::StaticStr(b)) => a == b,
            // KStr equality compares the captured handle (pointer and
            // epoch). Two KStr handles are equal only if they point to
            // the same arena allocation under the same epoch. Content
            // equality across distinct arena allocations is not checked
            // because the comparison would require an arena borrow that
            // `PartialEq` does not provide. Hosts that want content
            // equality must compare through `as_str_with_arena` against
            // a known arena.
            (Self::KStr(a), Self::KStr(b)) => a.epoch() == b.epoch(),
            (Self::Tuple(a), Self::Tuple(b)) | (Self::Array(a), Self::Array(b)) => a == b,
            (
                Self::Struct {
                    type_name: na,
                    fields: fa,
                },
                Self::Struct {
                    type_name: nb,
                    fields: fb,
                },
            ) => na == nb && fa == fb,
            (
                Self::Enum {
                    type_name: na,
                    variant: va,
                    fields: fa,
                },
                Self::Enum {
                    type_name: nb,
                    variant: vb,
                    fields: fb,
                },
            ) => na == nb && va == vb && fa == fb,
            // Opaque equality is pointer identity. Two Arcs are
            // equal only if they share the same allocation. This
            // matches the convention for host-managed references
            // and avoids requiring `Eq` on the host's opaque type.
            (Self::Opaque(a), Self::Opaque(b)) => alloc::sync::Arc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl<W: crate::word::Word, F: crate::float::Float> GenericValue<W, F> {
    /// Return a human-readable type name for error messages.
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Unit => "Unit",
            Self::Bool(_) => "Bool",
            Self::Int(_) => "Int",
            Self::Byte(_) => "Byte",
            Self::Fixed(_) => "Fixed",
            #[cfg(feature = "floats")]
            Self::Float(_) => "Float",
            Self::StaticStr(_) => "StaticStr",
            Self::KStr(_) => "KStr",
            Self::Tuple(_) => "Tuple",
            Self::Array(_) => "Array",
            Self::Struct { .. } => "Struct",
            Self::Enum { .. } => "Enum",
            Self::None => "None",
            // Returning a `&'static str` for an opaque value would
            // require leaking the host-supplied name, so we surface
            // a generic literal here. Diagnostics that need the
            // host's specific name read it through
            // [`GenericValue::opaque_type_name`].
            Self::Opaque(_) => "Opaque",
            #[cfg(not(feature = "floats"))]
            Self::_PhantomFloat(_) => unreachable!("_PhantomFloat is never constructed"),
        }
    }

    /// Return the host-supplied script-side type name for an
    /// opaque value, or `None` if the value is not opaque.
    pub fn opaque_type_name(&self) -> Option<&'static str> {
        match self {
            Self::Opaque(o) => Some(o.type_name()),
            _ => None,
        }
    }

    /// Borrow the underlying UTF-8 contents of a static string.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::StaticStr(s) => Some(s.as_str()),
            _ => Option::None,
        }
    }

    /// Borrow the underlying UTF-8 contents of any string variant,
    /// resolving `KStr` through the supplied arena.
    pub fn as_str_with_arena<'a>(
        &'a self,
        arena: &'a keleusma_arena::Arena,
    ) -> Result<Option<&'a str>, keleusma_arena::Stale> {
        match self {
            Self::StaticStr(s) => Ok(Some(s.as_str())),
            Self::KStr(h) => h.get(arena).map(Some),
            _ => Ok(Option::None),
        }
    }

    /// Returns true if the value is an arena-resident dynamic
    /// string or transitively contains one.
    pub fn contains_dynstr(&self) -> bool {
        match self {
            Self::KStr(_) => true,
            Self::Tuple(items) | Self::Array(items) => items.iter().any(Self::contains_dynstr),
            Self::Struct { fields, .. } => fields.iter().any(|(_, v)| v.contains_dynstr()),
            Self::Enum { fields, .. } => fields.iter().any(Self::contains_dynstr),
            _ => false,
        }
    }

    /// Lift an archived constant pool entry into a runtime
    /// `GenericValue<W, F>`.
    ///
    /// The constant pool stores [`ConstValue`] entries with fixed
    /// `i64` and `f64` payloads; this lift converts each constant
    /// to the runtime's `W` and `F` types via `Word::from_i64_wrap`
    /// and `Float::from_f64`. The conversion truncates / rounds
    /// when the runtime's word or float width is narrower than
    /// the bytecode's; programs whose constants do not fit are
    /// rejected at load time by the bytecode-header width check.
    pub fn from_const_archived(c: &ArchivedConstValue) -> Self {
        match c {
            ArchivedConstValue::Unit => Self::Unit,
            ArchivedConstValue::Bool(b) => Self::Bool(*b),
            ArchivedConstValue::Int(i) => Self::Int(W::from_i64_wrap(i.to_native())),
            ArchivedConstValue::Byte(b) => Self::Byte(*b),
            ArchivedConstValue::Fixed(i) => Self::Fixed(W::from_i64_wrap(i.to_native())),
            #[cfg(feature = "floats")]
            ArchivedConstValue::Float(f) => Self::Float(F::from_f64(f.to_native())),
            ArchivedConstValue::StaticStr(s) => {
                use alloc::string::ToString;
                Self::StaticStr(s.as_str().to_string())
            }
            ArchivedConstValue::Tuple(items) => {
                Self::Tuple(items.iter().map(Self::from_const_archived).collect())
            }
            ArchivedConstValue::Array(items) => {
                Self::Array(items.iter().map(Self::from_const_archived).collect())
            }
            ArchivedConstValue::Struct { type_name, fields } => {
                use alloc::string::ToString;
                Self::Struct {
                    type_name: type_name.as_str().to_string(),
                    fields: fields
                        .iter()
                        .map(|kv| (kv.0.as_str().to_string(), Self::from_const_archived(&kv.1)))
                        .collect(),
                }
            }
            ArchivedConstValue::Enum {
                type_name,
                variant,
                fields,
            } => {
                use alloc::string::ToString;
                Self::Enum {
                    type_name: type_name.as_str().to_string(),
                    variant: variant.as_str().to_string(),
                    fields: fields.iter().map(Self::from_const_archived).collect(),
                }
            }
            ArchivedConstValue::None => Self::None,
        }
    }
}

/// Classification of a compiled function chunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub enum BlockType {
    /// Atomic total function (`fn`). No yields, no streaming.
    Func,
    /// Non-atomic total function (`yield fn`). Must contain at least one Yield.
    Reentrant,
    /// Productive divergent function (`loop fn`). Contains Stream/Reset and Yield.
    Stream,
}

/// A bytecode instruction.
///
/// V0.2.0 Phase 7c moved opcode serialization out of the rkyv
/// archive and into the [`crate::wire_format`] opcode stream; the
/// rkyv derives retire alongside `ArchivedModule` and
/// `op_from_archived` in Phase 8.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Op {
    /// Push a constant from the chunk's constant pool.
    Const(u16),

    /// Push local variable by slot index.
    GetLocal(u16),
    /// Pop and store to local variable slot.
    SetLocal(u16),

    /// Push data segment slot value onto stack.
    GetData(u16),
    /// Pop value and store into data segment slot.
    SetData(u16),

    /// Indexed read from a data-segment array. The first immediate is
    /// the array's base slot, the second is the array's total slot
    /// count. The opcode pops a `Value::Int` index from the operand
    /// stack, checks `0 <= index < total`, traps if the index is out
    /// of range, and pushes `data[base + index]`. Used by the compiler
    /// for `state.field[i]` reads when `state.field` is an array-typed
    /// data field.
    GetDataIndexed(u16, u16),
    /// Indexed write to a data-segment array. The first immediate is
    /// the array's base slot, the second is the array's total slot
    /// count. The opcode pops the `Value::Int` index, then pops the
    /// new value, checks `0 <= index < total`, traps if out of range,
    /// and stores `data[base + index] = value`.
    SetDataIndexed(u16, u16),
    /// Bounds check against the value on top of the operand stack
    /// without modifying the stack. The immediate is the exclusive
    /// upper bound. Traps when the top is not a `Value::Int`, when
    /// the value is negative, or when the value is greater than or
    /// equal to the bound. Used by the compiler to validate each
    /// level of a multi-dimensional `state.field[i][j]...` access
    /// before the per-level stride arithmetic computes the flat
    /// offset.
    BoundsCheck(u16),

    /// Binary addition.
    Add,
    /// Binary subtraction.
    Sub,
    /// Binary multiplication.
    Mul,
    /// Binary division.
    Div,
    /// Binary modulo.
    Mod,
    /// Unary negation.
    Neg,

    /// Equality comparison.
    CmpEq,
    /// Inequality comparison.
    CmpNe,
    /// Less than comparison.
    CmpLt,
    /// Greater than comparison.
    CmpGt,
    /// Less than or equal comparison.
    CmpLe,
    /// Greater than or equal comparison.
    CmpGe,

    /// Logical NOT.
    Not,

    // -- Block-structured control flow --
    /// Pop bool; if false, skip to target (matching Else or EndIf).
    /// Target is an op index within the current chunk; chunks are
    /// capped at `u16::MAX` ops by the compiler.
    If(u16),
    /// Skip to target (matching EndIf). Reached when then-block
    /// falls through. Target is an op index within the current
    /// chunk.
    Else(u16),
    /// Block delimiter for If/Else. No-op at runtime.
    EndIf,

    /// Begin loop block. Target is past EndLoop (used by Break and
    /// BreakIf). Target is an op index within the current chunk.
    Loop(u16),
    /// Back-edge to instruction after matching Loop. Target is an
    /// op index within the current chunk.
    EndLoop(u16),
    /// Unconditional forward jump past enclosing EndLoop. Target is
    /// an op index within the current chunk.
    Break(u16),
    /// Pop bool; if true, forward jump past enclosing EndLoop.
    /// Target is an op index within the current chunk.
    BreakIf(u16),

    // -- Streaming --
    /// Stream block entry marker. No-op at runtime.
    Stream,
    /// Clear arena, return VmState::Reset to host.
    Reset,

    // -- Functions --
    /// Call compiled function by chunk index with N arguments.
    Call(u16, u8),
    /// Return from the current function.
    Return,

    /// Yield: pop output value, suspend. On resume, input is pushed.
    Yield,

    /// Duplicate top of stack.
    Dup,

    /// Build struct from template. Pop field_count values in field order.
    NewStruct(u16),
    /// Build enum variant. Pop arg_count values.
    NewEnum(u16, u16, u8),
    /// Build array from top N stack values.
    NewArray(u16),
    /// Build tuple from top N stack values.
    NewTuple(u8),

    /// Pop struct, push field value by name (const pool index).
    GetField(u16),
    /// Pop index (Int), pop array, push element.
    GetIndex,
    /// Pop tuple, push element at literal index.
    GetTupleField(u8),
    /// Pop enum, push field at literal index.
    GetEnumField(u8),
    /// Pop composite value, push its length as Int.
    Len,

    /// Peek at TOS: push true if matching enum type and variant, false otherwise.
    IsEnum(u16, u16),
    /// Peek at TOS: push true if matching struct type, false otherwise.
    IsStruct(u16),

    /// Cast i64 to f64.
    IntToFloat,
    /// Cast f64 to i64 (truncation).
    FloatToInt,
    /// Cast `Word` to `Byte`. Pops a `Value::Int`, masks to the
    /// low eight bits, pushes `Value::Byte`. Defined for any
    /// `Value::Int`; out-of-range Words wrap mod 256.
    WordToByte,
    /// Cast `Byte` to `Word`. Pops a `Value::Byte`, zero-extends
    /// to `i64`, pushes `Value::Int`.
    ByteToWord,
    /// Cast `Word` to `Fixed` with the given fraction-bit count.
    /// Pops a `Value::Int`, left-shifts by `frac_bits`, pushes
    /// `Value::Fixed`. Overflow saturates at `i64::MAX`/`MIN`.
    WordToFixed(u8),
    /// Cast `Fixed` (with the given fraction-bit count) to `Word`.
    /// Pops a `Value::Fixed`, arithmetic-right-shifts by
    /// `frac_bits`, pushes `Value::Int`. Truncates toward
    /// negative infinity per arithmetic shift.
    FixedToWord(u8),
    /// Multiply two `Fixed` operands sharing the given fraction-bit
    /// count. Pops two `Value::Fixed`, computes
    /// `(a as i128 * b as i128) >> frac_bits`, pushes
    /// `Value::Fixed`. Saturates at `i64::MAX`/`MIN` on overflow.
    FixedMul(u8),
    /// Divide two `Fixed` operands sharing the given fraction-bit
    /// count. Pops two `Value::Fixed`, computes
    /// `(a as i128 << frac_bits) / b as i128`, pushes
    /// `Value::Fixed`. Saturates at `i64::MAX`/`MIN`. Returns
    /// `VmError::DivisionByZero` for `b == 0`.
    FixedDiv(u8),

    /// Halt execution with a runtime error.
    Trap(u16),

    /// Overflow-checked Word addition. Pops two `Value::Int`
    /// operands, computes the true sum in `i128`, and pushes three
    /// slots: the high 64 bits as `Value::Int`, the low 64 bits as
    /// `Value::Int`, and an outcome flag `Value::Int(0)` (ok),
    /// `Value::Int(1)` (overflow), or `Value::Int(2)` (underflow).
    /// The compiler stashes all three into temporary locals at the
    /// dispatch site. The construct's surface form is `expr {
    /// ok(v) => ..., overflow(h, l) => ..., underflow(h, l) =>
    /// ... }`.
    CheckedAdd,
    /// Overflow-checked Word subtraction. Same stack effect as
    /// `Op::CheckedAdd`. The true difference is computed in `i128`
    /// and split into high and low halves before the flag.
    CheckedSub,
    /// Overflow-checked Word multiplication. Same stack effect.
    /// The true product is computed in `i128`; the high half is
    /// the load-bearing value for big-number multiplication.
    CheckedMul,
    /// Overflow-checked Word negation. Pops one `Value::Int` and
    /// pushes three slots in the same shape: high, low, flag. The
    /// only overflow case is `-i64::MIN`, in which the high half
    /// is `0` and the low half is `i64::MIN` (the wrapped result).
    CheckedNeg,
    /// Overflow-checked Word division. Same stack shape as the
    /// other `Op::Checked*` variants: pops two operands and pushes
    /// `(high, low, flag)`. Division by zero traps with
    /// `VmError::DivisionByZero` as usual. The only overflow case
    /// is `i64::MIN / -1`, whose true mathematical result is
    /// `2^63` and does not fit in `Word`; the construct routes to
    /// the overflow arm with `high = 0`, `low = i64::MIN`. All
    /// other inputs route through the ok arm with `high = 0` and
    /// the wrapped quotient as `low`.
    CheckedDiv,
    /// Overflow-checked Word modulo. Same stack shape. Division
    /// by zero traps. The only overflow case is `i64::MIN % -1`,
    /// whose mathematical result is `0` but whose computation
    /// overflows on the underlying `i64::MIN / -1`. The construct
    /// routes to the overflow arm with `high = 0`, `low = 0` in
    /// that case. All other inputs route through ok with `high =
    /// 0` and the wrapped remainder as `low`.
    CheckedMod,

    // -- V0.2.0 ISA additions (B20). Additive in Phase 1; compiler
    // -- emission and removal of legacy opcodes lands in later phases.
    /// Push an inline immediate value. Encoding:
    /// `0 = Unit`, `1 = true`, `2 = false`, `3 = None`,
    /// `4..19 = Int(operand - 4)`, `20..255 = reserved`.
    PushImmediate(u8),

    /// Pop `n` values from the top of the stack and discard them.
    /// Replaces single-slot `Op::Pop` and multi-slot pop sequences.
    /// `n = 0` is a no-op (admissible but redundant).
    PopN(u8),

    /// Bitwise AND of two `Value::Int` operands. Pops two, pushes one.
    BitAnd,
    /// Bitwise OR of two `Value::Int` operands. Pops two, pushes one.
    BitOr,
    /// Bitwise XOR of two `Value::Int` operands. Pops two, pushes one.
    BitXor,
    /// Logical shift-left of a `Value::Int` by a `Value::Int` count.
    /// Count is masked to the word width (`count & (word_bits - 1)`)
    /// so behavior is defined for all counts. Pops count then value;
    /// pushes the shifted value.
    Shl,
    /// Arithmetic right shift of a `Value::Int` by a `Value::Int`
    /// count (sign-preserving). Count is masked to the word width.
    /// Pops count then value; pushes the shifted value.
    Shr,

    /// Call a verified native function with attested WCET/WCMU
    /// bounds. Cost folds into the iteration's WCET/WCMU budget per
    /// host attestation. Emitted by the compiler for `use module::name`
    /// imports. The runtime cross-checks the registered native's
    /// classification at `Vm::new`; a native registered through
    /// `register_external_native` referenced here is rejected at
    /// load time.
    CallVerifiedNative(u16, u8),

    /// Call an external native function. Iteration cost budget
    /// pauses for the call duration; the verifier tracks invocation
    /// count per iteration instead of per-call cost. Emitted by the
    /// compiler for `use external module::name` imports. The runtime
    /// cross-checks the registered native's classification at
    /// `Vm::new`; a native registered through
    /// `register_verified_native` referenced here is rejected at
    /// load time.
    CallExternalNative(u16, u8),
}

/// Size in bytes of one operand-stack slot, namely the size of `Value` on
/// the modern 64-bit target. The actual `core::mem::size_of::<Value>()` is
/// implementation-dependent and may include padding to align variant
/// discriminators. For WCMU analysis, the conservative upper bound is
/// chosen so that the analysis remains sound even if the runtime
/// representation grows.
///
/// On the V0.0 cycle target (R33), this constant is 32 bytes. Future work
/// under B10 may parameterize this by target through a [`CostModel`].
pub const VALUE_SLOT_SIZE_BYTES: u32 = 32;

/// Context passed to an [`OpCost::Dynamic`] cost evaluator.
///
/// Carries the abstract-interpretation results that bear on the
/// opcode's cost. The WCMU text-size tracking pass populates the
/// `lhs_text_len` and `rhs_text_len` fields when evaluating the
/// heap-allocation cost of text-producing opcodes (`Op::Add` on
/// text, plus host-registered text-producing natives). Fields that
/// the analysis cannot bound are reported as `u32::MAX` (the
/// saturation value for the length lattice), which conservatively
/// propagates an "unbounded" verdict to the surrounding analysis.
///
/// Forward-looking. Populated stubbed-out in V0.2.0; the WCMU
/// text-size tracking pass in V0.2.x is the first consumer.
#[derive(Clone, Copy, Debug, Default)]
pub struct OpCostContext {
    /// Upper-bound length in bytes of the left text operand for
    /// text-producing opcodes. `u32::MAX` denotes unbounded.
    pub lhs_text_len: u32,
    /// Upper-bound length in bytes of the right text operand for
    /// text-producing opcodes. `u32::MAX` denotes unbounded.
    pub rhs_text_len: u32,
}

/// Cost of an opcode under a [`CostModel`].
///
/// `Fixed(n)` is the existing case where the cost is a compile-time
/// constant per opcode. For example, `Op::Add` on `i64` operands
/// always costs two pipelined cycles regardless of operand values.
///
/// `Dynamic(f)` is for operations whose cost depends on runtime
/// data. The concrete motivating case is the heap byte allocation
/// of `Op::Add` on text operands, where the resulting `KString`
/// length is the sum of the operand lengths. The WCMU pass
/// invokes the dynamic variant with an [`OpCostContext`] populated
/// from the abstract-interpretation results; the WCET pass
/// currently treats `Dynamic` as a sentinel forwarding to the
/// abstract-interpretation pass.
///
/// Hosts that supply a custom cost model may choose `Fixed` for
/// all opcodes if they prefer a simpler accounting model. The
/// abstract-interpretation pass falls back to a conservative
/// upper bound when a dynamic cost cannot be evaluated.
#[derive(Clone, Copy)]
pub enum OpCost {
    /// Cost is a compile-time constant per opcode.
    Fixed(u32),
    /// Cost depends on runtime data carried in [`OpCostContext`].
    Dynamic(fn(&OpCostContext) -> u32),
}

impl OpCost {
    /// Evaluate the cost against a context. `Fixed` returns the
    /// inner value directly; `Dynamic` invokes the function pointer
    /// against the supplied context.
    pub fn evaluate(&self, ctx: &OpCostContext) -> u32 {
        match self {
            OpCost::Fixed(n) => *n,
            OpCost::Dynamic(f) => f(ctx),
        }
    }
}

/// Per-target cost model used by the WCET and WCMU analyses.
///
/// Units. WCMU is reported in **bytes**. WCET is reported in
/// **pipelined cycles**. A pipelined cycle is a CPU cycle in which
/// the host's pipeline operates at steady-state throughput, assuming
/// warm instruction and data caches, correctly predicted branches,
/// and no contention on the memory bus. The pipelined-cycle metric
/// is what CPU optimization tables call "throughput" or "reciprocal
/// throughput" per instruction. It is observable through standard
/// benchmarking with warm caches and a stable predictor.
///
/// What the analysis bounds, and what it does not. The pipelined-
/// cycle bound is sound for the abstract metric. Actual cycles on
/// real hardware exceed the bound by the host's stall budget,
/// covering cache misses, branch mispredictions, and memory-bus
/// contention. Wall-clock time additionally depends on the clock
/// period and on frequency scaling. The conversion from pipelined-
/// cycle bound to wall-clock WCET is a platform-specific scalar,
/// conventionally called the calibration factor or dilation factor
/// in the WCET literature. The host establishes this factor during
/// deployment validation. For many practical applications, the
/// pipelined-cycle bound multiplied by a measured calibration factor
/// is an effective approximation of the worst-case wall-clock
/// execution time.
///
/// Custom cost models. Hosts construct a `CostModel` by setting
/// `value_slot_bytes` to the runtime's value-slot size and
/// `op_cycles` to a function pointer that returns the pipelined-cycle
/// cost for each opcode. The function pointer is reentrant and must
/// not allocate or fail. The convention is that the function
/// pattern-matches on the `Op` variant and returns the corresponding
/// cycle count from a target-specific table.
///
/// The bundled [`NOMINAL_COST_MODEL`] supplies unmeasured pipelined-
/// cycle estimates that the existing analysis APIs use when no
/// custom model is provided. The estimates are suitable for relative
/// ordering of programs on a single platform but are not validated
/// against any specific host CPU.
#[derive(Clone, Copy)]
pub struct CostModel {
    /// Bytes per operand-stack slot for the host runtime. Determines
    /// the conversion from slot count to byte count in the WCMU
    /// analysis. The current 64-bit Keleusma runtime uses 32 bytes
    /// per slot; a future 32-bit runtime would use a smaller value.
    pub value_slot_bytes: u32,

    /// Function returning the nominal cycle cost for the given
    /// opcode. The nominal cost model uses an unmeasured table whose
    /// values are relative weights rather than measured cycles.
    /// Hosts override this for measured per-target cycle tables.
    pub op_cycles: fn(&Op) -> u32,
}

impl CostModel {
    /// Compute the nominal cycle cost for the opcode under this
    /// cost model.
    pub fn cycles(&self, op: &Op) -> u32 {
        (self.op_cycles)(op)
    }

    /// Compute the WCMU byte cost of an operand-stack slot count
    /// under this cost model.
    pub fn slots_to_bytes(&self, slots: u32) -> u32 {
        slots.saturating_mul(self.value_slot_bytes)
    }

    /// Compute the heap byte allocation for the opcode under this
    /// cost model. For composite-construction opcodes, multiplies
    /// the field count by the cost model's `value_slot_bytes`.
    /// Text-producing opcodes (`Op::Add` on text) are reported via
    /// [`Self::heap_alloc_cost`] as [`OpCost::Dynamic`]; the
    /// fixed-cost view returned here saturates such cases to zero
    /// because the heap cost is not knowable without abstract
    /// interpretation. The WCMU pass that tracks text sizes must
    /// use [`Self::heap_alloc_cost`] instead.
    pub fn heap_alloc_bytes(&self, op: &Op, chunk: &Chunk) -> u32 {
        match self.heap_alloc_cost(op, chunk) {
            OpCost::Fixed(n) => n,
            OpCost::Dynamic(_) => 0,
        }
    }

    /// Compute the heap allocation cost for the opcode under this
    /// cost model as an [`OpCost`].
    ///
    /// Composite-construction opcodes (struct, enum, array, tuple)
    /// report `OpCost::Fixed` because their size is known at the
    /// opcode site. `Op::Add` on text operands reports
    /// `OpCost::Dynamic` because the allocated `KString` length is
    /// the sum of the operand lengths, which the verifier learns
    /// only through the abstract-interpretation text-size pass.
    pub fn heap_alloc_cost(&self, op: &Op, chunk: &Chunk) -> OpCost {
        match op {
            Op::NewStruct(template_idx) => {
                let idx = *template_idx as usize;
                let field_count = chunk
                    .struct_templates
                    .get(idx)
                    .map_or(0, |t| t.field_names.len() as u32);
                OpCost::Fixed(self.slots_to_bytes(field_count))
            }
            Op::NewEnum(_, _, n) => OpCost::Fixed(self.slots_to_bytes(*n as u32)),
            Op::NewArray(n) => OpCost::Fixed(self.slots_to_bytes(*n as u32)),
            Op::NewTuple(n) => OpCost::Fixed(self.slots_to_bytes(*n as u32)),
            Op::Add => OpCost::Dynamic(add_text_heap_alloc_bytes),
            _ => OpCost::Fixed(0),
        }
    }
}

/// Dynamic heap-allocation cost for `Op::Add` on text operands.
///
/// Returns the sum of the operand lengths saturated at `u32::MAX`.
/// The WCMU pass evaluates this against an [`OpCostContext`]
/// populated from the per-slot text-size lattice. When either
/// operand length is `u32::MAX` (unbounded), the result saturates
/// to `u32::MAX` so the outer analysis propagates an unbounded
/// verdict.
fn add_text_heap_alloc_bytes(ctx: &OpCostContext) -> u32 {
    ctx.lhs_text_len.saturating_add(ctx.rhs_text_len)
}

/// Default cost model for the bundled runtime. WCMU value-slot size
/// matches the runtime's `VALUE_SLOT_SIZE_BYTES`. WCET pipelined
/// cycles come from the unmeasured table provided by
/// [`nominal_op_cycles`].
///
/// **Pipelined-cycle caveat.** The bundled values are unmeasured
/// estimates chosen for relative ordering, not measured pipelined
/// cycles for any specific host CPU. The scale is one cycle for data
/// movement and trivial control flow, two for arithmetic and
/// comparison, three for division and field lookup, five for
/// composite construction, ten for function calls. A program whose
/// pipelined-cycle WCET exceeds another program's pipelined-cycle
/// WCET on the same platform is more expensive in the relative
/// sense. Hosts that need a wall-clock bound apply a platform-
/// specific calibration factor to convert pipelined cycles to actual
/// cycles and to wall-clock time. A measured-cycle CostModel
/// improves the approximation by replacing the bundled estimates
/// with measured pipelined cycles for the target CPU.
pub const NOMINAL_COST_MODEL: CostModel = CostModel {
    value_slot_bytes: VALUE_SLOT_SIZE_BYTES,
    op_cycles: nominal_op_cycles,
};

/// The pipelined-cycle cost table used by [`NOMINAL_COST_MODEL`].
/// Returns unmeasured pipelined-cycle estimates per the documented
/// scale. The values are intended to be replaced with measured
/// pipelined cycles during deployment validation.
pub fn nominal_op_cycles(op: &Op) -> u32 {
    match op {
        Op::Const(_)
        | Op::GetLocal(_)
        | Op::SetLocal(_)
        | Op::GetData(_)
        | Op::SetData(_)
        | Op::Dup
        | Op::Not => 1,

        Op::If(_)
        | Op::Else(_)
        | Op::EndIf
        | Op::Loop(_)
        | Op::EndLoop(_)
        | Op::Break(_)
        | Op::BreakIf(_)
        | Op::Stream
        | Op::Reset
        | Op::Yield
        | Op::Trap(_) => 1,

        Op::Add
        | Op::Sub
        | Op::CheckedAdd
        | Op::CheckedSub
        | Op::CheckedMul
        | Op::CheckedNeg
        | Op::CheckedDiv
        | Op::CheckedMod
        | Op::Mul
        | Op::Neg
        | Op::CmpEq
        | Op::CmpNe
        | Op::CmpLt
        | Op::CmpGt
        | Op::CmpLe
        | Op::CmpGe
        | Op::GetIndex
        | Op::GetTupleField(_)
        | Op::GetEnumField(_)
        | Op::Len
        | Op::IntToFloat
        | Op::FloatToInt
        | Op::WordToByte
        | Op::ByteToWord
        | Op::WordToFixed(_)
        | Op::FixedToWord(_)
        | Op::FixedMul(_)
        | Op::FixedDiv(_)
        | Op::Return
        | Op::GetDataIndexed(_, _)
        | Op::SetDataIndexed(_, _)
        | Op::BoundsCheck(_) => 2,

        Op::Div | Op::Mod | Op::GetField(_) | Op::IsEnum(_, _) | Op::IsStruct(_) => 3,

        Op::NewStruct(_) | Op::NewEnum(_, _, _) | Op::NewArray(_) | Op::NewTuple(_) => 5,

        Op::Call(_, _) => 10,

        // V0.2.0 ISA additions.
        Op::PushImmediate(_) | Op::PopN(_) => 1,
        Op::BitAnd | Op::BitOr | Op::BitXor | Op::Shl | Op::Shr => 2,
        Op::CallVerifiedNative(_, _) | Op::CallExternalNative(_, _) => 10,
    }
}

impl Op {
    /// Return the WCET cost of this instruction in **pipelined
    /// cycles** per the [`NOMINAL_COST_MODEL`].
    ///
    /// **Unit.** The result is a count of pipelined cycles. A
    /// pipelined cycle is a CPU cycle in which the host's pipeline
    /// operates at steady-state throughput, assuming warm caches,
    /// correctly predicted branches, and no memory-bus contention.
    /// The bundled values are unmeasured estimates chosen for
    /// relative ordering of programs on a single platform. The scale
    /// is one cycle for data movement and trivial control flow, two
    /// for arithmetic and comparison, three for division and field
    /// lookup, five for composite construction, ten for function
    /// calls. The values are not validated against any specific host
    /// CPU. Hosts that need wall-clock WCET apply a platform-specific
    /// calibration factor to the pipelined-cycle bound, or construct
    /// a custom [`CostModel`] whose `op_cycles` returns measured
    /// pipelined cycles for the target hardware.
    ///
    /// This method is a thin wrapper over [`NOMINAL_COST_MODEL`].
    /// Analysis APIs that take an explicit `&CostModel` parameter
    /// allow per-target cost tables to flow through without changing
    /// the rest of the analysis.
    pub fn cost(&self) -> u32 {
        NOMINAL_COST_MODEL.cycles(self)
    }

    /// Number of operand-stack slots pushed by this instruction.
    ///
    /// This is the maximum the operand stack can grow during execution of
    /// this single instruction relative to its starting depth. Used by the
    /// WCMU analysis to compute peak stack consumption.
    pub fn stack_growth(&self) -> u32 {
        match self {
            Op::Const(_) | Op::GetLocal(_) | Op::GetData(_) | Op::Dup => 1,

            Op::Not | Op::Neg => 0,

            // CheckedAdd / CheckedSub / CheckedMul / CheckedDiv /
            // CheckedMod pop two operands and push (high, low,
            // flag); net delta +1. CheckedNeg pops one and pushes
            // three; net delta +2. The high half is the i128
            // intermediate's high 64 bits, providing the load-
            // bearing value for big-number multiplication.
            Op::CheckedAdd | Op::CheckedSub | Op::CheckedMul | Op::CheckedDiv | Op::CheckedMod => 1,
            Op::CheckedNeg => 2,

            Op::Add
            | Op::Sub
            | Op::Mul
            | Op::Div
            | Op::Mod
            | Op::CmpEq
            | Op::CmpNe
            | Op::CmpLt
            | Op::CmpGt
            | Op::CmpLe
            | Op::CmpGe => 0,

            Op::SetLocal(_) | Op::SetData(_) => 0,

            // GetDataIndexed pops one index, pushes one value.
            Op::GetDataIndexed(_, _) => 1,
            // SetDataIndexed pops index and value.
            Op::SetDataIndexed(_, _) => 0,
            // BoundsCheck does not change the stack.
            Op::BoundsCheck(_) => 0,

            Op::If(_) | Op::BreakIf(_) => 0,
            Op::Else(_) | Op::EndIf | Op::Loop(_) | Op::EndLoop(_) | Op::Break(_) => 0,
            Op::Stream | Op::Reset => 0,
            Op::Yield => 0,

            Op::Call(_, _) => 1,
            Op::Return => 0,

            Op::NewStruct(_) | Op::NewEnum(_, _, _) | Op::NewArray(_) | Op::NewTuple(_) => 1,

            Op::GetField(_)
            | Op::GetIndex
            | Op::GetTupleField(_)
            | Op::GetEnumField(_)
            | Op::Len => 0,

            Op::IsEnum(_, _) | Op::IsStruct(_) => 0,

            Op::IntToFloat
            | Op::FloatToInt
            | Op::WordToByte
            | Op::ByteToWord
            | Op::WordToFixed(_)
            | Op::FixedToWord(_) => 0,
            Op::FixedMul(_) | Op::FixedDiv(_) => 0,

            Op::Trap(_) => 0,

            // V0.2.0 ISA additions.
            Op::PushImmediate(_) => 1,
            Op::PopN(_) => 0,
            Op::BitAnd | Op::BitOr | Op::BitXor | Op::Shl | Op::Shr => 0,
            Op::CallVerifiedNative(_, _) | Op::CallExternalNative(_, _) => 1,
        }
    }

    /// Number of operand-stack slots popped by this instruction.
    pub fn stack_shrink(&self) -> u32 {
        match self {
            Op::Const(_) | Op::GetLocal(_) | Op::GetData(_) | Op::Dup => 0,

            Op::Not | Op::Neg => 0,

            // CheckedAdd / CheckedSub / CheckedMul / CheckedDiv /
            // CheckedMod net +1 (pop 2, push 3). CheckedNeg net +2
            // (pop 1, push 3). The growth/shrink split records
            // peak vs. final; shrink is zero because there is no
            // net pop.
            Op::CheckedAdd
            | Op::CheckedSub
            | Op::CheckedMul
            | Op::CheckedNeg
            | Op::CheckedDiv
            | Op::CheckedMod => 0,

            Op::Add
            | Op::Sub
            | Op::Mul
            | Op::Div
            | Op::Mod
            | Op::CmpEq
            | Op::CmpNe
            | Op::CmpLt
            | Op::CmpGt
            | Op::CmpLe
            | Op::CmpGe => 1,

            Op::SetLocal(_) | Op::SetData(_) => 1,

            // GetDataIndexed pops the index, SetDataIndexed pops the
            // index then the value, BoundsCheck does not pop.
            Op::GetDataIndexed(_, _) => 1,
            Op::SetDataIndexed(_, _) => 2,
            Op::BoundsCheck(_) => 0,

            Op::If(_) | Op::BreakIf(_) => 1,
            Op::Else(_) | Op::EndIf | Op::Loop(_) | Op::EndLoop(_) | Op::Break(_) => 0,
            Op::Stream | Op::Reset => 0,
            Op::Yield => 1,

            Op::Call(_, n) => *n as u32,
            Op::Return => 0,

            Op::NewStruct(_) => 0,
            Op::NewEnum(_, _, n) => *n as u32,
            Op::NewArray(n) => *n as u32,
            Op::NewTuple(n) => *n as u32,

            Op::GetField(_) | Op::GetIndex | Op::GetTupleField(_) | Op::GetEnumField(_) => 1,
            Op::Len => 0,

            Op::IsEnum(_, _) | Op::IsStruct(_) => 0,

            Op::IntToFloat
            | Op::FloatToInt
            | Op::WordToByte
            | Op::ByteToWord
            | Op::WordToFixed(_)
            | Op::FixedToWord(_) => 0,
            Op::FixedMul(_) | Op::FixedDiv(_) => 0,

            Op::Trap(_) => 0,

            // V0.2.0 ISA additions.
            Op::PushImmediate(_) => 0,
            Op::PopN(n) => *n as u32,
            // Bit ops pop 2, push 1; net shrink = 1 in the same
            // convention as `Add` etc.
            Op::BitAnd | Op::BitOr | Op::BitXor | Op::Shl | Op::Shr => 1,
            Op::CallVerifiedNative(_, n) | Op::CallExternalNative(_, n) => *n as u32,
        }
    }

    /// WCMU heap allocation by this instruction in **bytes** under
    /// the [`NOMINAL_COST_MODEL`].
    ///
    /// **Unit.** The result is a count of bytes. The byte count is
    /// computed as the field-slot count multiplied by the cost
    /// model's `value_slot_bytes`. The slot count is target-
    /// independent (a structural property of the opcode); the byte
    /// conversion depends on the runtime's value representation.
    ///
    /// For composite-construction instructions, the size is the count
    /// of stored field slots times `value_slot_bytes`. For
    /// `NewStruct`, the field count comes from the chunk's struct
    /// templates and is looked up through the provided `chunk`
    /// reference.
    ///
    /// Calls and native calls report zero local heap. The transitive
    /// heap contribution of a `Call` is the WCMU of the called
    /// function and is computed at the analysis level. The heap
    /// contribution of a `CallNative` comes from the host's WCMU
    /// attestation recorded against the native function entry.
    ///
    /// This method is a thin wrapper over
    /// [`CostModel::heap_alloc_bytes`] using [`NOMINAL_COST_MODEL`].
    /// Analysis APIs that take an explicit `&CostModel` allow
    /// per-target value-slot sizes to flow through without changing
    /// the rest of the analysis.
    pub fn heap_alloc(&self, chunk: &Chunk) -> u32 {
        NOMINAL_COST_MODEL.heap_alloc_bytes(self, chunk)
    }
}

/// Template for struct construction.
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct StructTemplate {
    /// Struct type name.
    pub type_name: String,
    /// Field names in order.
    pub field_names: Vec<String>,
}

/// A named slot in the data segment.
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct DataSlot {
    /// Slot name (for host initialization and debugging).
    pub name: String,
    /// Slot visibility to the host. Shared slots are accessible
    /// through `Vm::set_data` and `Vm::get_data`. Private slots
    /// are script-only; the host API rejects access. Both
    /// persist across resets. Source declaration uses the
    /// `shared` (default) and `private` modifiers on `data`
    /// blocks.
    pub visibility: SlotVisibility,
}

/// Slot visibility flag carried in [`DataSlot::visibility`].
///
/// Mirrors `ast::DataVisibility` at the bytecode layer so the
/// runtime can enforce the host-API boundary without reading
/// the source AST. Serialized as part of the data layout in the
/// bytecode body; it is not part of the framing header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub enum SlotVisibility {
    /// Host-visible slot. The default. `Vm::set_data` and
    /// `Vm::get_data` admit this slot.
    Shared,
    /// Script-only slot. The host API rejects this slot.
    Private,
}

/// Data segment layout declaration.
///
/// Defines the fixed-size, fixed-layout set of persistent values that
/// survive across RESET boundaries. The host initializes data slots
/// before execution begins. Scripts read and write slots by index.
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct DataLayout {
    /// Named slots in declaration order. Slot index corresponds to
    /// the `GetData`/`SetData` operand.
    pub slots: Vec<DataSlot>,
}

/// A compiled function.
///
/// V0.2.0 Phase 7c moved the on-the-wire representation to
/// [`crate::wire_format::WireChunk`], which carries the same
/// per-chunk metadata minus the ops (which live in the opcode
/// stream section). `Chunk` is the in-memory representation;
/// the rkyv derives retire in Phase 8.
#[derive(Debug, Clone)]
pub struct Chunk {
    /// Function name (for debugging and lookup).
    pub name: String,
    /// Bytecode instructions.
    pub ops: Vec<Op>,
    /// Constant pool. Stores compile-time constants only.
    pub constants: Vec<ConstValue>,
    /// Struct field layout templates.
    pub struct_templates: Vec<StructTemplate>,
    /// Total local variable slots (including parameters).
    pub local_count: u16,
    /// Number of parameters.
    pub param_count: u8,
    /// Block type classification for structural verification.
    pub block_type: BlockType,
    /// Parameter type tags, one per parameter. Used by
    /// `Vm::call` to reject ill-typed arguments before any
    /// bytecode runs. Composite types (struct, enum, tuple,
    /// array, option, opaque) record [`TypeTag::Composite`]
    /// which the runtime accepts without further checking.
    /// For Stream chunks, the single entry also serves as the
    /// resume value's type (see [`crate::vm::Vm::resume`]).
    pub param_types: Vec<TypeTag>,
}

/// Compact representation of a primitive parameter type for
/// runtime call validation. Composite types (struct, enum,
/// tuple, array, option, opaque, function values) collapse to
/// [`TypeTag::Composite`]; the runtime accepts any non-primitive
/// `Value` for a `Composite` parameter without further checking.
///
/// Fixed-point types record only the canonical tag and not the
/// fraction-bit count; the type checker has already enforced
/// fraction-bit compatibility at compile time, so the runtime
/// only needs to confirm the operand is `Value::Fixed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub enum TypeTag {
    /// Non-primitive type. The runtime does not check shape; any
    /// `Value` is accepted.
    Composite,
    /// Eight-bit unsigned integer. Accepts `Value::Byte`.
    Byte,
    /// Target-word signed integer. Accepts `Value::Int`.
    Word,
    /// Signed Q-format fixed-point. Accepts `Value::Fixed`.
    Fixed,
    /// Target-float. Accepts `Value::Float`.
    Float,
    /// Boolean. Accepts `Value::Bool`.
    Bool,
    /// Unit `()`. Accepts `Value::Unit`.
    Unit,
    /// UTF-8 text. Accepts `Value::StaticStr` or `Value::KStr`.
    Text,
}

impl TypeTag {
    /// Lift an [`ArchivedTypeTag`] into a [`TypeTag`]. The archive
    /// form is a unit-variant enum with the same discriminant
    /// layout, so the lift is a one-to-one match.
    pub fn from_archived(archived: &ArchivedTypeTag) -> Self {
        match archived {
            ArchivedTypeTag::Composite => TypeTag::Composite,
            ArchivedTypeTag::Byte => TypeTag::Byte,
            ArchivedTypeTag::Word => TypeTag::Word,
            ArchivedTypeTag::Fixed => TypeTag::Fixed,
            ArchivedTypeTag::Float => TypeTag::Float,
            ArchivedTypeTag::Bool => TypeTag::Bool,
            ArchivedTypeTag::Unit => TypeTag::Unit,
            ArchivedTypeTag::Text => TypeTag::Text,
        }
    }

    /// Returns `true` if `value` is admissible for a parameter
    /// declared with this tag. Generic over the parametric value
    /// type so the bundled `Vm<i64, u64, f64>` and a host-
    /// instantiated narrower `Vm<W, A, F>` share the same check.
    pub fn admits<W: crate::word::Word, F: crate::float::Float>(
        &self,
        value: &GenericValue<W, F>,
    ) -> bool {
        match self {
            TypeTag::Composite => true,
            TypeTag::Byte => matches!(value, GenericValue::Byte(_)),
            TypeTag::Word => matches!(value, GenericValue::Int(_)),
            TypeTag::Fixed => matches!(value, GenericValue::Fixed(_)),
            #[cfg(feature = "floats")]
            TypeTag::Float => matches!(value, GenericValue::Float(_)),
            #[cfg(not(feature = "floats"))]
            TypeTag::Float => false,
            TypeTag::Bool => matches!(value, GenericValue::Bool(_)),
            TypeTag::Unit => matches!(value, GenericValue::Unit),
            TypeTag::Text => {
                matches!(value, GenericValue::StaticStr(_) | GenericValue::KStr(_))
            }
        }
    }

    /// Human-readable name for the tag, suitable for error
    /// messages.
    pub fn name(&self) -> &'static str {
        match self {
            TypeTag::Composite => "Composite",
            TypeTag::Byte => "Byte",
            TypeTag::Word => "Word",
            TypeTag::Fixed => "Fixed",
            TypeTag::Float => "Float",
            TypeTag::Bool => "Bool",
            TypeTag::Unit => "Unit",
            TypeTag::Text => "Text",
        }
    }
}

/// A compiled Keleusma module.
///
/// V0.2.0 Phase 7c cut the on-the-wire serialization over to
/// the section-partitioned wire format defined in
/// [`crate::wire_format`]; the rkyv archive of the full
/// `Module` is no longer produced or consumed. `Module` is the
/// in-memory representation; serialization flows through
/// `Module::to_bytes` -> `module_to_wire_bytes` and
/// deserialization through `module_from_wire_bytes` ->
/// `Module`. The Phase 8 publication readiness pass drops the
/// rkyv derives.
#[derive(Debug, Clone)]
pub struct Module {
    /// Compiled function chunks.
    pub chunks: Vec<Chunk>,
    /// Declared native function names (from `use` declarations).
    pub native_names: Vec<String>,
    /// Entry point chunk index (the `main` function).
    pub entry_point: Option<usize>,
    /// Data segment layout. If present, defines persistent slots that
    /// survive across RESET boundaries.
    pub data_layout: Option<DataLayout>,
    /// Word size required by this bytecode, encoded as the base-2
    /// exponent. Actual width in bits is `1 << word_bits_log2`. The
    /// runtime accepts the bytecode when the recorded value is at most
    /// the runtime's `RUNTIME_WORD_BITS_LOG2`. The VM masks integer
    /// arithmetic to the declared width using sign-extending shift.
    /// Mirrored in the framing header for fast pre-decode rejection.
    pub word_bits_log2: u8,
    /// Address size required by this bytecode, encoded as the base-2
    /// exponent. Actual width in bits is `1 << addr_bits_log2`. The
    /// runtime accepts the bytecode when the recorded value is at most
    /// the runtime's `RUNTIME_ADDRESS_BITS_LOG2`. Mirrored in the
    /// framing header for fast pre-decode rejection.
    pub addr_bits_log2: u8,
    /// Floating-point width required by this bytecode, encoded as the
    /// base-2 exponent. Actual width in bits is `1 << float_bits_log2`.
    /// The runtime accepts the bytecode when the recorded value is at
    /// most the runtime's `RUNTIME_FLOAT_BITS_LOG2`. The current
    /// runtime uses f64 exclusively (exponent 6); narrower or wider
    /// floats are reserved for future portability work tracked under
    /// B10. Mirrored in the framing header for fast pre-decode
    /// rejection.
    pub float_bits_log2: u8,
    /// Declared worst-case execution time per Stream-to-Reset slice,
    /// in pipelined cycles. Producer's claim about the maximum cycles
    /// the script consumes between two yield boundaries.
    ///
    /// - `0` means **auto**: the producer did not declare a value;
    ///   the runtime computes the bound at load time through its own
    ///   verifier pass.
    /// - `u32::MAX` means **overflow**: the producer attempted to
    ///   compute the bound but the result exceeds the field's range.
    ///   Programs declaring `u32::MAX` are rejected at the safe
    ///   constructor `Vm::new` because no representable bound exists.
    /// - Any other value is the producer's bound. The safe runtime
    ///   accepts the value as-is; trust skip applies to declared
    ///   values just as it does to arena capacity.
    ///
    /// Mirrored in the framing header for inspection without body
    /// decode.
    pub wcet_cycles: u32,
    /// Declared worst-case memory usage per Stream-to-Reset slice,
    /// in bytes. Same `0`/`u32::MAX` conventions as
    /// [`Module::wcet_cycles`]. Total of stack and heap regions.
    /// Mirrored in the framing header.
    pub wcmu_bytes: u32,
    /// Bit flags describing static properties of the module.
    /// Currently defined bits.
    ///
    /// - `0x01` (`FLAG_EPHEMERAL`). The module is provably
    ///   ephemeral: at every yield or return that crosses the
    ///   host-VM boundary, no arena-resident value is observed,
    ///   and at every resume or entry no value loaded from arena
    ///   memory allocated prior to that resume or entry is read.
    ///   Hosts that observe this bit may reuse a single arena
    ///   across many modules of this kind, sized to the largest
    ///   module's WCMU.
    ///
    /// Unused bits are reserved for future declarations and must
    /// be zero. The runtime treats any unrecognised bits as
    /// reserved and ignores them.
    ///
    /// Mirrored in the framing header.
    pub flags: u8,
    /// Bytes of shared data declared by this module. Shared
    /// data lives in the Vm's owned slot storage and is
    /// host-visible through `Vm::set_data` and `Vm::get_data`.
    /// Survives RESET. Mirrored in the framing header.
    pub shared_data_bytes: u32,
    /// Bytes of private data declared by this module. Private
    /// data lives in the arena's persistent (`.data`) region
    /// and is not exposed through the host API. Survives
    /// RESET. The host sizes its arena's persistent capacity to
    /// match this value before loading the module. Mirrored in
    /// the framing header.
    pub private_data_bytes: u32,
    /// CRC-32 hash of the data-segment layout. Used by
    /// [`crate::vm::Vm::replace_module`] to reject hot swaps
    /// against incompatible schemas before any data is loaded.
    /// Computed from a canonical serialisation of each slot's
    /// name and visibility in declaration order; see
    /// [`compute_schema_hash`] for the exact byte sequence. A
    /// module with no data layout reports zero. The check is
    /// strict by default; hosts that need to swap across
    /// incompatible schemas (different data declaration, same
    /// arena capacity) call
    /// [`crate::vm::Vm::replace_module_unchecked`] to bypass it.
    pub schema_hash: u32,
}

/// Bit flags defined for [`Module::flags`].
///
/// See [`Module::flags`] for the semantic description of each bit.
/// Unused bits are reserved.
pub const FLAG_EPHEMERAL: u8 = 0x01;

/// Magic prefix identifying serialized Keleusma bytecode (`KELE`).
pub const BYTECODE_MAGIC: [u8; 4] = *b"KELE";

/// Wire format version for serialized bytecode. Bytecode produced under a
/// different version is rejected at load time.
///
/// V0.2 development releases briefly used version 2 before this crate
/// achieved public adoption; the version was rolled back to 1 when the
/// header was extended with the flags byte and the shared and private
/// data byte counts. Bytecode produced under any earlier development
/// build is rejected at load time on header-shape mismatch through the
/// CRC trailer.
pub const BYTECODE_VERSION: u16 = 1;

/// Word size in bits assumed by this binary build, encoded as the
/// base-2 exponent. Actual width in bits is `1 << RUNTIME_WORD_BITS_LOG2`.
/// Default value is `6` (64-bit words). The `narrow-word-8`,
/// `narrow-word-16`, and `narrow-word-32` Cargo features lower the
/// value to `3`, `4`, and `5` respectively, narrowing the framing-level
/// upper bound on bytecode this binary admits. The narrowest enabled
/// feature wins, preserving Cargo's additive-features semantics. See
/// B16 step 12 in `docs/decisions/BACKLOG.md` for the rationale.
#[cfg(feature = "narrow-word-8")]
pub const RUNTIME_WORD_BITS_LOG2: u8 = 3;
/// Word size in bits assumed by this binary build (log2 form).
#[cfg(all(feature = "narrow-word-16", not(feature = "narrow-word-8")))]
pub const RUNTIME_WORD_BITS_LOG2: u8 = 4;
/// Word size in bits assumed by this binary build (log2 form).
#[cfg(all(
    feature = "narrow-word-32",
    not(any(feature = "narrow-word-8", feature = "narrow-word-16"))
))]
pub const RUNTIME_WORD_BITS_LOG2: u8 = 5;
/// Word size in bits assumed by this binary build (log2 form).
#[cfg(not(any(
    feature = "narrow-word-8",
    feature = "narrow-word-16",
    feature = "narrow-word-32"
)))]
pub const RUNTIME_WORD_BITS_LOG2: u8 = 6;

/// Address size in bits assumed by this binary build, encoded as the
/// base-2 exponent. Actual width in bits is
/// `1 << RUNTIME_ADDRESS_BITS_LOG2`. Default value is `6` (64-bit
/// addresses). The `narrow-address-8`, `narrow-address-16`, and
/// `narrow-address-32` Cargo features lower the value following the
/// same narrowest-wins rule as `RUNTIME_WORD_BITS_LOG2`.
#[cfg(feature = "narrow-address-8")]
pub const RUNTIME_ADDRESS_BITS_LOG2: u8 = 3;
/// Address size in bits assumed by this binary build (log2 form).
#[cfg(all(feature = "narrow-address-16", not(feature = "narrow-address-8")))]
pub const RUNTIME_ADDRESS_BITS_LOG2: u8 = 4;
/// Address size in bits assumed by this binary build (log2 form).
#[cfg(all(
    feature = "narrow-address-32",
    not(any(feature = "narrow-address-8", feature = "narrow-address-16"))
))]
pub const RUNTIME_ADDRESS_BITS_LOG2: u8 = 5;
/// Address size in bits assumed by this binary build (log2 form).
#[cfg(not(any(
    feature = "narrow-address-8",
    feature = "narrow-address-16",
    feature = "narrow-address-32"
)))]
pub const RUNTIME_ADDRESS_BITS_LOG2: u8 = 6;

/// Floating-point width in bits assumed by this binary build,
/// encoded as the base-2 exponent. Actual width in bits is
/// `1 << RUNTIME_FLOAT_BITS_LOG2`. Default value is `6` (f64). The
/// `narrow-float-32` Cargo feature lowers the value to `5`,
/// rejecting f64 bytecode at the framing level.
#[cfg(feature = "narrow-float-32")]
pub const RUNTIME_FLOAT_BITS_LOG2: u8 = 5;
/// Floating-point width in bits assumed by this binary build (log2 form).
#[cfg(not(feature = "narrow-float-32"))]
pub const RUNTIME_FLOAT_BITS_LOG2: u8 = 6;

/// Header length in bytes. The fields are
///
/// - bytes 0..4: magic (`KELE`)
/// - bytes 4..6: version (u16 little-endian)
/// - bytes 6..10: total framing length (u32 little-endian, includes
///   header and CRC trailer)
/// - bytes 10..11: word_bits_log2 (u8). Actual width is `1 << value`.
/// - bytes 11..12: addr_bits_log2 (u8). Actual width is `1 << value`.
/// - bytes 12..13: float_bits_log2 (u8). Actual width is `1 << value`.
/// - bytes 13..14: flags (u8). Bit 0 is `FLAG_EPHEMERAL`. Other
///   bits reserved and must be zero.
/// - bytes 14..16: reserved (zero), preserved for backward layout.
/// - bytes 16..20: declared WCET in pipelined cycles per Stream-to-Reset
///   slice (u32 little-endian). `0` means auto (runtime computes).
///   `u32::MAX` means overflow (rejected at safe `Vm::new`).
/// - bytes 20..24: declared WCMU in bytes per Stream-to-Reset slice
///   (u32 little-endian). Same `0`/`u32::MAX` conventions.
/// - bytes 24..28: shared data bytes (u32 little-endian).
/// - bytes 28..32: private data bytes (u32 little-endian).
///
/// Reflected polynomial for the standard CRC-32 (IEEE 802.3, gzip, PNG,
/// ZIP). Reflected form of 0x04C11DB7. Paired with init 0xFFFFFFFF,
/// refin/refout true, and xor-out 0xFFFFFFFF. The V0.2.0 wire format
/// uses the residue self-inclusion property to verify integrity in a
/// single pass over the framed buffer.
const CRC32_POLY: u32 = 0xEDB88320;

/// CRC-32 of the data-segment layout's canonical byte serialisation.
///
/// Canonical form: for each slot in declaration order, emit
///
/// - the slot name's UTF-8 bytes,
/// - a single null byte `0x00` as separator,
/// - one byte for the visibility tag (`0x53` `'S'` for Shared,
///   `0x50` `'P'` for Private),
/// - a single newline `0x0A` as slot terminator.
///
/// The trailing newline keeps adjacent slots disambiguated when
/// one slot's name is a prefix of the next. A module with no
/// data layout returns 0.
///
/// The hash is computed at compile time and stored in
/// [`Module::schema_hash`]; [`crate::vm::Vm::replace_module`]
/// compares the values across a hot swap. The hash covers slot
/// names and visibility but not per-slot type tags; the layout
/// does not carry per-slot type information at the bytecode
/// level. Type-level checks remain a future extension.
pub fn compute_schema_hash(layout: Option<&DataLayout>) -> u32 {
    let layout = match layout {
        Some(l) => l,
        None => return 0,
    };
    if layout.slots.is_empty() {
        return 0;
    }
    let mut buf: Vec<u8> = Vec::new();
    for slot in &layout.slots {
        buf.extend_from_slice(slot.name.as_bytes());
        buf.push(0x00);
        let vis_tag = match slot.visibility {
            SlotVisibility::Shared => b'S',
            SlotVisibility::Private => b'P',
        };
        buf.push(vis_tag);
        buf.push(b'\n');
    }
    crc32(&buf)
}

pub(crate) fn crc32(bytes: &[u8]) -> u32 {
    let mut crc: u32 = 0xFFFFFFFF;
    for &byte in bytes {
        crc ^= byte as u32;
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ CRC32_POLY
            } else {
                crc >> 1
            };
        }
    }
    crc ^ 0xFFFFFFFF
}

/// A failure encountered while loading or saving precompiled bytecode.
///
/// Returned by [`Module::to_bytes`] and [`Module::from_bytes`]. The runtime
/// converts this into [`crate::vm::VmError::LoadError`] when used through
/// [`crate::vm::Vm::load_bytes`] and the related convenience constructors.
#[derive(Debug, Clone)]
pub enum LoadError {
    /// The header magic bytes did not match `KELE`.
    BadMagic,
    /// The buffer was shorter than the required header plus footer, or
    /// the recorded length field exceeds the slice length, or the
    /// recorded length is below the minimum framing size.
    Truncated,
    /// The bytecode version is not supported by this runtime.
    UnsupportedVersion {
        /// Version recorded in the bytecode header.
        got: u16,
        /// Version the runtime supports.
        expected: u16,
    },
    /// The recorded word size exponent exceeds what this runtime build
    /// supports. Values are log-base-2 exponents. The bytecode is
    /// admitted when `got <= max_supported`.
    WordSizeMismatch {
        /// Word size exponent recorded in the bytecode header.
        got: u8,
        /// Maximum word size exponent this runtime build supports.
        max_supported: u8,
    },
    /// The recorded address size exponent exceeds what this runtime
    /// build supports. Values are log-base-2 exponents. The bytecode is
    /// admitted when `got <= max_supported`.
    AddressSizeMismatch {
        /// Address size exponent recorded in the bytecode header.
        got: u8,
        /// Maximum address size exponent this runtime build supports.
        max_supported: u8,
    },
    /// The recorded floating-point width exponent exceeds what this
    /// runtime build supports. Values are log-base-2 exponents. The
    /// bytecode is admitted when `got <= max_supported`.
    FloatSizeMismatch {
        /// Float width exponent recorded in the bytecode header.
        got: u8,
        /// Maximum float width exponent this runtime build supports.
        max_supported: u8,
    },
    /// The CRC-32 trailer did not satisfy the algebraic self-inclusion
    /// residue. The bytecode is corrupted or was produced by a different
    /// CRC implementation.
    BadChecksum,
    /// The declared WCET in the framing header is `u32::MAX`, signaling
    /// that the producer attempted to compute a bound but the result
    /// exceeded the field's range. No representable bound exists, so
    /// safe loading is refused.
    WcetOverflow,
    /// The declared WCMU in the framing header is `u32::MAX`, signaling
    /// that the producer attempted to compute a bound but the result
    /// exceeded the field's range. No representable bound exists, so
    /// safe loading is refused.
    WcmuOverflow,
    /// The body could not be encoded or decoded.
    Codec(String),
    /// The bytecode's framing header carries `FLAG_REQUIRES_SIGNATURE`
    /// but no key in the host's trust matrix verifies the attached
    /// signature, or the signed-extension metadata is inconsistent.
    /// Hosts respond by either refusing the module or registering an
    /// additional [`crate::vm::Vm::register_verifying_key`] entry.
    InvalidSignature,
    /// The bytecode is signed but the runtime build does not include
    /// the `signatures` cargo feature. The host has no way to verify
    /// the signature, so loading is refused at framing time.
    SignaturesUnsupported,
}

impl core::fmt::Display for LoadError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            LoadError::BadMagic => f.write_str("bytecode header missing magic 'KELE'"),
            LoadError::Truncated => f.write_str(
                "bytecode truncated, recorded length exceeds slice, or below minimum framing",
            ),
            LoadError::UnsupportedVersion { got, expected } => {
                write!(
                    f,
                    "bytecode version {} not supported, expected {}",
                    got, expected
                )
            }
            LoadError::WordSizeMismatch { got, max_supported } => {
                write!(
                    f,
                    "bytecode requires {}-bit words, runtime supports up to {}-bit",
                    1u32 << got,
                    1u32 << max_supported
                )
            }
            LoadError::AddressSizeMismatch { got, max_supported } => {
                write!(
                    f,
                    "bytecode requires {}-bit addresses, runtime supports up to {}-bit",
                    1u32 << got,
                    1u32 << max_supported
                )
            }
            LoadError::FloatSizeMismatch { got, max_supported } => {
                write!(
                    f,
                    "bytecode requires {}-bit floats, runtime supports up to {}-bit",
                    1u32 << got,
                    1u32 << max_supported
                )
            }
            LoadError::BadChecksum => f.write_str("bytecode CRC-32 residue check failed"),
            LoadError::WcetOverflow => {
                f.write_str("declared WCET is u32::MAX (overflow); no representable bound")
            }
            LoadError::WcmuOverflow => {
                f.write_str("declared WCMU is u32::MAX (overflow); no representable bound")
            }
            LoadError::Codec(msg) => write!(f, "bytecode codec error: {}", msg),
            LoadError::InvalidSignature => {
                f.write_str("bytecode signature did not verify against any registered key")
            }
            LoadError::SignaturesUnsupported => f.write_str(
                "bytecode is signed but the runtime build does not include the `signatures` feature",
            ),
        }
    }
}

impl core::error::Error for LoadError {}

impl Module {
    /// Serialize the module to a self-describing byte vector.
    ///
    /// The output begins with the twelve-byte header (magic, version,
    /// total length, word size, address size), then the module body in
    /// postcard wire format, then a four-byte little-endian CRC-32
    /// trailer. The CRC covers the entire framed range. The algebraic
    /// self-inclusion residue of the CRC parameterization makes the
    /// trailer part of the checksummed range.
    ///
    /// All multi-byte integer fields in the framing are stored in
    /// little-endian order. Postcard stores its own multi-byte values in
    /// little-endian or as varints. The wire format is therefore
    /// identical bytes regardless of producer or consumer host
    /// endianness.
    ///
    /// Returns [`LoadError::Codec`] if postcard rejects any field. The
    /// `Module` type is composed entirely of types that postcard supports,
    /// so encode failures are not expected in practice and indicate
    /// corruption of the runtime data.
    pub fn to_bytes(&self) -> Result<Vec<u8>, LoadError> {
        // V0.2.0 Phase 7c cuts the producer over to the section-
        // partitioned wire format defined in `wire_format.rs`. The
        // ops live in the opcode stream and the operand pool;
        // every other Module field is rkyv-archived in the
        // auxiliary body section. See `docs/architecture/WIRE_FORMAT.md`
        // for the framing-header layout and the section semantics.
        crate::wire_format::module_to_wire_bytes(self)
    }

    /// Deserialize a module from a self-describing byte slice.
    ///
    /// Validation order is truncation, magic, length, CRC residue,
    /// version, word size, address size, and body decode. The slice is
    /// truncated to the recorded length before the CRC check so that
    /// bytecode embedded in a larger buffer is supported. Trailing
    /// bytes after the recorded length are ignored.
    ///
    /// The CRC is checked before the version, word size, and address
    /// size because a corrupted byte in any of those fields would
    /// otherwise be reported as a mismatch rather than the more
    /// accurate `BadChecksum`.
    ///
    /// Does not run structural verification or resource bounds checks.
    /// Pass the result to [`crate::vm::Vm::new`] for full verification or
    /// to [`crate::vm::Vm::new_unchecked`] for trust-based skipping of
    /// the bounds checks.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, LoadError> {
        // V0.2.0 Phase 7c routes the consumer through the wire-
        // format reader. The framing, magic, version, length,
        // and CRC residue checks run inside
        // `module_from_wire_bytes`; the opcode stream and
        // operand pool sections supply the chunk ops while the
        // auxiliary body's rkyv archive supplies the rest of the
        // module.
        crate::wire_format::module_from_wire_bytes(bytes)
    }

    /// Validate framing and return a borrowed archived view of the module.
    ///
    /// Performs the same framing checks as [`Module::from_bytes`] (magic,
    /// length, CRC residue, version, word size, address size) and then
    /// runs `rkyv::access` on the body to obtain a `&'a ArchivedModule`
    /// without deserialization.
    ///
    /// The body must be 8-byte aligned within the slice. Because the
    /// header is sixteen bytes, the body is 8-byte aligned within the
    /// slice when the slice base itself is 8-byte aligned. Hosts that compute
    /// or load bytecode into an `rkyv::util::AlignedVec` or a static
    /// buffer with `#[repr(align(8))]` satisfy this requirement.
    /// Bytecode placed by the linker into a section that aligns to at
    /// least 8 bytes also satisfies it.
    ///
    /// Returns `LoadError::Codec` with an alignment message when the
    /// body is not aligned, or when the rkyv structural validator
    /// rejects the body. Returns the other `LoadError` variants for
    /// header validation failures.
    pub fn access_bytes(
        bytes: &[u8],
    ) -> Result<&crate::wire_format::ArchivedWireAuxBody, LoadError> {
        use alloc::format;
        // V0.2.0 Phase 7c routes the zero-copy view through the
        // wire format. `parse_wire_sections` validates the
        // framing header, CRC residue, and section bounds; the
        // header-mirrored target widths are checked separately
        // through `read_header_fields`. The returned auxiliary
        // body slice points into the input buffer at the
        // wire-format aux_body section; that section is rkyv-
        // archived and lives on an 8-byte aligned offset.
        let header = crate::wire_format::read_header_fields(bytes)?;
        if header.word_bits_log2 > RUNTIME_WORD_BITS_LOG2 {
            return Err(LoadError::WordSizeMismatch {
                got: header.word_bits_log2,
                max_supported: RUNTIME_WORD_BITS_LOG2,
            });
        }
        if header.addr_bits_log2 > RUNTIME_ADDRESS_BITS_LOG2 {
            return Err(LoadError::AddressSizeMismatch {
                got: header.addr_bits_log2,
                max_supported: RUNTIME_ADDRESS_BITS_LOG2,
            });
        }
        if header.float_bits_log2 > RUNTIME_FLOAT_BITS_LOG2 {
            return Err(LoadError::FloatSizeMismatch {
                got: header.float_bits_log2,
                max_supported: RUNTIME_FLOAT_BITS_LOG2,
            });
        }
        if header.wcet_cycles == u32::MAX {
            return Err(LoadError::WcetOverflow);
        }
        if header.wcmu_bytes == u32::MAX {
            return Err(LoadError::WcmuOverflow);
        }
        let sections = crate::wire_format::parse_wire_sections(bytes)?;
        if !(sections.aux_body.as_ptr() as usize).is_multiple_of(8) {
            return Err(LoadError::Codec(format!(
                "auxiliary body not 8-byte aligned (slice base 0x{:x}); use Module::from_bytes for unaligned input",
                bytes.as_ptr() as usize
            )));
        }
        rkyv::access::<crate::wire_format::ArchivedWireAuxBody, rkyv::rancor::Error>(
            sections.aux_body,
        )
        .map_err(|e| LoadError::Codec(format!("rkyv access failed: {}", e)))
    }

    /// Deserialize a module from an aligned byte slice without the
    /// AlignedVec copy step that [`Module::from_bytes`] performs.
    ///
    /// Validates the framing through [`Module::access_bytes`] and then
    /// calls `rkyv::deserialize` on the validated archived form. Returns
    /// an owned `Module` for compatibility with the existing execution
    /// path. The wire-format validation runs in place against the input
    /// slice. The deserialization step still allocates the owned form.
    ///
    /// True zero-copy execution against `&ArchivedModule` is recorded as
    /// the next iteration of P10. Path B requires lifetime-parameterizing
    /// the Vm and rewriting the execution loop to read from
    /// `&ArchivedModule`. The current view path delivers in-place
    /// validation and is the architectural foundation for Phase 2.
    ///
    /// Requires the body to be 8-byte aligned. See [`Module::access_bytes`]
    /// for the alignment contract.
    pub fn view_bytes(bytes: &[u8]) -> Result<Module, LoadError> {
        // V0.2.0 Phase 7c routes view_bytes through the wire
        // format. The aux body's archived form does not carry
        // the ops; the wire-format reader assembles each chunk's
        // ops from the opcode stream section.
        crate::wire_format::module_from_wire_bytes(bytes)
    }
}

impl ConstValue {
    /// Lower a runtime [`Value`] into a compile-time [`ConstValue`].
    ///
    /// Returns `Err` for the runtime-only variant [`Value::KStr`]
    /// which cannot be embedded in the bytecode's constant pool.
    /// The compiler is the sole caller and uses this at the boundary
    /// where it pushes constants to a chunk's pool.
    pub fn try_from_value(value: Value) -> Result<Self, &'static str> {
        match value {
            Value::Unit => Ok(ConstValue::Unit),
            Value::Bool(b) => Ok(ConstValue::Bool(b)),
            Value::Int(i) => Ok(ConstValue::Int(i)),
            Value::Byte(b) => Ok(ConstValue::Byte(b)),
            Value::Fixed(i) => Ok(ConstValue::Fixed(i)),
            #[cfg(feature = "floats")]
            Value::Float(f) => Ok(ConstValue::Float(f)),
            Value::StaticStr(s) => Ok(ConstValue::StaticStr(s)),
            Value::KStr(_) => Err("KStr cannot be a compile-time constant"),
            Value::Opaque(_) => Err("Opaque cannot be a compile-time constant"),
            Value::Tuple(items) => items
                .into_iter()
                .map(ConstValue::try_from_value)
                .collect::<Result<Vec<_>, _>>()
                .map(ConstValue::Tuple),
            Value::Array(items) => items
                .into_iter()
                .map(ConstValue::try_from_value)
                .collect::<Result<Vec<_>, _>>()
                .map(ConstValue::Array),
            Value::Struct { type_name, fields } => {
                let cfields: Result<Vec<_>, _> = fields
                    .into_iter()
                    .map(|(n, v)| ConstValue::try_from_value(v).map(|cv| (n, cv)))
                    .collect();
                Ok(ConstValue::Struct {
                    type_name,
                    fields: cfields?,
                })
            }
            Value::Enum {
                type_name,
                variant,
                fields,
            } => {
                let cfields: Result<Vec<_>, _> =
                    fields.into_iter().map(ConstValue::try_from_value).collect();
                Ok(ConstValue::Enum {
                    type_name,
                    variant,
                    fields: cfields?,
                })
            }
            Value::None => Ok(ConstValue::None),
            #[cfg(not(feature = "floats"))]
            Value::_PhantomFloat(_) => unreachable!("_PhantomFloat is never constructed"),
        }
    }

    /// Lift a [`ConstValue`] into a runtime [`Value`].
    ///
    /// Inverse of [`ConstValue::try_from_value`] for the constant
    /// subset. Always succeeds because every `ConstValue` variant has
    /// a corresponding `Value` variant.
    pub fn into_value(self) -> Value {
        match self {
            ConstValue::Unit => Value::Unit,
            ConstValue::Bool(b) => Value::Bool(b),
            ConstValue::Int(i) => Value::Int(i),
            ConstValue::Byte(b) => Value::Byte(b),
            ConstValue::Fixed(i) => Value::Fixed(i),
            #[cfg(feature = "floats")]
            ConstValue::Float(f) => Value::Float(f),
            ConstValue::StaticStr(s) => Value::StaticStr(s),
            ConstValue::Tuple(items) => {
                Value::Tuple(items.into_iter().map(ConstValue::into_value).collect())
            }
            ConstValue::Array(items) => {
                Value::Array(items.into_iter().map(ConstValue::into_value).collect())
            }
            ConstValue::Struct { type_name, fields } => Value::Struct {
                type_name,
                fields: fields
                    .into_iter()
                    .map(|(n, v)| (n, v.into_value()))
                    .collect(),
            },
            ConstValue::Enum {
                type_name,
                variant,
                fields,
            } => Value::Enum {
                type_name,
                variant,
                fields: fields.into_iter().map(ConstValue::into_value).collect(),
            },
            ConstValue::None => Value::None,
        }
    }
}

impl PartialEq for ConstValue {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ConstValue::Unit, ConstValue::Unit) | (ConstValue::None, ConstValue::None) => true,
            (ConstValue::Bool(a), ConstValue::Bool(b)) => a == b,
            (ConstValue::Int(a), ConstValue::Int(b)) => a == b,
            (ConstValue::Byte(a), ConstValue::Byte(b)) => a == b,
            (ConstValue::Fixed(a), ConstValue::Fixed(b)) => a == b,
            #[cfg(feature = "floats")]
            (ConstValue::Float(a), ConstValue::Float(b)) => a == b,
            (ConstValue::StaticStr(a), ConstValue::StaticStr(b)) => a == b,
            (ConstValue::Tuple(a), ConstValue::Tuple(b))
            | (ConstValue::Array(a), ConstValue::Array(b)) => a == b,
            (
                ConstValue::Struct {
                    type_name: na,
                    fields: fa,
                },
                ConstValue::Struct {
                    type_name: nb,
                    fields: fb,
                },
            ) => na == nb && fa == fb,
            (
                ConstValue::Enum {
                    type_name: na,
                    variant: va,
                    fields: fa,
                },
                ConstValue::Enum {
                    type_name: nb,
                    variant: vb,
                    fields: fb,
                },
            ) => na == nb && va == vb && fa == fb,
            _ => false,
        }
    }
}

/// Convert an archived `ConstValue` to its owned [`Value`] form.
///
/// Recursive. Materializes the entire value tree as owned. For
/// constants loaded into the operand stack at runtime under the
/// zero-copy execution path. The cost per load is proportional to the
/// constant's size; for primitive constants the cost is one match arm
/// and a small copy. For string and composite constants the cost
/// includes a heap allocation.
pub fn value_from_archived<W: crate::word::Word, F: crate::float::Float>(
    archived: &ArchivedConstValue,
) -> GenericValue<W, F> {
    GenericValue::<W, F>::from_const_archived(archived)
}

/// Sign-extending truncation to a narrower-than-runtime word width.
///
/// When bytecode declares a word size narrower than the runtime
/// supports, the VM applies this mask to the low half of each
/// integer-arithmetic result so the result fits the bytecode's
/// declared width. For `word_bits_log2 >= 6` the function is the
/// identity, since the runtime's native i64 already matches or
/// exceeds the declared width.
///
/// V0.2.0 Consolidation B and the post-V0.2.0 follow-on. The
/// `Op::Add` / `Op::Sub` / `Op::Mul` / `Op::Neg` family no longer
/// accepts `Int` operands; the compiler routes `Int` arithmetic
/// through `CheckedXxx` followed by `PopN(2)`. The checked
/// dispatch applies this truncation to the `low` half so the
/// wrapping result matches the bytecode's declared width, and the
/// flag detection through [`declared_width_range`] reports
/// overflow against the declared (narrower) range rather than the
/// runtime width.
pub(crate) fn truncate_int_to_declared_width(value: i64, word_bits_log2: u8) -> i64 {
    if word_bits_log2 >= 6 {
        return value;
    }
    let bits = 1u32 << word_bits_log2;
    let shift = 64 - bits;
    (value << shift) >> shift
}

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

    #[test]
    fn nominal_cost_model_value_slot_bytes_matches_constant() {
        assert_eq!(NOMINAL_COST_MODEL.value_slot_bytes, VALUE_SLOT_SIZE_BYTES);
    }

    #[test]
    fn runtime_width_constants_track_narrowing_features() {
        // B16 step 12: the RUNTIME_*_BITS_LOG2 constants reflect the
        // narrowing Cargo features in effect for this build. The
        // narrowest enabled feature wins per dimension. With no
        // narrowing features enabled the defaults are 6/6/6 (i64,
        // u64, f64). The test pins the constants per feature
        // combination so future refactors do not regress the
        // narrowest-wins rule.
        #[cfg(feature = "narrow-word-8")]
        assert_eq!(RUNTIME_WORD_BITS_LOG2, 3);
        #[cfg(all(feature = "narrow-word-16", not(feature = "narrow-word-8")))]
        assert_eq!(RUNTIME_WORD_BITS_LOG2, 4);
        #[cfg(all(
            feature = "narrow-word-32",
            not(any(feature = "narrow-word-8", feature = "narrow-word-16"))
        ))]
        assert_eq!(RUNTIME_WORD_BITS_LOG2, 5);
        #[cfg(not(any(
            feature = "narrow-word-8",
            feature = "narrow-word-16",
            feature = "narrow-word-32"
        )))]
        assert_eq!(RUNTIME_WORD_BITS_LOG2, 6);

        #[cfg(feature = "narrow-address-8")]
        assert_eq!(RUNTIME_ADDRESS_BITS_LOG2, 3);
        #[cfg(all(feature = "narrow-address-16", not(feature = "narrow-address-8")))]
        assert_eq!(RUNTIME_ADDRESS_BITS_LOG2, 4);
        #[cfg(all(
            feature = "narrow-address-32",
            not(any(feature = "narrow-address-8", feature = "narrow-address-16"))
        ))]
        assert_eq!(RUNTIME_ADDRESS_BITS_LOG2, 5);
        #[cfg(not(any(
            feature = "narrow-address-8",
            feature = "narrow-address-16",
            feature = "narrow-address-32"
        )))]
        assert_eq!(RUNTIME_ADDRESS_BITS_LOG2, 6);

        #[cfg(feature = "narrow-float-32")]
        assert_eq!(RUNTIME_FLOAT_BITS_LOG2, 5);
        #[cfg(not(feature = "narrow-float-32"))]
        assert_eq!(RUNTIME_FLOAT_BITS_LOG2, 6);
    }

    #[test]
    fn nominal_cost_model_cycles_match_op_cost_method() {
        // The Op::cost backward-compatibility wrapper must agree with
        // the nominal cost model's cycle table for every variant. Pick
        // a representative sample across the cost tiers.
        let ops: alloc::vec::Vec<Op> = alloc::vec![
            Op::Const(0),
            Op::PushImmediate(0),
            Op::Add,
            Op::Mul,
            Op::Div,
            Op::NewArray(2),
            Op::Call(0, 0),
            Op::Yield,
        ];
        for op in &ops {
            assert_eq!(NOMINAL_COST_MODEL.cycles(op), op.cost());
        }
    }

    #[test]
    fn cost_model_slots_to_bytes_uses_slot_size() {
        let model = CostModel {
            value_slot_bytes: 8,
            op_cycles: nominal_op_cycles,
        };
        assert_eq!(model.slots_to_bytes(0), 0);
        assert_eq!(model.slots_to_bytes(1), 8);
        assert_eq!(model.slots_to_bytes(4), 32);
    }

    #[test]
    fn cost_model_heap_alloc_bytes_scales_with_slot_size() {
        // A custom cost model with half the value-slot size should
        // halve the reported heap allocation for composite-construction
        // opcodes. This pins the contract that `value_slot_bytes`
        // determines the byte conversion.
        let nominal = NOMINAL_COST_MODEL;
        let custom = CostModel {
            value_slot_bytes: VALUE_SLOT_SIZE_BYTES / 2,
            op_cycles: nominal_op_cycles,
        };
        let chunk = Chunk {
            name: alloc::string::String::from("test"),
            ops: alloc::vec::Vec::new(),
            constants: alloc::vec::Vec::new(),
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec::Vec::new(),
        };
        let op = Op::NewArray(4);
        let nominal_bytes = nominal.heap_alloc_bytes(&op, &chunk);
        let custom_bytes = custom.heap_alloc_bytes(&op, &chunk);
        assert_eq!(nominal_bytes, 4 * VALUE_SLOT_SIZE_BYTES);
        assert_eq!(custom_bytes, 4 * (VALUE_SLOT_SIZE_BYTES / 2));
        assert_eq!(custom_bytes * 2, nominal_bytes);
    }

    #[test]
    fn custom_cost_model_returns_custom_cycles() {
        // Demonstrate that a host-supplied op_cycles function flows
        // through the model. The custom function returns a flat 100
        // for every op; the model's `cycles` must return that value.
        fn flat_hundred(_op: &Op) -> u32 {
            100
        }
        let custom = CostModel {
            value_slot_bytes: VALUE_SLOT_SIZE_BYTES,
            op_cycles: flat_hundred,
        };
        assert_eq!(custom.cycles(&Op::Add), 100);
        assert_eq!(custom.cycles(&Op::PushImmediate(0)), 100);
        assert_eq!(custom.cycles(&Op::Call(0, 0)), 100);
    }

    #[test]
    fn op_cost_fixed_evaluates_to_inner_value() {
        let ctx = OpCostContext::default();
        assert_eq!(OpCost::Fixed(42).evaluate(&ctx), 42);
        assert_eq!(OpCost::Fixed(0).evaluate(&ctx), 0);
    }

    #[test]
    fn op_cost_dynamic_invokes_function_with_context() {
        fn sum_lengths(ctx: &OpCostContext) -> u32 {
            ctx.lhs_text_len.saturating_add(ctx.rhs_text_len)
        }
        let cost = OpCost::Dynamic(sum_lengths);
        let ctx = OpCostContext {
            lhs_text_len: 100,
            rhs_text_len: 200,
        };
        assert_eq!(cost.evaluate(&ctx), 300);
    }

    #[test]
    fn op_cost_dynamic_saturates_at_u32_max_for_unbounded_operand() {
        fn sum_lengths(ctx: &OpCostContext) -> u32 {
            ctx.lhs_text_len.saturating_add(ctx.rhs_text_len)
        }
        let cost = OpCost::Dynamic(sum_lengths);
        let ctx = OpCostContext {
            lhs_text_len: u32::MAX,
            rhs_text_len: 100,
        };
        assert_eq!(cost.evaluate(&ctx), u32::MAX);
    }

    #[test]
    fn heap_alloc_cost_text_add_is_dynamic() {
        let chunk = Chunk {
            name: alloc::string::String::from("test"),
            ops: alloc::vec::Vec::new(),
            constants: alloc::vec::Vec::new(),
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec::Vec::new(),
        };
        let cost = NOMINAL_COST_MODEL.heap_alloc_cost(&Op::Add, &chunk);
        assert!(matches!(cost, OpCost::Dynamic(_)));
        let ctx = OpCostContext {
            lhs_text_len: 5,
            rhs_text_len: 6,
        };
        assert_eq!(cost.evaluate(&ctx), 11);
    }

    #[test]
    fn heap_alloc_cost_composite_is_fixed() {
        let chunk = Chunk {
            name: alloc::string::String::from("test"),
            ops: alloc::vec::Vec::new(),
            constants: alloc::vec::Vec::new(),
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec::Vec::new(),
        };
        let cost = NOMINAL_COST_MODEL.heap_alloc_cost(&Op::NewArray(3), &chunk);
        assert!(matches!(cost, OpCost::Fixed(_)));
        assert_eq!(
            cost.evaluate(&OpCostContext::default()),
            3 * VALUE_SLOT_SIZE_BYTES
        );
    }

    #[test]
    fn heap_alloc_bytes_text_add_reports_zero_in_fixed_view() {
        // The Fixed-view accessor saturates dynamic costs to zero
        // because they require abstract-interpretation context.
        let chunk = Chunk {
            name: alloc::string::String::from("test"),
            ops: alloc::vec::Vec::new(),
            constants: alloc::vec::Vec::new(),
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec::Vec::new(),
        };
        assert_eq!(NOMINAL_COST_MODEL.heap_alloc_bytes(&Op::Add, &chunk), 0);
    }
}