keleusma 0.2.2

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
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
// 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,
        /// Variant discriminant, when the compiler resolved it (B28 P2).
        /// `Some` lets the value materialise into a flat enum body;
        /// `None` (e.g. folded from a boxed runtime value) materialises
        /// boxed.
        discriminant: Option<i64>,
        /// 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>;

// The bundled `Value` slot is 32 bytes, the close of B28 item 2. The
// single-variant `FlatComposite` (a `NonNull`-bearing arena handle) keeps its
// pointer niche exposed for the body enums to reuse for their `Flat`/`Boxed`
// discriminant; a second data-less variant would spend that niche and pin the
// slot at 40. This static assertion fails the build if the layout regresses.
//
// The 32-byte figure is the 64-bit-pointer layout (`FlatComposite` carries an
// 8-byte `NonNull`). On a 32-bit target (for example a `thumbv*-none-eabi*`
// embedded build) the pointer, and therefore the slot, is naturally smaller, so
// the guard is scoped to the 64-bit pointer width it describes.
#[cfg(target_pointer_width = "64")]
const _: () = assert!(
    core::mem::size_of::<Value>() == 32,
    "Value slot must be 32 bytes (B28 item 2 step 6B); a layout change regressed it"
);

/// 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.
/// The body of a `Tuple` value during the B28 P2 migration.
///
/// A transitively-scalar tuple is `Flat`, a pure byte buffer with the
/// fields packed at compiler-baked offsets. A tuple containing a
/// reference field (`Text`, `Opaque`) or a not-yet-migrated nested
/// composite is `Boxed`, the pre-B28 `Vec` representation, which P3
/// removes. Construction chooses the form; the access handler dispatches
/// on it.
#[derive(Debug, Clone, PartialEq)]
pub enum TupleBody<W: crate::word::Word, F: crate::float::Float> {
    /// Flat bytes; fields read at compiler-baked offsets.
    Flat(crate::flat_value::FlatComposite),
    /// Boxed elements (the pre-B28 reference/float/oversize fallback). The
    /// `Vec` is heap-boxed so this variant costs one pointer rather than a
    /// 24-byte `Vec` inline, keeping `GenericValue` at the 32-byte slot
    /// (B28 P3 item 1).
    Boxed(alloc::boxed::Box<alloc::vec::Vec<GenericValue<W, F>>>),
}

impl<W: crate::word::Word, F: crate::float::Float> TupleBody<W, F> {
    /// Construct a boxed tuple body, heap-boxing the element vector.
    pub fn boxed(elements: alloc::vec::Vec<GenericValue<W, F>>) -> Self {
        Self::Boxed(alloc::boxed::Box::new(elements))
    }

    /// The boxed elements. Panics on the `Flat` form, which carries no
    /// per-element values; flat-tuple reads go through `Op::GetTupleField`
    /// with the baked field kind instead.
    pub fn elements(&self) -> &[GenericValue<W, F>] {
        match self {
            Self::Boxed(v) => v,
            Self::Flat(_) => {
                unreachable!("flat tuple body has no element values; read via GetTupleField")
            }
        }
    }

    /// The boxed elements by value. Panics on the `Flat` form.
    pub fn into_elements(self) -> alloc::vec::Vec<GenericValue<W, F>> {
        match self {
            Self::Boxed(v) => *v,
            Self::Flat(_) => {
                unreachable!("flat tuple body has no element values; read via GetTupleField")
            }
        }
    }
}

/// The byte body of an array value (B28 P2). An array is homogeneous, so
/// its flat body is `count * element_size` packed little-endian bytes with
/// no per-element offset table; the element kind is carried by the
/// [`ArrayElem`] operand the compiler bakes into [`Op::GetIndex`], and the
/// element size follows from that kind at the module-declared scalar
/// widths. A transitively-scalar array is `Flat`; an array whose element
/// type is a reference, float, or composite stays `Boxed`, the pre-B28
/// `Vec` form that P3 removes.
#[derive(Debug, Clone, PartialEq)]
pub enum ArrayBody<W: crate::word::Word, F: crate::float::Float> {
    /// Flat bytes; elements read at `index * element_size`.
    Flat(crate::flat_value::FlatComposite),
    /// Boxed elements (the pre-B28 reference/float/oversize fallback). The
    /// `Vec` is heap-boxed so this variant costs one pointer rather than a
    /// 24-byte `Vec` inline, keeping `GenericValue` at the 32-byte slot
    /// (B28 P3 item 1).
    Boxed(alloc::boxed::Box<alloc::vec::Vec<GenericValue<W, F>>>),
}

impl<W: crate::word::Word, F: crate::float::Float> ArrayBody<W, F> {
    /// Construct a boxed array body, heap-boxing the element vector.
    pub fn boxed(elements: alloc::vec::Vec<GenericValue<W, F>>) -> Self {
        Self::Boxed(alloc::boxed::Box::new(elements))
    }

    /// The boxed elements. Panics on the `Flat` form, which carries no
    /// element kind; flat-array reads go through [`Op::GetIndex`] with the
    /// baked [`ArrayElem`] kind, or through the host marshalling boundary
    /// which supplies the element type, never through this accessor.
    pub fn elements(&self) -> &[GenericValue<W, F>] {
        match self {
            Self::Boxed(v) => v,
            Self::Flat(_) => {
                unreachable!(
                    "flat array body has no element kind; read via GetIndex or marshalling"
                )
            }
        }
    }

    /// The boxed elements by value. Panics on the `Flat` form, as
    /// [`Self::elements`].
    pub fn into_elements(self) -> alloc::vec::Vec<GenericValue<W, F>> {
        match self {
            Self::Boxed(v) => *v,
            Self::Flat(_) => {
                unreachable!(
                    "flat array body has no element kind; read via GetIndex or marshalling"
                )
            }
        }
    }
}

/// The byte body of a struct value (B28 P2). A struct is a named record;
/// its flat body packs the fields in declaration order with no type name
/// or field-name keys (those are compile-time information baked into the
/// access ops and the type test). A struct with a reference, float, or
/// nested-composite field stays `Boxed`, the pre-B28 representation that
/// carries the type name and the ordered (name, value) pairs, which P3
/// removes.
#[derive(Debug, Clone, PartialEq)]
pub enum StructBody<W: crate::word::Word, F: crate::float::Float> {
    /// Flat bytes; fields read at compiler-baked offsets.
    Flat(crate::flat_value::FlatComposite),
    /// Boxed named fields (pre-B28 representation; removed in P3). The
    /// payload is heap-boxed so this variant costs one pointer rather than
    /// a `String` plus a `Vec`; a boxed struct is comparatively rare on the
    /// operand stack, and keeping the variant small keeps every
    /// `GenericValue` slot small, which directly shrinks the pre-sized
    /// operand-stack arena footprint (B28 P3 item 5).
    Boxed(alloc::boxed::Box<BoxedStruct<W, F>>),
}

/// Heap payload of a non-flat struct value. Boxed inside
/// [`StructBody::Boxed`] to keep `GenericValue` small. Transitional
/// representation removed when boxed bodies relocate into the arena
/// (B28 P3 item 5 C4).
#[derive(Debug, Clone, PartialEq)]
pub struct BoxedStruct<W: crate::word::Word, F: crate::float::Float> {
    /// Name of the struct type.
    pub type_name: alloc::string::String,
    /// Ordered (field-name, field-value) pairs.
    pub fields: alloc::vec::Vec<(alloc::string::String, GenericValue<W, F>)>,
}

impl<W: crate::word::Word, F: crate::float::Float> StructBody<W, F> {
    /// Build a [`StructBody::Boxed`] from its parts, boxing the payload.
    pub fn boxed(
        type_name: alloc::string::String,
        fields: alloc::vec::Vec<(alloc::string::String, GenericValue<W, F>)>,
    ) -> Self {
        Self::Boxed(alloc::boxed::Box::new(BoxedStruct { type_name, fields }))
    }
}

/// The byte body of an enum value (B28 P2). The flat body is the variant's
/// `Word`-sized discriminant followed by the current variant's payload
/// packed in declaration order: `[disc: word_bytes][payload]`. The
/// discriminant matches the `Enum as Word` cast and is what the variant
/// test (`Op::IsEnum`) reads, since an enum is a sum type whose variant is
/// not statically known. The body is sized to the *current* variant (enums
/// are not yet inlined into other flat composites, so a per-value size is
/// sufficient); the worst-case-memory bound is still the largest variant.
/// An enum with a reference, float, or nested-composite payload stays
/// `Boxed`, the pre-B28 representation carrying the type and variant names
/// and the payload values, which P3 removes.
#[derive(Debug, Clone, PartialEq)]
pub enum EnumBody<W: crate::word::Word, F: crate::float::Float> {
    /// Flat bytes: `[discriminant: word_bytes][payload]`.
    Flat(crate::flat_value::FlatComposite),
    /// Boxed variant (pre-B28 representation; removed in P3). The payload
    /// is heap-boxed so this variant costs one pointer rather than two
    /// `String`s plus a `Vec` (the 72-byte form that previously made every
    /// `GenericValue` slot 72 bytes); keeping it small shrinks the pre-sized
    /// operand-stack arena footprint (B28 P3 item 5).
    Boxed(alloc::boxed::Box<BoxedEnum<W, F>>),
}

/// Heap payload of a non-flat enum value. Boxed inside [`EnumBody::Boxed`]
/// to keep `GenericValue` small. Transitional representation removed when
/// boxed bodies relocate into the arena (B28 P3 item 5 C4).
///
/// The `disc` and `min_payload` fields are re-flattening hints so a boxed enum
/// can be re-packed to the `[disc word][payload]` arena body the compiler-baked
/// flat access ops expect (B28 item 2 step 6B; see
/// [`GenericValue::into_arena_canonical`]). `disc` is the variant discriminant;
/// `min_payload` is the largest-variant payload size in bytes for a uniformly
/// flat enum (zero otherwise), which pads the flat body to a fixed size so the
/// enum nests in a parent composite at a stable slot. Both are hints, not part
/// of value identity: the discriminant is uniquely determined by the
/// (`type_name`, `variant`) pair and the padding is a layout detail, so both are
/// deliberately excluded from equality to keep a host-built value comparable to
/// a script-built value of the same variant regardless of how each populated the
/// hints.
#[derive(Debug, Clone)]
pub struct BoxedEnum<W: crate::word::Word, F: crate::float::Float> {
    /// Name of the enum type.
    pub type_name: alloc::string::String,
    /// Name of the variant.
    pub variant: alloc::string::String,
    /// Variant discriminant, a re-flattening hint (see the type docs).
    pub disc: i64,
    /// Largest-variant payload size in bytes for a uniformly flat enum (zero
    /// otherwise), the padding re-flattening hint (see the type docs).
    pub min_payload: usize,
    /// Positional payload values; empty for a unit variant.
    pub fields: alloc::vec::Vec<GenericValue<W, F>>,
}

impl<W: crate::word::Word, F: crate::float::Float> PartialEq for BoxedEnum<W, F> {
    /// Equality ignores the `disc`/`min_payload` re-flattening hints; two boxed
    /// enums are equal when their type, variant, and payload match.
    fn eq(&self, other: &Self) -> bool {
        self.type_name == other.type_name
            && self.variant == other.variant
            && self.fields == other.fields
    }
}

impl<W: crate::word::Word, F: crate::float::Float> EnumBody<W, F> {
    /// Build an [`EnumBody::Boxed`] from its parts, boxing the payload. The
    /// re-flattening hints default to zero; this is correct for every caller
    /// whose value is read through the boxed access ops or whose payload is not
    /// flat-eligible (a reference-bearing enum stays boxed under
    /// [`GenericValue::into_arena_canonical`], where the hints would be used).
    /// A caller whose value may be canonicalised to a flat body must use
    /// [`Self::boxed_with_disc`] or [`Self::boxed_with_layout`].
    pub fn boxed(
        type_name: alloc::string::String,
        variant: alloc::string::String,
        fields: alloc::vec::Vec<GenericValue<W, F>>,
    ) -> Self {
        Self::boxed_with_layout(type_name, variant, 0, 0, fields)
    }

    /// Build an [`EnumBody::Boxed`] recording the variant discriminant, with no
    /// padding hint (B28 item 2 step 6B). For a top-level (not nested) host enum
    /// such as the ad-hoc [`GenericValue::enum_value`], whose flat body is
    /// variant-sized and read directly.
    pub fn boxed_with_disc(
        type_name: alloc::string::String,
        variant: alloc::string::String,
        disc: i64,
        fields: alloc::vec::Vec<GenericValue<W, F>>,
    ) -> Self {
        Self::boxed_with_layout(type_name, variant, disc, 0, fields)
    }

    /// Build an [`EnumBody::Boxed`] recording both re-flattening hints (B28 item
    /// 2 step 6B): the discriminant and the largest-variant payload byte size
    /// that pads the flat body for nesting. Used by the width-aware enum
    /// constructor, whose value the script may read through flat-baked access
    /// ops after [`GenericValue::into_arena_canonical`].
    pub fn boxed_with_layout(
        type_name: alloc::string::String,
        variant: alloc::string::String,
        disc: i64,
        min_payload: usize,
        fields: alloc::vec::Vec<GenericValue<W, F>>,
    ) -> Self {
        Self::Boxed(alloc::boxed::Box::new(BoxedEnum {
            type_name,
            variant,
            disc,
            min_payload,
            fields,
        }))
    }
}

#[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. The body is flat bytes for a transitively-scalar
    /// tuple or boxed elements otherwise (B28 P2); see [`TupleBody`].
    Tuple(TupleBody<W, F>),
    /// Fixed-size array of values. The body is flat bytes for a
    /// transitively-scalar element type or boxed elements otherwise
    /// (B28 P2); see [`ArrayBody`].
    Array(ArrayBody<W, F>),
    /// Named struct. The body is flat bytes for a transitively-scalar
    /// field list or boxed named fields otherwise (B28 P2); see
    /// [`StructBody`].
    Struct(StructBody<W, F>),
    /// Enum variant with optional payload. The body is flat bytes for a
    /// transitively-scalar payload or boxed otherwise (B28 P2); see
    /// [`EnumBody`].
    Enum(EnumBody<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>),

    /// Internal POD index form of an opaque host reference (B33).
    ///
    /// An opaque value on the operand stack and as a boxed-composite
    /// element is carried as this `u32` index into the VM's
    /// `ephemeral_opaques` registry, not as the `Drop`-bearing
    /// [`Self::Opaque`] `Arc`. The operand stack is arena-resident, so this
    /// keeps it free of global-heap pointers, which the snapshot and
    /// no-global-heap goals require. The `Arc` is materialised back from
    /// the index only at host boundaries (native call, yield, decode).
    ///
    /// Equality is index equality, which coincides with `Arc` pointer
    /// identity because interning deduplicates by pointer (see
    /// [`crate::vm::Vm`]'s `intern_ephemeral_opaque`). Host code never
    /// observes this variant: the boundary walks convert it to
    /// [`Self::Opaque`] before a value crosses into host hands.
    ///
    /// Hidden from the public surface because it is an internal runtime form;
    /// host code only ever observes [`Self::Opaque`].
    #[doc(hidden)]
    OpaqueRef(u32),

    /// 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)) => a == b,
            (Self::Array(a), Self::Array(b)) => a == b,
            (Self::Struct(a), Self::Struct(b)) => a == b,
            // Flat enum bodies compare with padding tolerance (B28 P2):
            // a compiler-padded body (`word + payload_max`) and an
            // unpadded variant-sized body of the same value differ only in
            // trailing zero padding. Comparing the overlapping prefix and
            // requiring each remainder to be zero makes them equal without
            // a type table. The discriminant word lies in the prefix (both
            // bodies are at least `word_bytes` long) and is unique per
            // variant, so distinct variants never alias. Boxed and mixed
            // pairs keep the derived comparison.
            (Self::Enum(EnumBody::Flat(a)), Self::Enum(EnumBody::Flat(b))) => {
                match (a.inline_bytes(), b.inline_bytes()) {
                    (Some(x), Some(y)) => flat_enum_bytes_eq(x, y),
                    // An arena enum body needs the arena to read, which
                    // `PartialEq` lacks; the VM materialises composites to
                    // inline before `CmpEq`, so this arm never sees an arena
                    // body in practice (B28 P2).
                    _ => false,
                }
            }
            (Self::Enum(a), Self::Enum(b)) => a == b,
            // 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),
            // OpaqueRef equality is index equality. Interning deduplicates by
            // `Arc` pointer identity, so equal indices coincide with the same
            // host object, matching the `Opaque` arm above (B33).
            (Self::OpaqueRef(a), Self::OpaqueRef(b)) => a == b,
            _ => false,
        }
    }
}

/// The flat-composite scalar kind of a value, or `None` when the value
/// is not a flat-eligible tuple field (B28 P2).
///
/// Eligible kinds are the non-reference, non-float fixed-size scalars.
/// `Float` is excluded because the flat body compares by raw bytes,
/// which would change the `+0.0`/`-0.0` and `NaN` semantics of tuple
/// equality. References, `None`, and composites are not flat-eligible.
/// The compiler's `type_flat_scalar_kind` mirrors this on the type
/// side so construction and baked access agree.
pub(crate) fn flat_tuple_scalar_kind<W: crate::word::Word, F: crate::float::Float>(
    v: &GenericValue<W, F>,
) -> Option<crate::value_layout::ScalarKind> {
    use crate::value_layout::ScalarKind as K;
    match v {
        GenericValue::Unit => Some(K::Unit),
        GenericValue::Bool(_) => Some(K::Bool),
        GenericValue::Byte(_) => Some(K::Byte),
        GenericValue::Int(_) => Some(K::Int),
        GenericValue::Fixed(_) => Some(K::Fixed),
        // A `Float` is flat (B28 P3 item 5): it packs by its little-endian
        // bytes (handled by `write_scalar_le`/`read_scalar_le`) and a
        // float-bearing composite is compared field-wise by the compiler, so
        // the byte residence does not change its IEEE equality semantics.
        #[cfg(feature = "floats")]
        GenericValue::Float(_) => Some(K::Float),
        // A `KStr` is flat as a two-word `(data_ptr, len)` arena reference
        // (B28 P3). `StaticStr` is heap-owned and not flat here; the VM
        // construct path copies it into the arena, converting it to a
        // `KStr`, before packing. `Opaque` stays non-flat (interned to a
        // one-word registry index by the VM, not packed from here).
        GenericValue::KStr(_) => Some(K::Text),
        _ => None,
    }
}

/// Byte length a value contributes as a field of a flat composite, or
/// `None` if it is not flat-eligible (B28 P2 nested inlining).
///
/// A flat-eligible scalar contributes its scalar size. A composite that
/// is itself in its `Flat` byte body contributes that body's byte
/// length, so it can be inlined into the parent's body. A boxed
/// composite or a reference-bearing value is not flat-eligible and forces
/// the parent boxed, exactly as `flat_tuple_scalar_kind` already does for
/// scalars.
pub(crate) fn flat_field_size<W: crate::word::Word, F: crate::float::Float>(
    v: &GenericValue<W, F>,
    word_bytes: usize,
    float_bytes: usize,
) -> Option<usize> {
    if let Some(kind) = flat_tuple_scalar_kind(v) {
        return Some(kind.size_in_bytes(word_bytes, float_bytes));
    }
    // A `StaticStr` is not directly packable (it has no arena `(ptr, len)`
    // handle); the VM construct path converts it to a `KStr` before packing,
    // and `flat_tuple_scalar_kind` already reports a `KStr` as `Text`. A
    // `StaticStr` reaching here through a host or constant path with no arena
    // therefore stays boxed via `try_pack_flat` returning `None` (B28 P3
    // item 5 C4).
    //
    // A nested flat composite contributes its body length. `byte_len` reads
    // the length of both an `Inline` and an `Arena` body without the arena, so
    // this size query is safe on an arena-resident child (the arena-direct
    // construction path packs un-materialised children; B28 P3 item 5
    // C-residual 3b), unlike the byte-borrowing `flat_body_bytes`.
    flat_composite_ref(v).map(|fc| fc.byte_len())
}

/// Whether `v` is flat-eligible as a tuple or array element including the
/// opaque reference kind (B28 P3 item 3), the value-side mirror of the
/// compiler's `classify_flat_field` for tuples and arrays. A tuple or array
/// is built flat only when every element satisfies this. `Opaque` is
/// eligible (the VM interns it to a one-word registry index). Text is not
/// eligible here: flattening a tuple's text would hide its `KStr` from the
/// `materialise_kstrings`/`contains_dynstr` lifecycle and remove the ability
/// to yield a static-text tuple, so a text-bearing tuple stays boxed (its
/// arena residence is the concern of the boxed-body arena migration). Every
/// other case reduces to `flat_field_size` (a flat scalar or
/// transitively-flat nested composite; a float, a string, or a boxed
/// composite is not eligible). The VM interns an `Opaque` before packing, so
/// this predicate takes the pre-interning value.
pub(crate) fn flat_tuple_element_with_refs<W: crate::word::Word, F: crate::float::Float>(
    v: &GenericValue<W, F>,
    word_bytes: usize,
    float_bytes: usize,
) -> bool {
    match v {
        // Both the host `Arc` form and the internal index form are opaque and
        // flat-eligible; the pack path converts either to the one-word index
        // (B33).
        GenericValue::Opaque(_) | GenericValue::OpaqueRef(_) => true,
        // A `Text` element (a `StaticStr` literal or a `KStr`) flattens to a
        // two-word `(ptr, len)` handle, the same representation as a flat
        // `Text` struct field (B28 P3 item 5 C4). It is flat-eligible only
        // when the word slot is at least the host pointer width, matching the
        // compiler's `classify_flat_field` narrow-word gate; a narrow-word
        // build keeps text boxed. A flat-text tuple/array is then subject to
        // the same cross-yield prohibition as a flat-text struct.
        GenericValue::StaticStr(_) | GenericValue::KStr(_) => {
            word_bytes >= core::mem::size_of::<usize>()
        }
        _ => flat_field_size(v, word_bytes, float_bytes).is_some(),
    }
}

/// Padding-tolerant equality of two flat enum bodies (B28 P2).
///
/// Compares the overlapping prefix and requires each trailing remainder
/// to be all-zero. This makes a compiler-padded body (`word + payload_max`)
/// equal to an unpadded variant-sized body of the same value, because the
/// only difference is deterministic zero padding. The discriminant word
/// lies within the prefix (both bodies are at least `word_bytes` long) and
/// is unique per variant, so two distinct variants always differ in the
/// prefix and never alias under this rule.
fn flat_enum_bytes_eq(a: &[u8], b: &[u8]) -> bool {
    let m = core::cmp::min(a.len(), b.len());
    a[..m] == b[..m] && a[m..].iter().all(|&x| x == 0) && b[m..].iter().all(|&x| x == 0)
}

/// The flat composite body of a `Flat`-bodied tuple, array, struct, or enum,
/// or `None` for a boxed composite or a non-composite. Borrows the
/// [`crate::flat_value::FlatComposite`] itself rather than its bytes, so the
/// caller chooses an arena-aware read (`resolve`) or an arena-less length query
/// (`byte_len`). Used by the arena-direct construction packer, which
/// inlines un-materialised arena children (B28 P3 item 5 C-residual 3b).
pub(crate) fn flat_composite_ref<W: crate::word::Word, F: crate::float::Float>(
    v: &GenericValue<W, F>,
) -> Option<&crate::flat_value::FlatComposite> {
    match v {
        GenericValue::Tuple(TupleBody::Flat(fc))
        | GenericValue::Array(ArrayBody::Flat(fc))
        | GenericValue::Struct(StructBody::Flat(fc))
        | GenericValue::Enum(EnumBody::Flat(fc)) => Some(fc),
        _ => None,
    }
}

/// Error from the total flat-scalar codec ([`GenericValue::read_scalar_le`]
/// and [`GenericValue::write_scalar_le`]). Replaces the prior panics on a
/// short buffer, a reference kind, or an unsupported width, so attacker-shaped
/// bytecode reaches a clean rejection rather than a panic or out-of-bounds
/// access (V0.2.1 security audit, findings 10, 11, 12, 14, 19, 20, 21).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalarError {
    /// The requested byte range lies outside the buffer.
    OutOfBounds,
    /// A reference kind (`Text`/`Opaque`) was requested through the flat
    /// fixed-scalar path, which carries only fixed scalars.
    ReferenceKind,
    /// An unsupported width: a float width other than 4 or 8 bytes, a word
    /// width above 8 bytes, or a non-fixed-scalar value on the write path.
    UnsupportedWidth,
}

impl<W: crate::word::Word, F: crate::float::Float> GenericValue<W, F> {
    /// Construct a tuple value, choosing the flat byte body for a
    /// transitively-scalar tuple and the boxed body otherwise (B28 P2).
    ///
    /// This is the common constructor used by hosts, tests, and the
    /// runtime. It delegates to [`GenericValue::tuple_with_widths`] at
    /// the runtime's own scalar widths (from [`crate::word::Word::BITS_LOG2`]
    /// and [`crate::float::Float::BITS_LOG2`]), which equal the
    /// module-declared widths on the bundled runtime. Routing every
    /// construction through the same flat-or-boxed decision is what lets
    /// a given tuple type have one representation, which tuple equality
    /// and flat access both rely on. A reference-bearing or float-
    /// bearing tuple is not flat-eligible and stays boxed.
    pub fn tuple(elements: alloc::vec::Vec<Self>) -> Self {
        let word_bytes = (1usize << <W as crate::word::Word>::BITS_LOG2) / 8;
        let float_bytes = (1usize << <F as crate::float::Float>::BITS_LOG2) / 8;
        Self::tuple_with_widths(elements, word_bytes, float_bytes)
    }

    /// Construct a tuple value, choosing the flat byte body for a
    /// transitively-scalar tuple and the boxed body otherwise, using
    /// the given scalar widths (B28 P2).
    ///
    /// This is the single choke point for tuple construction so every
    /// path (the VM `NewTuple` handler, constant materialisation, and
    /// host marshalling) agrees on the representation for a given type.
    /// A flat body is produced only when every element is a
    /// flat-eligible scalar (see `flat_tuple_scalar_kind`) and the
    /// packed size fits the sixteen-bit access offset; the fields are
    /// written little-endian at packed offsets using `word_bytes` and
    /// `float_bytes`, the same widths the compiler bakes access offsets
    /// against.
    pub fn tuple_with_widths(
        elements: alloc::vec::Vec<Self>,
        word_bytes: usize,
        float_bytes: usize,
    ) -> Self {
        // No arena is available here (B28 item 2 step 6B), so a flat body has
        // nowhere to live: the owned `Inline` form is gone and every flat body
        // is an arena region handle. The no-arena path therefore produces the
        // boxed representation. The runtime builds flat composites through the
        // arena-direct `*_in_arena` family instead, and a host that wants a flat
        // arena body uses the `into_value_ctx` boundary (B36); composite
        // equality is field-wise, so the boxed host representation compares
        // equal to a flat runtime one of the same type.
        let _ = (word_bytes, float_bytes);
        Self::Tuple(TupleBody::boxed(elements))
    }

    /// Construct an array value at the runtime's own scalar widths,
    /// choosing the flat byte body for a transitively-scalar element type
    /// and the boxed body otherwise (B28 P2). The array analogue of
    /// [`GenericValue::tuple`].
    pub fn array(elements: alloc::vec::Vec<Self>) -> Self {
        let word_bytes = (1usize << <W as crate::word::Word>::BITS_LOG2) / 8;
        let float_bytes = (1usize << <F as crate::float::Float>::BITS_LOG2) / 8;
        Self::array_with_widths(elements, word_bytes, float_bytes)
    }

    /// Construct an array value, choosing the flat byte body for a
    /// transitively-scalar element type and the boxed body otherwise,
    /// using the given scalar widths (B28 P2).
    ///
    /// This is the single choke point for array construction so the VM
    /// `NewArray` handler, constant materialisation, and host marshalling
    /// all agree on the representation an array type uses, which equality
    /// relies on. The eligibility rule is the same as for a tuple field
    /// (`flat_tuple_scalar_kind`): a flat body is produced only when
    /// every element is a flat-eligible scalar and the packed size fits
    /// the sixteen-bit access offset. Because the array is homogeneous the
    /// elements share one kind, so the packed layout is `count * size`.
    pub fn array_with_widths(
        elements: alloc::vec::Vec<Self>,
        word_bytes: usize,
        float_bytes: usize,
    ) -> Self {
        // No arena here, so the no-arena path is boxed; see `tuple_with_widths`
        // (B28 item 2 step 6B). The runtime builds arrays through `array_in_arena`.
        let _ = (word_bytes, float_bytes);
        Self::Array(ArrayBody::boxed(elements))
    }

    /// Construct a struct value at the runtime's own scalar widths,
    /// choosing the flat byte body for a transitively-scalar field list and
    /// the boxed body otherwise (B28 P2). The struct analogue of
    /// [`GenericValue::tuple`]; `fields` must be in declaration order.
    pub fn struct_value(
        type_name: alloc::string::String,
        fields: alloc::vec::Vec<(alloc::string::String, Self)>,
    ) -> Self {
        let word_bytes = (1usize << <W as crate::word::Word>::BITS_LOG2) / 8;
        let float_bytes = (1usize << <F as crate::float::Float>::BITS_LOG2) / 8;
        Self::struct_with_widths(type_name, fields, word_bytes, float_bytes)
    }

    /// Construct a struct value, choosing the flat byte body for a
    /// transitively-scalar field list and the boxed body otherwise, using
    /// the given scalar widths (B28 P2).
    ///
    /// The single choke point for struct construction, so the VM
    /// `NewStruct` handler, constant materialisation, and host marshalling
    /// agree on the representation a struct type uses, which equality relies
    /// on. `fields` are packed in declaration order, the same order the
    /// compiler bakes field offsets against; the eligibility rule is the
    /// same as for a tuple field (`flat_tuple_scalar_kind`). A flat body
    /// carries no type name or field names.
    pub fn struct_with_widths(
        type_name: alloc::string::String,
        fields: alloc::vec::Vec<(alloc::string::String, Self)>,
        word_bytes: usize,
        float_bytes: usize,
    ) -> Self {
        // No arena here, so the no-arena path is boxed; see `tuple_with_widths`
        // (B28 item 2 step 6B). The runtime builds structs through `struct_in_arena`.
        let _ = (word_bytes, float_bytes);
        Self::Struct(StructBody::boxed(type_name, fields))
    }

    /// Construct an enum value at the runtime's own scalar widths, choosing
    /// the flat byte body for a transitively-scalar payload and the boxed
    /// body otherwise (B28 P2). `disc` is the variant's discriminant value.
    pub fn enum_value(
        type_name: alloc::string::String,
        variant: alloc::string::String,
        disc: i64,
        fields: alloc::vec::Vec<Self>,
    ) -> Self {
        let word_bytes = (1usize << <W as crate::word::Word>::BITS_LOG2) / 8;
        let float_bytes = (1usize << <F as crate::float::Float>::BITS_LOG2) / 8;
        // Ad-hoc construction with no type-table knowledge: produce a
        // variant-sized (unpadded) body. Padding-tolerant flat-enum
        // equality lets this still compare equal to a compiler-padded
        // value of the same variant (B28 P2).
        Self::enum_with_widths(type_name, variant, disc, fields, 0, word_bytes, float_bytes)
    }

    /// Construct an enum value at the given scalar widths (B28 P2). No arena is
    /// available here, so the no-arena path produces the boxed representation
    /// (B28 item 2 step 6B); the owned `Inline` flat body is gone and every flat
    /// body is an arena region handle. The runtime builds flat enums through the
    /// arena-direct path, and host/const enums stay boxed, which composite
    /// equality (field-wise) and the boxed access ops handle. `disc`,
    /// `min_payload`, and the widths are accepted for signature compatibility
    /// with the callers and are not needed by the boxed body, which records the
    /// `variant` name from which the discriminant is recovered.
    pub fn enum_with_widths(
        type_name: alloc::string::String,
        variant: alloc::string::String,
        disc: i64,
        fields: alloc::vec::Vec<Self>,
        min_payload: usize,
        word_bytes: usize,
        float_bytes: usize,
    ) -> Self {
        // No arena here, so the body is boxed; the discriminant and the
        // largest-variant payload size are recorded so the VM-entry
        // `into_arena_canonical` can re-flatten a host enum argument to the
        // `[disc word][payload]` form flat access expects, padded for nesting
        // (B28 item 2 step 6B).
        let _ = (word_bytes, float_bytes);
        Self::Enum(EnumBody::boxed_with_layout(
            type_name,
            variant,
            disc,
            min_payload,
            fields,
        ))
    }

    /// Arena-direct counterpart of [`GenericValue::tuple_with_widths`] (B28 P3
    /// item 2, Increment 3).
    ///
    /// Packs a flat-eligible tuple body straight into the arena through
    /// [`GenericValue::pack_flat_in_arena`], with no intermediate global-heap
    /// `Inline`; a reference- or boxed-element tuple falls back to the boxed
    /// body exactly as the global-heap constructor does. The host marshalling
    /// boundary calls this so a native tuple result carries no global-heap
    /// body. A nested composite element is still built by the global-heap
    /// `into_value` and resolved-and-copied into the parent's single arena
    /// allocation, so the arena footprint is exactly one body (no per-child
    /// arena allocation, hence no change to the worst-case-memory accounting);
    /// eliminating that transient child `Inline` is the Increment 5 collapse.
    pub fn tuple_in_arena(
        elements: alloc::vec::Vec<Self>,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        match Self::pack_flat_in_arena(&elements, 0, word_bytes, float_bytes, arena)? {
            Some(body) => Ok(Self::Tuple(TupleBody::Flat(body))),
            None => Ok(Self::Tuple(TupleBody::boxed(elements))),
        }
    }

    /// Arena-direct counterpart of [`GenericValue::array_with_widths`] (B28 P3
    /// item 2, Increment 3). See [`GenericValue::tuple_in_arena`].
    pub fn array_in_arena(
        elements: alloc::vec::Vec<Self>,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        match Self::pack_flat_in_arena(&elements, 0, word_bytes, float_bytes, arena)? {
            Some(body) => Ok(Self::Array(ArrayBody::Flat(body))),
            None => Ok(Self::Array(ArrayBody::boxed(elements))),
        }
    }

    /// Arena-direct counterpart of [`GenericValue::struct_with_widths`] (B28 P3
    /// item 2, Increment 3). See [`GenericValue::tuple_in_arena`]. The field
    /// names are retained for the boxed fallback by unzipping before the pack
    /// and rezipping only on the not-flat-eligible path.
    pub fn struct_in_arena(
        type_name: alloc::string::String,
        fields: alloc::vec::Vec<(alloc::string::String, Self)>,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        let (names, values): (
            alloc::vec::Vec<alloc::string::String>,
            alloc::vec::Vec<Self>,
        ) = fields.into_iter().unzip();
        match Self::pack_flat_in_arena(&values, 0, word_bytes, float_bytes, arena)? {
            Some(body) => Ok(Self::Struct(StructBody::Flat(body))),
            None => Ok(Self::Struct(StructBody::boxed(
                type_name,
                names.into_iter().zip(values).collect(),
            ))),
        }
    }

    /// Arena-direct enum constructor (B28 item 2 step 6B). Packs a flat enum
    /// body `[disc word][payload]` straight into the arena, matching the layout
    /// [`GenericValue::enum_with_widths`] produced before the `Inline` form was
    /// removed and what [`Op::IsEnum`]/[`Op::GetEnumField`] read. The
    /// discriminant is the leading `Word`; the payload packs in declaration
    /// order with no variant padding (`min_bytes` is the discriminant word
    /// alone), which a host-built value not inlined into a fixed parent slot
    /// permits. A reference- or float-bearing payload is not flat-eligible and
    /// falls back to the boxed body. The built-in generic `Option` is kept
    /// boxed by the caller, since its access is baked boxed.
    // An enum's flat body needs its name, variant, discriminant, padding hint,
    // payload, the two scalar widths, and the arena; the eight parameters are
    // irreducible (the names and variant feed the boxed fallback, the rest the
    // flat pack), so the arity lint is allowed here, as the pre-6B note on this
    // constructor anticipated.
    #[allow(clippy::too_many_arguments)]
    pub fn enum_in_arena(
        type_name: alloc::string::String,
        variant: alloc::string::String,
        disc: i64,
        min_payload: usize,
        fields: alloc::vec::Vec<Self>,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        let disc_value = Self::Int(<W as crate::word::Word>::from_i64_wrap(disc));
        let mut values: alloc::vec::Vec<Self> = alloc::vec::Vec::with_capacity(fields.len() + 1);
        values.push(disc_value);
        values.extend(fields);
        // `min_bytes == word_bytes + min_payload`: the discriminant word plus
        // the largest-variant payload, so every value of a uniformly flat enum
        // shares one fixed body size and nests in a parent at a stable slot
        // (matching the body `enum_with_widths` produced before the `Inline`
        // form was removed). A top-level host enum has `min_payload == 0` and is
        // variant-sized.
        let min_bytes = word_bytes + min_payload;
        match Self::pack_flat_in_arena(&values, min_bytes, word_bytes, float_bytes, arena)? {
            Some(body) => Ok(Self::Enum(EnumBody::Flat(body))),
            None => {
                // Not flat-eligible: rebuild the boxed body, dropping the
                // leading discriminant word back into the recorded hint.
                let mut it = values.into_iter();
                it.next();
                let fields: alloc::vec::Vec<Self> = it.collect();
                Ok(Self::Enum(EnumBody::boxed_with_layout(
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                )))
            }
        }
    }

    /// Re-pack a host-built boxed composite into an arena-resident flat body so
    /// the compiler-baked flat field-access ops can read it (B28 item 2 step
    /// 6B). The arena-less host constructors ([`Self::enum_with_widths`] and
    /// kin, the `KeleusmaType` derive's no-arena `from_value`) can only produce
    /// the boxed representation, but a script reads a host-provided composite
    /// argument through flat-baked ops ([`Op::GetField`]/[`Op::GetTupleField`]/
    /// [`Op::GetEnumField`]) that reject a boxed body. This canonicalisation
    /// runs at the VM entry points (call arguments and the resume value) where
    /// the arena is available. It recurses bottom-up, so a nested boxed child
    /// becomes flat first and lets its parent flatten.
    ///
    /// A scalar, reference, already-flat, `Unit`, or `None` value is returned
    /// unchanged. A composite whose payload is not flat-eligible (a reference-
    /// or float-bearing field, or an `Option`) stays boxed and is read through
    /// the boxed access ops, which tolerate it. Widths are the MODULE widths,
    /// so a narrow-word build casts each host scalar to the module width
    /// exactly as [`crate::marshall::KeleusmaType::from_value_ctx`] does (B36);
    /// the cast cannot widen because the loader requires module width at most
    /// runtime width.
    pub fn into_arena_canonical(
        self,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        match self {
            Self::Tuple(TupleBody::Boxed(elems)) => {
                let elems = (*elems)
                    .into_iter()
                    .map(|v| v.into_arena_canonical_field(word_bytes, float_bytes, arena))
                    .collect::<Result<alloc::vec::Vec<_>, _>>()?;
                Self::tuple_in_arena(elems, word_bytes, float_bytes, arena)
            }
            Self::Array(ArrayBody::Boxed(elems)) => {
                let elems = (*elems)
                    .into_iter()
                    .map(|v| v.into_arena_canonical_field(word_bytes, float_bytes, arena))
                    .collect::<Result<alloc::vec::Vec<_>, _>>()?;
                Self::array_in_arena(elems, word_bytes, float_bytes, arena)
            }
            Self::Struct(StructBody::Boxed(b)) => {
                let BoxedStruct { type_name, fields } = *b;
                let fields = fields
                    .into_iter()
                    .map(|(k, v)| {
                        Ok::<_, allocator_api2::alloc::AllocError>((
                            k,
                            v.into_arena_canonical_field(word_bytes, float_bytes, arena)?,
                        ))
                    })
                    .collect::<Result<alloc::vec::Vec<_>, _>>()?;
                Self::struct_in_arena(type_name, fields, word_bytes, float_bytes, arena)
            }
            Self::Enum(EnumBody::Boxed(b)) => {
                let BoxedEnum {
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                } = *b;
                // `Option::Some` flattens like any enum (B28 P3 item 5 C4): the
                // compiler bakes flat construction and flat access for
                // `Option<T>` when `T` is a flat field, with the fixed
                // discriminant `Some == 1`. An earlier branch kept `Option`
                // boxed on the B28 P2 assumption that its access was baked
                // boxed, which left a native-returned `Option<Text>` boxed
                // against flat-baked access (B37). Promote the payload and
                // flatten with the `Option` discriminant; `enum_in_arena` falls
                // back to boxed when the payload is not flat-eligible, matching
                // the compiler's boxed access for `Option<non-flat>`. The
                // discriminant carried by an unsignatured native's `EnumBody`
                // is not reliable (the no-arena constructor records `0`), so the
                // fixed `Some == 1` convention is applied here rather than
                // trusting `disc`. `Option::None` is the scalar `Value::None`
                // and never reaches this arm.
                if type_name == "Option" {
                    let fields = fields
                        .into_iter()
                        .map(|v| v.into_arena_canonical_field(word_bytes, float_bytes, arena))
                        .collect::<Result<alloc::vec::Vec<_>, _>>()?;
                    return Self::enum_in_arena(
                        type_name,
                        variant,
                        1,
                        min_payload,
                        fields,
                        word_bytes,
                        float_bytes,
                        arena,
                    );
                }
                let fields = fields
                    .into_iter()
                    .map(|v| v.into_arena_canonical_field(word_bytes, float_bytes, arena))
                    .collect::<Result<alloc::vec::Vec<_>, _>>()?;
                Self::enum_in_arena(
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                    word_bytes,
                    float_bytes,
                    arena,
                )
            }
            other => Ok(other),
        }
    }

    /// Canonicalise a composite *field* for flat packing (B28, B37).
    ///
    /// First canonicalises the field through [`Self::into_arena_canonical`]
    /// (flattening a nested composite), then promotes an owned `StaticStr`
    /// to an arena `KStr`. The promotion is what lets a text-bearing
    /// composite pack flat: the compiler classifies a `Text` field as a flat
    /// `(ptr, len)` when the module word slot holds a host pointer
    /// (`classify_flat_field`), and the value-side packer
    /// ([`Self::pack_flat_in_arena`] via `flat_field_size`) treats a `KStr`,
    /// but not a `StaticStr`, as that flat field. An unsignatured native that
    /// builds its result with no arena returns a boxed composite whose text
    /// is a `StaticStr`; without this promotion the result stays boxed and
    /// mismatches the compiler's baked flat access (`InvalidBytecode` at the
    /// `GetTupleField`/`GetStructField` access). Promoting the field here
    /// makes a native-returned composite identical to the one the in-script
    /// `NewComposite` path builds for the same type.
    ///
    /// Only a composite *field* is promoted, not a top-level bare `StaticStr`
    /// return: a bare string is read directly, never through baked flat
    /// composite access, so leaving it owned avoids a needless arena copy.
    ///
    /// The promotion is gated on `word_bytes >= host pointer width`, the same
    /// condition `classify_flat_field` uses to admit a flat `Text` field. On a
    /// narrow-word build the compiler keeps `Text` boxed and bakes boxed
    /// access, so the `StaticStr` is left owned and the composite stays boxed,
    /// matching that access. Without the gate the field would promote to a
    /// `KStr` and the composite would pack flat against a boxed access,
    /// reintroducing the very mismatch this repair removes, on narrow targets.
    fn into_arena_canonical_field(
        self,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        match self.into_arena_canonical(word_bytes, float_bytes, arena)? {
            Self::StaticStr(s) if word_bytes >= core::mem::size_of::<usize>() => {
                let ks = crate::kstring::KString::alloc(arena, &s)?;
                Ok(Self::KStr(ks))
            }
            other => Ok(other),
        }
    }

    /// Write this fixed-size scalar's little-endian bytes into `dst` at
    /// `offset` (B28 P2). The width of an `Int`/`Fixed` is `word_bytes`
    /// and of a `Float` is `float_bytes`, taken from the runtime's
    /// target descriptor, so the same routine serves narrow runtimes.
    /// `Unit` and `None` write nothing.
    ///
    /// This is the pack half of the composite construct handlers: each
    /// field's scalar is written at the offset the compiler baked.
    /// Reference scalars (`StaticStr`, `KStr`, `Opaque`) and composites
    /// are handled by later phases and panic here, which a correct
    /// compiler never reaches because it routes them differently.
    #[cfg_attr(not(feature = "floats"), allow(unused_variables))]
    pub fn write_scalar_le(
        &self,
        dst: &mut [u8],
        offset: usize,
        word_bytes: usize,
        float_bytes: usize,
    ) -> Result<(), ScalarError> {
        // Checked mutable slice of `n` bytes at `offset`; an out-of-range
        // offset rejects cleanly rather than panicking.
        fn slice_mut(dst: &mut [u8], offset: usize, n: usize) -> Result<&mut [u8], ScalarError> {
            offset
                .checked_add(n)
                .and_then(|end| dst.get_mut(offset..end))
                .ok_or(ScalarError::OutOfBounds)
        }
        match self {
            Self::Unit | Self::None => {}
            Self::Bool(b) => *dst.get_mut(offset).ok_or(ScalarError::OutOfBounds)? = u8::from(*b),
            Self::Byte(b) => *dst.get_mut(offset).ok_or(ScalarError::OutOfBounds)? = *b,
            Self::Int(w) | Self::Fixed(w) => {
                if word_bytes > 8 {
                    return Err(ScalarError::UnsupportedWidth);
                }
                let le = w.to_i64().to_le_bytes();
                slice_mut(dst, offset, word_bytes)?.copy_from_slice(&le[..word_bytes]);
            }
            #[cfg(feature = "floats")]
            Self::Float(f) => {
                let v = f.to_f64();
                match float_bytes {
                    8 => slice_mut(dst, offset, 8)?.copy_from_slice(&v.to_le_bytes()),
                    4 => slice_mut(dst, offset, 4)?.copy_from_slice(&(v as f32).to_le_bytes()),
                    _ => return Err(ScalarError::UnsupportedWidth),
                }
            }
            // A `KStr` Text field is two words: the arena data pointer then
            // the byte length, each `word_bytes` wide (B28 P3). The epoch is
            // reattached at the read side, not stored. This requires
            // `word_bytes` to be at least the host pointer width, which the
            // bundled `i64` runtime satisfies; a narrower-word target keeps
            // `Text` boxed (a separate compile-time gate), so a narrow word
            // here rejects rather than truncating the pointer.
            Self::KStr(ks) => {
                let (ptr, len) = ks.raw_parts();
                if word_bytes < core::mem::size_of::<usize>() {
                    return Err(ScalarError::UnsupportedWidth);
                }
                let pe = (ptr as u64).to_le_bytes();
                slice_mut(dst, offset, word_bytes)?.copy_from_slice(&pe[..word_bytes]);
                let le = (len as u64).to_le_bytes();
                slice_mut(dst, offset + word_bytes, word_bytes)?.copy_from_slice(&le[..word_bytes]);
            }
            // Composite, reference, or otherwise non-fixed-scalar values are
            // not writable through this path.
            _ => return Err(ScalarError::UnsupportedWidth),
        }
        Ok(())
    }

    /// Build a boxed composite of `kind` from `values` (B28 P4). For a
    /// struct the `names` are the field names (declaration order); for an
    /// enum `names[0]` is the variant name and `type_name` the enum name; a
    /// tuple or array ignores `type_name` and `names`. The boxed form is the
    /// interim representation for a reference-bearing field or `Option`,
    /// removed at P3.
    pub fn new_composite_boxed(
        kind: crate::value_layout::CompositeKind,
        type_name: alloc::string::String,
        names: alloc::vec::Vec<alloc::string::String>,
        values: alloc::vec::Vec<Self>,
    ) -> Self {
        use crate::value_layout::CompositeKind as C;
        match kind {
            C::Tuple => Self::Tuple(TupleBody::boxed(values)),
            C::Array => Self::Array(ArrayBody::boxed(values)),
            C::Struct => Self::Struct(StructBody::boxed(
                type_name,
                names.into_iter().zip(values).collect(),
            )),
            C::Enum => {
                let variant = names.into_iter().next().unwrap_or_default();
                Self::Enum(EnumBody::boxed(type_name, variant, values))
            }
        }
    }

    /// Re-wrap a nested composite's extracted byte range as a flat
    /// composite `Value` of the given kind (B28 P2 nested inlining). The
    /// access handler slices the child body out of the parent and calls
    /// this to materialise the field value. The bytes are copied into a
    /// fresh body, so the result is independent of the parent.
    /// Extract a nested child composite occupying `[offset, offset + size)` of
    /// `parent`, as a flat composite `Value` of `variant` kind, viewing the
    /// child in place (B28 P3 item 5 C-residual 3b). The arena parent yields a
    /// zero-copy sub-handle into its own storage (see
    /// [`crate::flat_value::FlatComposite::nested_view`]), so a nested access
    /// allocates nothing. Returns [`keleusma_arena::Stale`] only if an arena
    /// parent no longer resolves, which a correct caller never observes.
    pub fn flat_nested_field(
        parent: &crate::flat_value::FlatComposite,
        offset: usize,
        size: usize,
        variant: crate::value_layout::CompositeKind,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, keleusma_arena::Stale> {
        use crate::value_layout::CompositeKind as C;
        let fc = parent.nested_view(offset, size, arena)?;
        Ok(match variant {
            C::Tuple => Self::Tuple(TupleBody::Flat(fc)),
            C::Array => Self::Array(ArrayBody::Flat(fc)),
            C::Struct => Self::Struct(StructBody::Flat(fc)),
            C::Enum => Self::Enum(EnumBody::Flat(fc)),
        })
    }

    /// Migrate a flat composite value's body to the arena's top ephemeral
    /// head (B28 P2 arena residence). A `Flat`-bodied tuple, array, struct,
    /// or enum has its body copied to the arena and replaced with an
    /// epoch-guarded handle; any other value (a scalar, a boxed composite,
    /// a reference) is returned unchanged. The VM calls this on a
    /// freshly-constructed composite so it carries no global-heap allocation
    /// across a `loop` iteration's `RESET`.
    pub fn into_arena_body(
        self,
        arena: &keleusma_arena::Arena,
    ) -> Result<Self, allocator_api2::alloc::AllocError> {
        Ok(match self {
            Self::Tuple(TupleBody::Flat(fc)) => Self::Tuple(TupleBody::Flat(fc.in_arena(arena)?)),
            Self::Array(ArrayBody::Flat(fc)) => Self::Array(ArrayBody::Flat(fc.in_arena(arena)?)),
            Self::Struct(StructBody::Flat(fc)) => {
                Self::Struct(StructBody::Flat(fc.in_arena(arena)?))
            }
            Self::Enum(EnumBody::Flat(fc)) => Self::Enum(EnumBody::Flat(fc.in_arena(arena)?)),
            other => other,
        })
    }

    /// Materialise any arena-resident composite body in this value back to
    /// an owned `Inline` body (B28 P2 arena residence). A `Flat` body is
    /// copied out of the arena (its bytes are self-contained, so nested
    /// composites come with it); a `Boxed` body recurses into its element
    /// values, since those are separate values that may themselves be
    /// arena-resident. Scalars and references are returned unchanged.
    ///
    /// Used to bridge arena bodies across the three points that read bytes
    /// without an arena handle: the shared construction packer (which reads
    /// a child field's bytes to inline them), value equality, and the
    /// native-call boundary (where `from_value` has no arena).
    /// The originating arena epoch of this value's flat composite body, if
    /// it has one (B28 P3 item 1). A flat `Text` field is decoded by
    /// reattaching this epoch so a read after a `RESET` resolves `Stale`.
    /// Returns `None` for a boxed or non-composite value, whose reference
    /// fields (a bare `KStr`, an opaque index) carry their own validity.
    pub fn flat_ref_epoch(&self) -> Option<u64> {
        match self {
            Self::Tuple(TupleBody::Flat(fc)) => Some(fc.ref_epoch()),
            Self::Array(ArrayBody::Flat(fc)) => Some(fc.ref_epoch()),
            Self::Struct(StructBody::Flat(fc)) => Some(fc.ref_epoch()),
            Self::Enum(EnumBody::Flat(fc)) => Some(fc.ref_epoch()),
            _ => None,
        }
    }

    /// Pack `values` into a flat byte body built *directly in the arena*,
    /// padded to at least `min_bytes` (B28 P3 item 5 C-residual 3b). Used by
    /// the VM `Op::NewComposite` handler so a freshly constructed composite is
    /// arena-resident with no global-heap allocation. Since B28 item 2 step 6B
    /// this is the only flat-packing path; the owned-bytes `Inline` form and
    /// its `try_pack_flat` packer are gone, so a no-arena caller (host
    /// marshalling, constants) uses the boxed representation or the const pool
    /// instead.
    ///
    /// Returns `Ok(None)` when any value is not flat-eligible (a reference or
    /// boxed field) or the packed body exceeds the sixteen-bit access offset,
    /// in which case the caller falls back to the boxed body. Returns
    /// `Err(AllocError)` when the arena top head cannot satisfy the allocation.
    ///
    /// The fields are packed contiguously in order at running offsets (the
    /// flat model has no inter-field padding), so the `[0, packed)` prefix is
    /// written exactly once by the fields and the `[packed, size)` slack is
    /// zero-filled; together they cover every byte of the uninitialised arena
    /// allocation. A nested child is inlined by resolving its arena bytes and
    /// copying them into the parent's destination, never through an owned
    /// `Inline` intermediate.
    pub fn pack_flat_in_arena(
        values: &[Self],
        min_bytes: usize,
        word_bytes: usize,
        float_bytes: usize,
        arena: &keleusma_arena::Arena,
    ) -> Result<Option<crate::flat_value::FlatComposite>, allocator_api2::alloc::AllocError> {
        // Size and eligibility first, with no allocation: `flat_field_size`
        // reads a nested child's length through `byte_len`, which is valid for
        // both an `Inline` and an `Arena` body, so this is safe on the
        // un-materialised arena children the VM packs here.
        let mut size = 0usize;
        for v in values {
            match flat_field_size(v, word_bytes, float_bytes) {
                Some(n) => size += n,
                None => return Ok(None),
            }
        }
        if size < min_bytes {
            size = min_bytes;
        }
        if size > u16::MAX as usize {
            return Ok(None);
        }
        crate::flat_value::FlatComposite::build_in_arena(arena, size, |dst| {
            let mut off = 0usize;
            for v in values {
                if let Some(kind) = flat_tuple_scalar_kind(v) {
                    let field = kind.size_in_bytes(word_bytes, float_bytes);
                    v.write_scalar_le(dst, off, word_bytes, float_bytes)
                        .map_err(|_| ())?;
                    off += field;
                } else if let Some(fc) = flat_composite_ref(v) {
                    // A freshly constructed child resolves under the current
                    // epoch (no `RESET` intervenes); an unexpected stale child
                    // aborts the build (`Err(())` -> `None`, caller boxes).
                    let bytes = fc.resolve(arena).map_err(|_| ())?;
                    dst[off..off + bytes.len()].copy_from_slice(bytes);
                    off += bytes.len();
                } else {
                    // Not flat-eligible; eligibility was checked above, so this
                    // is unreachable for a correct caller.
                    return Err(());
                }
            }
            // Zero the trailing padding slack (an enum padded to its largest
            // variant); the arena storage was uninitialised.
            for b in dst[off..size].iter_mut() {
                *b = 0;
            }
            Ok(())
        })
    }

    /// Read a fixed-size scalar of `kind` from `src` at `offset` (B28
    /// P2), the read half of the composite access handlers. `Int` and
    /// `Fixed` are sign-extended from `word_bytes`; `Float` is widened
    /// from `float_bytes`. `kind` is the value the compiler baked into
    /// the access instruction. Panics on the reference kinds and on a
    /// `kind` outside the fixed-size scalar set, which later phases
    /// handle.
    #[cfg_attr(not(feature = "floats"), allow(unused_variables))]
    pub fn read_scalar_le(
        src: &[u8],
        offset: usize,
        kind: crate::value_layout::ScalarKind,
        word_bytes: usize,
        float_bytes: usize,
    ) -> Result<Self, ScalarError> {
        use crate::value_layout::ScalarKind;
        // Checked slice of `n` bytes at `offset`. The flat offset is operand
        // data the structural verifier does not yet bound, so an out-of-range
        // offset rejects cleanly rather than panicking or reading OOB.
        let slice = |n: usize| -> Result<&[u8], ScalarError> {
            offset
                .checked_add(n)
                .and_then(|end| src.get(offset..end))
                .ok_or(ScalarError::OutOfBounds)
        };
        match kind {
            ScalarKind::Unit => Ok(Self::Unit),
            ScalarKind::Bool => Ok(Self::Bool(
                *src.get(offset).ok_or(ScalarError::OutOfBounds)? != 0,
            )),
            ScalarKind::Byte => Ok(Self::Byte(
                *src.get(offset).ok_or(ScalarError::OutOfBounds)?,
            )),
            ScalarKind::Int | ScalarKind::Fixed => {
                if word_bytes > 8 {
                    return Err(ScalarError::UnsupportedWidth);
                }
                let mut buf = [0u8; 8];
                buf[..word_bytes].copy_from_slice(slice(word_bytes)?);
                let mut n = i64::from_le_bytes(buf);
                // Sign-extend a narrow word from its top bit.
                if word_bytes < 8 {
                    let bits = word_bytes * 8;
                    let sign = 1i64 << (bits - 1);
                    if n & sign != 0 {
                        n |= !((1i64 << bits) - 1);
                    }
                }
                let w = W::from_i64_wrap(n);
                Ok(if matches!(kind, ScalarKind::Fixed) {
                    Self::Fixed(w)
                } else {
                    Self::Int(w)
                })
            }
            #[cfg(feature = "floats")]
            ScalarKind::Float => {
                let v = match float_bytes {
                    8 => {
                        let mut buf = [0u8; 8];
                        buf.copy_from_slice(slice(8)?);
                        f64::from_le_bytes(buf)
                    }
                    4 => {
                        let mut buf = [0u8; 4];
                        buf.copy_from_slice(slice(4)?);
                        f32::from_le_bytes(buf) as f64
                    }
                    _ => return Err(ScalarError::UnsupportedWidth),
                };
                Ok(Self::Float(F::from_f64(v)))
            }
            ScalarKind::Text | ScalarKind::Opaque => Err(ScalarError::ReferenceKind),
        }
    }

    /// Walk the value recursively and replace every `KStr` variant
    /// with an equivalent `StaticStr` whose contents come from the
    /// supplied arena. Use this when transporting a value across a
    /// Vm boundary: `KStr` handles reference the original arena
    /// through an epoch-tagged pointer, so a value snapshotted from
    /// one Vm and restored into a Vm backed by a different arena
    /// would carry a stale handle. Materialising to `StaticStr`
    /// breaks the arena dependency so the value is portable.
    ///
    /// Composite variants (`Tuple`, `Array`, `Struct`, `Enum`) are
    /// walked recursively. Scalar variants are cloned unchanged.
    /// `Opaque` values are cloned by `Arc` increment as usual; the
    /// `HostOpaque` trait makes no assumption about arena residency.
    ///
    /// Stale `KStr` handles produce an empty `StaticStr`. A stale
    /// handle here means the original arena was already dropped
    /// between snapshot and materialisation, which should not happen
    /// in the documented REPL pattern but is handled defensively.
    pub fn materialise_kstrings(&self, arena: &keleusma_arena::Arena) -> Self {
        match self {
            Self::KStr(handle) => match handle.get(arena) {
                Ok(s) => Self::StaticStr(alloc::string::String::from(s)),
                Err(_) => Self::StaticStr(alloc::string::String::new()),
            },
            // A flat tuple is transitively scalar, so it holds no KStr
            // and materialises to itself. A boxed tuple may carry a
            // KStr and is walked element-wise.
            Self::Tuple(TupleBody::Flat(_)) => self.clone(),
            Self::Tuple(TupleBody::Boxed(items)) => Self::tuple(
                items
                    .iter()
                    .map(|v| v.materialise_kstrings(arena))
                    .collect(),
            ),
            // A flat array is transitively scalar and holds no KStr; a
            // boxed array is walked element-wise.
            Self::Array(ArrayBody::Flat(_)) => self.clone(),
            Self::Array(ArrayBody::Boxed(items)) => Self::array(
                items
                    .iter()
                    .map(|v| v.materialise_kstrings(arena))
                    .collect(),
            ),
            Self::Struct(StructBody::Flat(_)) => self.clone(),
            Self::Struct(StructBody::Boxed(b)) => Self::struct_value(
                b.type_name.clone(),
                b.fields
                    .iter()
                    .map(|(k, v)| (k.clone(), v.materialise_kstrings(arena)))
                    .collect(),
            ),
            // A flat enum is transitively scalar and holds no KStr.
            Self::Enum(EnumBody::Flat(_)) => self.clone(),
            Self::Enum(EnumBody::Boxed(b)) => Self::Enum(EnumBody::boxed_with_layout(
                b.type_name.clone(),
                b.variant.clone(),
                b.disc,
                b.min_payload,
                b.fields
                    .iter()
                    .map(|v| v.materialise_kstrings(arena))
                    .collect(),
            )),
            other => other.clone(),
        }
    }

    /// 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",
            // The internal index form names the same surface type. Resolving
            // the host-specific name needs the registry; diagnostics use the
            // generic literal, as for `Opaque` above (B33).
            Self::OpaqueRef(_) => "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,
            // A flat tuple is transitively scalar and cannot hold a
            // dynamic string; a boxed tuple is walked element-wise.
            Self::Tuple(TupleBody::Flat(_)) => false,
            Self::Tuple(TupleBody::Boxed(items)) => items.iter().any(Self::contains_dynstr),
            Self::Array(ArrayBody::Flat(_)) => false,
            Self::Array(ArrayBody::Boxed(items)) => items.iter().any(Self::contains_dynstr),
            Self::Struct(StructBody::Flat(_)) => false,
            Self::Struct(StructBody::Boxed(b)) => b.fields.iter().any(|(_, v)| v.contains_dynstr()),
            Self::Enum(EnumBody::Flat(_)) => false,
            Self::Enum(EnumBody::Boxed(b)) => b.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,
        word_bytes: usize,
        float_bytes: usize,
    ) -> 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())
            }
            // A constant tuple materialises through the same flat-or-boxed
            // choice as every other construction path, so a scalar
            // constant tuple matches a runtime-built one and the baked
            // flat access reads it correctly (B28 P2).
            ArchivedConstValue::Tuple(items) => Self::tuple_with_widths(
                items
                    .iter()
                    .map(|c| Self::from_const_archived(c, word_bytes, float_bytes))
                    .collect(),
                word_bytes,
                float_bytes,
            ),
            ArchivedConstValue::Array(items) => Self::array_with_widths(
                items
                    .iter()
                    .map(|c| Self::from_const_archived(c, word_bytes, float_bytes))
                    .collect(),
                word_bytes,
                float_bytes,
            ),
            ArchivedConstValue::Struct { type_name, fields } => {
                use alloc::string::ToString;
                Self::struct_with_widths(
                    type_name.as_str().to_string(),
                    fields
                        .iter()
                        .map(|kv| {
                            (
                                kv.0.as_str().to_string(),
                                Self::from_const_archived(&kv.1, word_bytes, float_bytes),
                            )
                        })
                        .collect(),
                    word_bytes,
                    float_bytes,
                )
            }
            ArchivedConstValue::Enum {
                type_name,
                variant,
                discriminant,
                fields,
            } => {
                use alloc::string::ToString;
                let materialised: alloc::vec::Vec<Self> = fields
                    .iter()
                    .map(|c| Self::from_const_archived(c, word_bytes, float_bytes))
                    .collect();
                // A resolved discriminant lets the constant materialise
                // into the flat body that matches the baked access; an
                // unresolved one stays boxed (B28 P2).
                match discriminant.as_ref().map(|d| d.to_native()) {
                    Some(disc) => Self::enum_with_widths(
                        type_name.as_str().to_string(),
                        variant.as_str().to_string(),
                        disc,
                        materialised,
                        // Constants carry no per-type padding hint; a const
                        // enum materialises variant-sized and relies on
                        // padding-tolerant equality. Const composites that
                        // would nest an enum are not flat-folded (see the
                        // compiler's const path), so a variant-sized const
                        // enum is never inlined into a fixed parent slot.
                        0,
                        word_bytes,
                        float_bytes,
                    ),
                    None => Self::Enum(EnumBody::boxed(
                        type_name.as_str().to_string(),
                        variant.as_str().to_string(),
                        materialised,
                    )),
                }
            }
            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,
}

/// The specific cause of an [`Op::Trap`]. The compiler encodes the
/// kind in the trap instruction's operand, and the virtual machine
/// surfaces it through `VmError::Trap` so a host can categorize the
/// fault without parsing a message string. These are the compiler-
/// emitted traps for partial operations whose unhandled case has no
/// in-band result, as distinct from the data faults that already
/// have their own `VmError` variants such as division by zero and
/// out-of-bounds indexing.
///
/// B35 (Partial Operation Handling) introduced this kind in place of
/// the prior free-form trap message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrapKind {
    /// A newtype refinement predicate returned false at a
    /// construction site.
    RefinementFailed,
    /// No head of a multiheaded function matched the arguments.
    NoMatchingHead,
    /// No arm of a `match` expression matched the scrutinee. This is
    /// reachable only when every arm carries a `when` guard, since
    /// the type checker proves unguarded matches exhaustive.
    NoMatchingArm,
    /// No arm of a checked-arithmetic construct matched the outcome.
    /// Reachable only through guarded arms, defensive otherwise.
    CheckedArithNoArm,
    /// An enum-to-`Word` cast met a `Value::Enum` whose variant is
    /// outside the declared set. Reachable only through a host-
    /// constructed enum value.
    EnumVariantUnmapped,
    /// A checked division or modulo met a zero divisor that no
    /// `zero_divisor` arm handled. The virtual machine surfaces this
    /// as `VmError::DivisionByZero`, the same error a plain division
    /// by zero produces.
    ZeroDivisor,
    /// A debug `assert` whose condition evaluated to false. Emitted
    /// only by debug builds (B29); release builds compile the assert
    /// out entirely.
    AssertionFailed,
}

impl TrapKind {
    /// The `u16` code carried in the [`Op::Trap`] operand.
    pub fn code(self) -> u16 {
        match self {
            TrapKind::RefinementFailed => 0,
            TrapKind::NoMatchingHead => 1,
            TrapKind::NoMatchingArm => 2,
            TrapKind::CheckedArithNoArm => 3,
            TrapKind::EnumVariantUnmapped => 4,
            TrapKind::ZeroDivisor => 5,
            TrapKind::AssertionFailed => 6,
        }
    }

    /// Decode a trap kind from an [`Op::Trap`] operand. Returns
    /// `None` for an unrecognized code, which indicates malformed
    /// bytecode.
    pub fn from_code(code: u16) -> Option<TrapKind> {
        match code {
            0 => Some(TrapKind::RefinementFailed),
            1 => Some(TrapKind::NoMatchingHead),
            2 => Some(TrapKind::NoMatchingArm),
            3 => Some(TrapKind::CheckedArithNoArm),
            4 => Some(TrapKind::EnumVariantUnmapped),
            5 => Some(TrapKind::ZeroDivisor),
            6 => Some(TrapKind::AssertionFailed),
            _ => None,
        }
    }
}

/// Baked operand of [`Op::GetTupleField`] (B28 P2).
///
/// The compiler resolves the access at compile time from the
/// ephemeral layout and bakes one of two forms. `Flat` reads the
/// field directly from the composite's byte buffer at `offset` as
/// `kind`, which is the flat representation a transitively-scalar
/// tuple uses. `Boxed` indexes the pre-B28 `Vec` body positionally
/// and is the fallback for a tuple that still carries a reference
/// field or a not-yet-migrated nested composite. The two forms agree
/// with the construction handler by static type, so a given tuple
/// type is always one or the other; the access handler dispatches on
/// the runtime body and faults on a form mismatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TupleField {
    /// Flat read at a compiler-baked byte `offset`, interpreting the
    /// bytes as `kind`. The offset is packed little-endian, the same
    /// layout the construction handler writes.
    Flat {
        /// Byte offset of the field within the composite body.
        offset: u16,
        /// Fixed-size scalar kind to read at the offset.
        kind: crate::value_layout::ScalarKind,
    },
    /// Flat read of a nested composite field: extract `size` bytes at
    /// `offset` from the parent body and re-wrap them as `variant`
    /// (B28 P2 nested inlining). The byte range is a complete child
    /// flat-composite body; the access handler wraps it in a fresh
    /// `Value` of the matching composite kind.
    FlatNested {
        /// Byte offset of the nested composite within the parent body.
        offset: u16,
        /// Byte length of the nested composite body.
        size: u16,
        /// Composite variant to re-wrap the extracted bytes as.
        variant: crate::value_layout::CompositeKind,
    },
    /// Positional index into the boxed `Vec` body (pre-B28 form).
    Boxed {
        /// Zero-based element index.
        index: u8,
    },
}

/// Baked operand of [`Op::GetField`] for struct field access (B28 P2).
///
/// Mirrors [`TupleField`] (a tuple is an anonymous struct), but the boxed
/// form carries the field-name constant-pool index rather than a
/// positional index, because the pre-B28 boxed struct body looks fields up
/// by name. The flat form reads at the compiler-baked byte offset; a struct
/// type is one form or the other by static type, and the access handler
/// dispatches on the runtime body and faults on a form mismatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructField {
    /// Flat read at a compiler-baked byte `offset`, interpreting the bytes
    /// as `kind`. The offset is packed little-endian, the same layout the
    /// construction handler writes.
    Flat {
        /// Byte offset of the field within the composite body.
        offset: u16,
        /// Fixed-size scalar kind to read at the offset.
        kind: crate::value_layout::ScalarKind,
    },
    /// Flat read of a nested composite field: extract `size` bytes at
    /// `offset` from the parent body and re-wrap them as `variant`
    /// (B28 P2 nested inlining).
    FlatNested {
        /// Byte offset of the nested composite within the parent body.
        offset: u16,
        /// Byte length of the nested composite body.
        size: u16,
        /// Composite variant to re-wrap the extracted bytes as.
        variant: crate::value_layout::CompositeKind,
    },
    /// Constant-pool index of the field name, looked up in the boxed body
    /// (pre-B28 form).
    Boxed {
        /// Field-name constant-pool index.
        name_const: u16,
    },
}

/// Baked operand of [`Op::GetEnumField`] for enum-payload access (B28 P2).
///
/// An enum payload field is positional (like a tuple element), so the boxed
/// form carries the index. The flat form carries the byte `offset` within
/// the flat body (already including the leading discriminant word) and the
/// field `kind`. The compiler bakes the form per variant; the access
/// handler dispatches on the runtime body and faults on a form mismatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnumField {
    /// Flat read at a compiler-baked byte `offset` (past the discriminant
    /// word), interpreting the bytes as `kind`.
    Flat {
        /// Byte offset of the payload field within the flat enum body.
        offset: u16,
        /// Fixed-size scalar kind to read at the offset.
        kind: crate::value_layout::ScalarKind,
    },
    /// Flat read of a nested composite payload field: extract `size`
    /// bytes at `offset` (past the discriminant word) from the flat enum
    /// body and re-wrap them as `variant` (B28 P2 nested inlining).
    FlatNested {
        /// Byte offset of the nested composite within the flat enum body.
        offset: u16,
        /// Byte length of the nested composite body.
        size: u16,
        /// Composite variant to re-wrap the extracted bytes as.
        variant: crate::value_layout::CompositeKind,
    },
    /// Positional index into the boxed payload (pre-B28 form).
    Boxed {
        /// Zero-based payload-field index.
        index: u8,
    },
}

/// Baked operand of [`Op::GetIndex`] (B28 P2).
///
/// An array is homogeneous, so unlike a tuple field the element offset
/// is not a compile-time constant; it is `index * element_size`,
/// computed at run time from the index on the stack. The baked operand
/// therefore carries only the element `kind`, from which the element
/// size follows at the runtime's scalar widths. `Flat` reads the
/// element directly from the array's flat byte body; `Boxed` indexes
/// the pre-B28 `Vec` body. The two forms agree with the construction
/// handler by static type, and the access handler dispatches on the
/// runtime body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrayElem {
    /// Flat read at `index * element_size`, interpreting the element
    /// bytes as `kind`. The element size is `kind.size_in_bytes` at the
    /// module-declared scalar widths, the same widths the construction
    /// handler packs against.
    Flat {
        /// Fixed-size scalar kind of each element.
        kind: crate::value_layout::ScalarKind,
    },
    /// Flat read of a nested composite element: each element occupies
    /// `size` bytes, so the element offset is `index * size`. Extract the
    /// element's bytes and re-wrap them as `variant` (B28 P2 nested
    /// inlining).
    FlatNested {
        /// Byte length of each nested composite element.
        size: u16,
        /// Composite variant to re-wrap the extracted bytes as.
        variant: crate::value_layout::CompositeKind,
    },
    /// Positional index into the boxed `Vec` body (pre-B28 form).
    Boxed,
}

/// Baked operand of [`Op::NewComposite`] (B28 P4).
///
/// One operand for all four composite kinds. The `Flat` form carries the
/// composite [`crate::value_layout::CompositeKind`], the `count` of values
/// to pop and pack, and the explicit `byte_size` to allocate on the arena
/// top head, which the worst-case-memory-usage verifier sums (conceptually
/// `ALLOCATEBYTES`). For a flat enum the first packed value is the
/// discriminant word, so `count` includes it. The `Boxed` form keeps the
/// boxed body for a reference-bearing field or `Option`; `meta` indexes the
/// chunk's boxed-composite metadata (a struct template, or an enum
/// type-and-variant pair) and is unused for a boxed tuple or array. The
/// boxed form is removed at P3 when reference fields become handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NewCompositeOperand {
    /// Allocate `byte_size` bytes, pack `count` popped values, wrap as
    /// `kind`.
    Flat {
        /// Which composite value variant to wrap the packed body as.
        kind: crate::value_layout::CompositeKind,
        /// Number of values to pop and pack (an enum's leading
        /// discriminant counts as one).
        count: u16,
        /// Bytes to allocate; the explicit allocation the WCMU pass sums.
        byte_size: u16,
    },
    /// Build the boxed body: pop `count` values; `meta` indexes the boxed
    /// metadata (struct template or enum type-and-variant).
    Boxed {
        /// Which composite value variant to build.
        kind: crate::value_layout::CompositeKind,
        /// Number of values to pop.
        count: u16,
        /// Index into the chunk's boxed-composite metadata.
        meta: u16,
    },
}

impl NewCompositeOperand {
    /// The composite kind this operand builds.
    pub fn kind(&self) -> crate::value_layout::CompositeKind {
        match self {
            Self::Flat { kind, .. } | Self::Boxed { kind, .. } => *kind,
        }
    }

    /// The number of operand-stack values the construction pops.
    pub fn count(&self) -> u16 {
        match self {
            Self::Flat { count, .. } | Self::Boxed { count, .. } => *count,
        }
    }

    /// The explicit flat allocation byte size, or zero for the boxed form
    /// (B28 P4). This is the value the worst-case-memory-usage verifier
    /// adds to the arena top-head bound for the construction.
    pub fn alloc_bytes(&self) -> u32 {
        match self {
            Self::Flat { byte_size, .. } => *byte_size as u32,
            Self::Boxed { .. } => 0,
        }
    }
}

/// 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 a value and store it into a data-segment slot. The runtime dispatches
    /// on the value. A scalar is stored inline in the slot. A private slot whose
    /// value is a flat composite copies its body into the persistent composite
    /// pool at the offset the module's private-composite layout table records
    /// for the slot and stores a region-aware handle that survives RESET in
    /// place (B28 P3 item 5, item 3a), so the body lives at a static,
    /// inspectable `.data`-style address rather than on the global heap. The
    /// pool offset comes from that module table rather than a baked operand, so
    /// no dedicated composite-write opcode is required.
    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 a composite of any kind from the top values (B28 P4). The
    /// single construction instruction that consolidates `NewStruct`,
    /// `NewTuple`, `NewArray`, and `NewEnum`: a tuple is an anonymous
    /// struct, an array a homogeneous struct, and a flat enum a struct
    /// whose first packed value is the discriminant word. The flat form
    /// carries the explicit allocation byte size the worst-case-memory-usage
    /// verifier sums (conceptually `ALLOCATEBYTES`); the boxed form (a
    /// reference-bearing field, or `Option`) carries the metadata index.
    NewComposite(NewCompositeOperand),

    /// Pop struct, push field value. The baked [`StructField`] operand
    /// selects a flat read at a compiler-baked byte offset or a by-name
    /// lookup in the boxed body (B28 P2).
    GetField(StructField),
    /// Pop index (Int), pop array, push element. The baked
    /// [`ArrayElem`] operand selects a flat read at `index * size` or a
    /// positional index into the boxed body (B28 P2).
    GetIndex(ArrayElem),
    /// Pop tuple, push element. The baked [`TupleField`] operand
    /// selects a flat read at an offset or a positional index into the
    /// boxed body (B28 P2).
    GetTupleField(TupleField),
    /// Pop enum, push payload field. The baked [`EnumField`] operand
    /// selects a flat read at a compiler-baked byte offset (past the
    /// discriminant word) or a positional index into the boxed body
    /// (B28 P2).
    GetEnumField(EnumField),
    /// Pop composite value, push its length as Int.
    Len,

    /// Peek at TOS: push true if matching enum type and variant, false
    /// otherwise. Operands are the enum-name and variant-name constant-pool
    /// indices and the variant discriminant constant index. The boxed body
    /// compares the variant name; the flat body compares the leading
    /// discriminant word to the constant (B28 P2).
    IsEnum(u16, 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 multiplication parameterized by a Q-format
    /// fraction-bit count (B35 P3d-iii). The operand is `0` for
    /// integer multiplication and greater than zero for `Fixed`
    /// multiplication, where the `i128` product is arithmetic-shifted
    /// right by that many bits before the range check, so `0`
    /// fraction bits is exactly integer multiply. For integer
    /// operands the true product is computed in `i128` and the high
    /// half is the load-bearing value for big-number multiplication;
    /// for `Fixed` operands the shifted result is a single word and
    /// the high slot is unused. Same stack effect as `CheckedAdd`.
    CheckedMul(u8),
    /// 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 division parameterized by a Q-format
    /// fraction-bit count (B35 P3d-iii). The operand is `0` for
    /// integer division and greater than zero for `Fixed` division,
    /// where the dividend is left-shifted by that many bits in the
    /// `i128` domain before dividing, so `0` fraction bits is exactly
    /// integer divide. A zero divisor reifies as flag `3`
    /// (zero_divisor) carrying the numerator; an unhandled zero
    /// divisor surfaces as `VmError::DivisionByZero`. For integer
    /// operands the only overflow case is `i64::MIN / -1`; for `Fixed`
    /// operands an out-of-range quotient wraps the single-word result.
    /// Same stack shape as the other `Op::Checked*` variants.
    CheckedDiv(u8),
    /// 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 real
/// `size_of::<Value>()` of the bundled 64-bit runtime.
///
/// This is bound to the actual `core::mem::size_of::<GenericValue<i64,
/// f64>>()` rather than a hand-maintained literal, so it can never drift
/// from the runtime representation (a prior literal of 32 understated the
/// real 72-byte value, which under-reported every WCMU figure derived from
/// it). It auto-tracks any change to the value layout, including the B28
/// flat-model shrink that reduced the value to 40 bytes.
///
/// **Soundness as a nominal figure.** The compiler bakes WCMU figures into
/// representation-independent bytecode that may also run on a narrow
/// `GenericVm<W, A, F>` whose slot is smaller, so this bundled-runtime size
/// is a conservative upper bound for those narrower runtimes (their
/// `GenericValue` is no larger, because the dominant `FlatComposite` body
/// is not parameterised by the scalar widths). The binding admission check
/// in [`crate::vm::GenericVm::new`] still uses each runtime's own
/// `size_of::<GenericValue<W, F>>()`, so the per-runtime bound is exact;
/// this constant governs the compile-time advisory header and the nominal
/// cost model. Future work under B10 may parameterise it by target through
/// a [`CostModel`].
pub const VALUE_SLOT_SIZE_BYTES: u32 = core::mem::size_of::<Value>() as u32;

/// 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,

    /// Extra WCET cycles charged per text byte for an O(length) string
    /// operation (#49). A text comparison (`Op::CmpEq`/`Op::CmpNe`),
    /// concatenation (`Op::Add` on text), and `Op::Len` on text run in time
    /// proportional to the operand length, which `op_cycles` does not capture
    /// because the flat per-opcode table is length-independent. The verifier's
    /// WCET pass multiplies this by the statically-bounded operand length (the
    /// shorter operand for a comparison, the sum for a concatenation) and adds
    /// it to the flat cost; a text operation whose length cannot be statically
    /// bounded is rejected as non-boundable. The nominal value is one cycle per
    /// byte, the data-movement scale; a measured cost model may override it, and
    /// it is not yet separately calibrated by `keleusma-bench`.
    pub text_byte_cycles: 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 {
            // NewComposite carries its exact flat allocation size in the
            // operand (B28 P4), so the worst-case-memory-usage bound is the
            // precise byte count rather than a `count * VALUE_SLOT` estimate.
            // The boxed form reports zero flat bytes (its body is the heap
            // `Vec`, accounted separately).
            Op::NewComposite(op) => OpCost::Fixed(op.alloc_bytes()),
            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,
    // One cycle per text byte, the data-movement scale (#49).
    text_byte_cycles: 1,
};

/// 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::NewComposite(_) => 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::NewComposite(_) => 1,

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

            // `IsEnum`/`IsStruct` peek the scrutinee (no pop) and push a Bool,
            // so they grow the operand stack by one slot. Modelling this as `0`
            // under-counted the worst-case operand peak by one relative to the
            // depth pass (`op_depth_effect` net +1) and the typed pass, which is
            // the number the WCMU bound checks against arena capacity.
            Op::IsEnum(_, _, _) | Op::IsStruct(_) => 1,

            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,
            // A native call pushes one result, or two slots
            // `(code, flag)` when the error-reify flag (high bit of
            // the argument-count byte, B35 P7) is set.
            Op::CallVerifiedNative(_, n) | Op::CallExternalNative(_, n) => {
                if n & 0x80 != 0 {
                    2
                } else {
                    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,

            // NewComposite pops `count` values (an enum's leading
            // discriminant counts as one) (B28 P4).
            Op::NewComposite(c) => c.count() 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,
            // Pop the argument count; the high bit is the error-reify
            // flag (B35 P7), not part of the count.
            Op::CallVerifiedNative(_, n) | Op::CallExternalNative(_, n) => (*n & 0x7F) 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>,
}

/// One variant's name and discriminant within an [`EnumLayout`].
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct EnumVariantDisc {
    /// Variant name.
    pub name: String,
    /// Variant discriminant (the flat body's leading word).
    pub disc: i64,
}

/// Module-level layout descriptor for one enum type (B37 / audit finding 25
/// follow-up).
///
/// Carries the type information the runtime needs to make an enum's flat body
/// *type-driven* rather than caller-asserted: the discriminant for each
/// variant and the padded-body payload size at the module's widths. The VM
/// consults it when flattening a boxed enum value returned by an unsignatured
/// native, correcting the discriminant and padding hints that the arena-less
/// [`EnumBody::boxed`] constructor cannot supply, so the flat body matches the
/// compiler's baked flat access exactly (the way a script-constructed value or
/// a signatured native already does). Only uniformly-flat enums, which the
/// compiler flattens, need the padding; a non-flat enum stays boxed and is
/// matched by name.
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct EnumLayout {
    /// Enum type name.
    pub type_name: String,
    /// Each variant's name and discriminant, in declaration order.
    pub variants: Vec<EnumVariantDisc>,
    /// Largest-variant payload size in bytes at the module's widths, the
    /// `min_payload` padding hint for a uniformly-flat enum's fixed body size
    /// (`word_bytes + min_payload`); `0` for a non-flat enum, which is not
    /// flattened.
    pub min_payload: u32,
}

/// Flat-shape descriptor for one value at a chunk's signature boundary
/// (a parameter, the resume value, or the return), consumed by the typed
/// operand-stack verifier pass to seed the abstract stack where the op stream
/// alone cannot determine a value's shape (A.2.1 Phase 2b). The `kind` fields
/// carry the stable [`crate::value_layout::ScalarKind::to_tag`] and
/// [`crate::value_layout::CompositeKind::to_tag`] codes rather than the layout
/// enums directly, so the wire encoding does not couple those enums to rkyv.
/// A [`WireShape::Top`] entry is the lattice top and reproduces the unseeded
/// Phase 1 behaviour (the pass defers shape-dependent checks).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub enum WireShape {
    /// Shape not statically known; the pass defers shape checks.
    Top,
    /// A fixed-size scalar. `kind` is a [`crate::value_layout::ScalarKind`] tag.
    Scalar {
        /// `ScalarKind::to_tag` code for the scalar's kind.
        kind: u8,
    },
    /// A flat composite body of `size` bytes at the module's widths. `kind` is
    /// a [`crate::value_layout::CompositeKind`] tag.
    Flat {
        /// `CompositeKind::to_tag` code for the composite variant.
        kind: u8,
        /// The body's byte length at the module's declared widths.
        size: u32,
    },
}

/// Per-chunk signature descriptor for the typed operand-stack verifier pass
/// (A.2.1 Phase 2b). Carried in a module-level table parallel to
/// [`Module::chunks`] so a `Call` can seed its result and check its arguments
/// against the callee's boundary. Additive on the wire (mirrored in the
/// auxiliary body alongside [`Module::enum_layouts`]); an absent table entry
/// or an all-[`WireShape::Top`] signature reproduces the unseeded Phase 1
/// behaviour. Only the signature boundary is described; non-parameter locals
/// are seeded as `Top` and refined by the pass (a later phase may narrow
/// them).
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct ChunkSignature {
    /// Flat shape of each parameter, in declaration order.
    pub params: Vec<WireShape>,
    /// Flat shape of the return value.
    pub ret: WireShape,
    /// Flat shape a `Yield`/resume pushes. A Stream chunk resumes with its
    /// single parameter's shape; other chunks record `Top`.
    pub resume: WireShape,
}

impl Default for ChunkSignature {
    fn default() -> Self {
        ChunkSignature {
            params: Vec::new(),
            ret: WireShape::Top,
            resume: WireShape::Top,
        }
    }
}

/// 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 live in the borrowed
    /// host-owned buffer and are read and written through
    /// `Vm::get_shared`/`Vm::set_shared` (B28 item 2); private slots
    /// live in the arena and are script-only. 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. Lives in the borrowed host buffer;
    /// `Vm::get_shared`/`Vm::set_shared` read and write it (B28 item 2).
    Shared,
    /// Script-only slot. Lives in the arena; no host accessor.
    Private,
}

/// Per-shared-slot byte layout in the borrowed host buffer (B28 item 2
/// shared-data re-architecture).
///
/// One entry per shared slot index, in the same order as the shared prefix of
/// [`DataLayout::slots`]. An array field expands to one entry per element slot,
/// so `Op::GetDataIndexed` resolves an element slot and the runtime reads its
/// entry. For a shared slot the runtime reads or writes the host buffer at
/// `offset` according to `kind`: a `crate::value_layout::ScalarKind::to_tag`
/// for a scalar slot, or, when the [`SHARED_SLOT_COMPOSITE_FLAG`] high bit is
/// set, a `CompositeKind::to_tag` in the low bits for a flat composite slot
/// whose body is `len` bytes. The instruction set is unchanged; this table is
/// how the existing
/// `GetData`/`SetData` reach the buffer without a new opcode, the rad-hard
/// minimal-ISA choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub struct SharedSlotLayout {
    /// Byte offset of this slot within the host buffer.
    pub offset: u16,
    /// Slot kind. When the [`SHARED_SLOT_COMPOSITE_FLAG`] high bit is clear,
    /// this is a `crate::value_layout::ScalarKind::to_tag` (`0..=7`) for a
    /// scalar slot. When the flag is set, the low seven bits are a
    /// `crate::value_layout::CompositeKind::to_tag` so the runtime re-wraps a
    /// copied-out shared composite as the correct `Tuple`/`Array`/`Struct`/
    /// `Enum`, which the kind-sensitive flat access ops require.
    pub kind: u8,
    /// Flat composite body length in bytes for a composite slot; `0` for a
    /// scalar slot.
    pub len: u16,
}

/// High bit of [`SharedSlotLayout::kind`] marking a flat composite slot. When
/// set, the low seven bits carry the composite's `CompositeKind::to_tag`
/// (`0..=3`); when clear, `kind` is a `ScalarKind::to_tag` (`0..=7`). The two
/// scalar/composite tag spaces overlap, so this flag is the discriminator.
pub const SHARED_SLOT_COMPOSITE_FLAG: u8 = 0x80;

/// Persistent-pool placement of one private composite data slot (B28 item 2
/// step 6A).
///
/// One entry per private slot that holds a flat composite body, single
/// composite fields and every element slot of an array-of-composite field
/// alike. The `offset` is the body's byte offset within the persistent
/// composite pool that follows the private-slot `Value` array in the arena
/// persistent region. At a flat-composite private write the runtime copies the
/// body into that fixed location and stores a region-aware handle that survives
/// RESET in place, so no private composite write needs a global-heap owned
/// body. This is the linker-style fixed-address placement of program state, the
/// 6502/NES and real-time control-loop model: every composite slot, including
/// array elements, has a statically baked address. Entries are sorted ascending
/// by `slot` so the runtime resolves a slot by binary search.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
pub struct PrivateCompositeSlot {
    /// Unified data-slot index (shared slots precede private slots).
    pub slot: u16,
    /// Byte offset of this slot's flat composite body within the persistent
    /// composite pool. A `u32` rather than a `u16` so the pool is not bounded
    /// to 64 KB; the access ops carry no offset, the runtime reads it here.
    pub offset: u32,
}

/// 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>,
    /// Per-shared-slot byte layout in the host buffer, one entry per shared
    /// slot in declaration order (B28 item 2). Empty when there are no shared
    /// slots; the private slots that follow the shared prefix carry no entries.
    pub shared_layout: Vec<SharedSlotLayout>,
    /// Persistent-pool placement of each private slot that holds a flat
    /// composite body, single composite fields and array-of-composite element
    /// slots alike (B28 item 2 step 6A). Sorted ascending by slot. Empty for a
    /// module with no private composite slots, so the wire form is unchanged
    /// for such modules. The runtime persists a flat-composite private write
    /// into the pool at the entry's offset; a private composite slot absent
    /// from this table is an empty (zero-byte) composite that needs no pool
    /// home.
    pub private_composite_layout: Vec<PrivateCompositeSlot>,
}

/// 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>,
    /// Optional strippable debug metadata (B29). `None` for a release
    /// build or a stripped artefact; `Some` when the chunk carries
    /// development aids such as source spans and variable names. The
    /// debug pool is held entirely here and never in `ops`, so the
    /// opcode sequence is byte-identical whether or not the pool is
    /// present. See [`crate::debug_meta`].
    pub debug_pool: Option<crate::debug_meta::DebugPool>,
}

/// 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,
    /// Worst-case bytes the runtime needs for its own ephemeral
    /// tracking structures per Stream-to-Reset slice, beyond the
    /// script-value WCMU (B28 P3 item 5, Phase C).
    ///
    /// These are the runtime's per-instance bookkeeping lists — the
    /// opaque registry, and (as the relocation lands) the backing of
    /// boxed composite bodies — which the runtime allocates inside the
    /// arena (the top ephemeral region) and pre-sizes once, as the
    /// first allocations after each RESET, rather than growing during
    /// an iteration. The runtime reads this value to pre-size those
    /// lists, and `auto_arena_capacity_for` adds it to the arena size.
    /// It is a runtime-only figure: native code never observes it, and
    /// it is distinct from the native-WCMU attestation path. `0` means
    /// the module needs no such tracking memory. Carried in the framing
    /// header's reserved word at offset 56.
    pub aux_arena_bytes: u32,
    /// Total bytes of persistent flat-composite body storage the private
    /// `.data` slots require in the arena's persistent region (B28 P3 item 5,
    /// item 3a). A private data slot holding a flat composite (struct, tuple,
    /// enum, or an array element thereof) stores its body in this persistent
    /// pool so it survives RESET in place, rather than on the global heap. The
    /// value is the sum over private composite slots of each slot's flat body
    /// size; `0` means no private slot holds a flat composite. The host adds
    /// this to the arena's persistent capacity (`required_persistent_capacity_for`
    /// accounts for it). Carried in the framing header's formerly-reserved word
    /// at offset 60; a `0` value leaves the header bytes identical to the prior
    /// reserved zero-fill, so existing bytecode without private composite slots
    /// is byte-unchanged.
    pub persistent_composite_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,
    /// Flat byte length of this module's shared data. Shared data is the
    /// host-owned buffer borrowed at each call, sized to this value and
    /// read or written through `Vm::get_shared`/`Vm::set_shared` (B28
    /// item 2). Survives RESET in the host's buffer. 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,
    /// Per-enum-type layout descriptors (B37 / audit finding 25 follow-up).
    /// Lets the VM make an enum's flat body type-driven: when flattening a
    /// boxed enum returned by an unsignatured native, it looks up the variant's
    /// true discriminant and the padded-body size here rather than trusting the
    /// arena-less constructor's hints. Empty for a module that declares no
    /// enums. See [`EnumLayout`].
    pub enum_layouts: Vec<EnumLayout>,
    /// Per-chunk signature descriptors for the typed operand-stack verifier
    /// pass (A.2.1 Phase 2b), parallel to [`Module::chunks`] by index. Seeds
    /// each chunk's parameters, resume, and return, and lets a `Call` seed its
    /// result and check its arguments against the callee. Empty (or shorter
    /// than `chunks`) reproduces the unseeded behaviour: a chunk without an
    /// entry is checked with an all-`Top` signature. See [`ChunkSignature`].
    pub signatures: Vec<ChunkSignature>,
    /// Return-value flat shape of each declared native, parallel to
    /// [`Module::native_names`] by index, so the typed verifier pass can seed a
    /// `CallVerifiedNative`/`CallExternalNative` result (A.2.1 native-result
    /// seeding). A native declared without a `use ... -> R` signature, or one
    /// whose return type does not resolve, records [`WireShape::Top`] and
    /// defers. Empty (or shorter than `native_names`) reproduces the unseeded
    /// behaviour.
    pub native_return_shapes: Vec<WireShape>,
}

/// 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::OpaqueRef(_) => Err("Opaque cannot be a compile-time constant"),
            Value::Tuple(items) => items
                .into_elements()
                .into_iter()
                .map(ConstValue::try_from_value)
                .collect::<Result<Vec<_>, _>>()
                .map(ConstValue::Tuple),
            Value::Array(items) => items
                .into_elements()
                .into_iter()
                .map(ConstValue::try_from_value)
                .collect::<Result<Vec<_>, _>>()
                .map(ConstValue::Array),
            Value::Struct(StructBody::Boxed(b)) => {
                let BoxedStruct { type_name, fields } = *b;
                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?,
                })
            }
            // A flat struct body carries no field names or values to
            // recover; compile-time constant folding runs before flat
            // construction, so a flat struct never reaches this path.
            Value::Struct(StructBody::Flat(_)) => {
                Err("a flat struct cannot be converted to a compile-time constant")
            }
            Value::Enum(EnumBody::Boxed(b)) => {
                // The `disc` re-flattening hint is intentionally not recovered
                // here: a script-built boxed enum carries the default-zero hint,
                // which would be wrong for a non-zero variant, so constant
                // folding stays variant-name-keyed and boxed (B28 P2).
                let BoxedEnum {
                    type_name,
                    variant,
                    fields,
                    ..
                } = *b;
                let cfields: Result<Vec<_>, _> =
                    fields.into_iter().map(ConstValue::try_from_value).collect();
                Ok(ConstValue::Enum {
                    type_name,
                    variant,
                    discriminant: None,
                    fields: cfields?,
                })
            }
            // A flat enum carries a discriminant and bytes, not the
            // variant name and values a constant needs; constant folding
            // runs before flat construction, so this is unreachable on a
            // valid path.
            Value::Enum(EnumBody::Flat(_)) => {
                Err("a flat enum cannot be converted to a compile-time constant")
            }
            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),
            // The bundled `Value` is `GenericValue<i64, f64>`, so the
            // scalar widths are eight bytes each. Routing through
            // `tuple_with_widths` keeps this constant tuple's body
            // representation identical to the runtime and archived
            // paths (B28 P2).
            ConstValue::Tuple(items) => Value::tuple_with_widths(
                items.into_iter().map(ConstValue::into_value).collect(),
                8,
                8,
            ),
            ConstValue::Array(items) => Value::array_with_widths(
                items.into_iter().map(ConstValue::into_value).collect(),
                8,
                8,
            ),
            ConstValue::Struct { type_name, fields } => Value::struct_with_widths(
                type_name,
                fields
                    .into_iter()
                    .map(|(n, v)| (n, v.into_value()))
                    .collect(),
                8,
                8,
            ),
            // A resolved discriminant materialises the flat body that
            // matches the baked access; otherwise boxed (B28 P2).
            ConstValue::Enum {
                type_name,
                variant,
                discriminant,
                fields,
            } => {
                let vals: Vec<Value> = fields.into_iter().map(ConstValue::into_value).collect();
                match discriminant {
                    Some(disc) => Value::enum_with_widths(type_name, variant, disc, vals, 0, 8, 8),
                    None => Value::Enum(EnumBody::boxed(type_name, variant, vals)),
                }
            }
            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,
        }
    }
}

/// Pack a transitively-scalar const composite's flat body bytes directly,
/// for the VM const-composite pool (B28 item 2 step 6B).
///
/// Returns `None` when the constant transitively carries a reference (a static
/// string or opaque) or an enum with an unresolved discriminant, which has no
/// flat body and keeps the boxed const path. The byte layout mirrors what the
/// arena packer ([`GenericValue::write_scalar_le`] via
/// [`GenericValue::pack_flat_in_arena`]) produces, so the compiler-baked access
/// offsets read a pooled const body correctly: each scalar little-endian at the
/// module scalar width, an enum as `[disc word][payload]`, and composites
/// concatenated with no inter-field padding (a const enum is variant-sized,
/// `min_payload` 0, which padding-tolerant flat-enum equality tolerates). This
/// replaces the former path of materialising a `Flat(Inline)` body and copying
/// its bytes out, now that the owned `Inline` form is gone.
pub(crate) fn const_flat_bytes(
    c: &ArchivedConstValue,
    word_bytes: usize,
    float_bytes: usize,
) -> Option<alloc::vec::Vec<u8>> {
    let mut buf = alloc::vec::Vec::new();
    const_flat_bytes_into(c, word_bytes, float_bytes, &mut buf)?;
    Some(buf)
}

fn const_flat_bytes_into(
    c: &ArchivedConstValue,
    word_bytes: usize,
    float_bytes: usize,
    buf: &mut alloc::vec::Vec<u8>,
) -> Option<()> {
    use ArchivedConstValue as A;
    match c {
        A::Unit => {}
        A::Bool(b) => buf.push(u8::from(*b)),
        A::Byte(b) => buf.push(*b),
        A::Int(i) | A::Fixed(i) => {
            let le = i.to_native().to_le_bytes();
            buf.extend_from_slice(&le[..word_bytes]);
        }
        #[cfg(feature = "floats")]
        A::Float(f) => {
            let v = f.to_native();
            match float_bytes {
                8 => buf.extend_from_slice(&v.to_le_bytes()),
                4 => buf.extend_from_slice(&(v as f32).to_le_bytes()),
                _ => return None,
            }
        }
        // A reference leaf has no position-independent flat body.
        A::StaticStr(_) => return None,
        // `Option::None` is the boxed `Option` representation (the access ops
        // bake the boxed form for the generic `Option`), so a const carrying it
        // is not flat-poolable.
        A::None => return None,
        A::Tuple(items) | A::Array(items) => {
            for it in items.iter() {
                const_flat_bytes_into(it, word_bytes, float_bytes, buf)?;
            }
        }
        A::Struct { fields, .. } => {
            for kv in fields.iter() {
                const_flat_bytes_into(&kv.1, word_bytes, float_bytes, buf)?;
            }
        }
        A::Enum {
            discriminant,
            fields,
            ..
        } => {
            // An unresolved discriminant has no flat body (it stays boxed).
            let disc = discriminant.as_ref()?.to_native();
            let le = disc.to_le_bytes();
            buf.extend_from_slice(&le[..word_bytes]);
            for f in fields.iter() {
                const_flat_bytes_into(f, word_bytes, float_bytes, buf)?;
            }
        }
    }
    Some(())
}

/// 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,
    word_bytes: usize,
    float_bytes: usize,
) -> GenericValue<W, F> {
    GenericValue::<W, F>::from_const_archived(archived, word_bytes, float_bytes)
}

/// 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::NewComposite(NewCompositeOperand::Flat {
                kind: crate::value_layout::CompositeKind::Array,
                count: 2,
                byte_size: 16,
            }),
            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,
            text_byte_cycles: 1,
        };
        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_is_operand_exact_not_slot_scaled() {
        // B28 P4: NewComposite carries its precise flat allocation size
        // in the operand, so the reported heap allocation is that byte
        // count verbatim and is independent of the model's
        // `value_slot_bytes`. Two models with different slot sizes must
        // agree on the composite's heap cost.
        let nominal = NOMINAL_COST_MODEL;
        let custom = CostModel {
            value_slot_bytes: VALUE_SLOT_SIZE_BYTES / 2,
            op_cycles: nominal_op_cycles,
            text_byte_cycles: 1,
        };
        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(),
            debug_pool: None,
        };
        let op = Op::NewComposite(NewCompositeOperand::Flat {
            kind: crate::value_layout::CompositeKind::Array,
            count: 4,
            byte_size: 32,
        });
        let nominal_bytes = nominal.heap_alloc_bytes(&op, &chunk);
        let custom_bytes = custom.heap_alloc_bytes(&op, &chunk);
        assert_eq!(nominal_bytes, 32);
        assert_eq!(custom_bytes, 32);
        assert_eq!(custom_bytes, 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,
            text_byte_cycles: 1,
        };
        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(),
            debug_pool: None,
        };
        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(),
            debug_pool: None,
        };
        let op = Op::NewComposite(NewCompositeOperand::Flat {
            kind: crate::value_layout::CompositeKind::Array,
            count: 3,
            byte_size: 24,
        });
        let cost = NOMINAL_COST_MODEL.heap_alloc_cost(&op, &chunk);
        assert!(matches!(cost, OpCost::Fixed(_)));
        assert_eq!(cost.evaluate(&OpCostContext::default()), 24);
    }

    #[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(),
            debug_pool: None,
        };
        assert_eq!(NOMINAL_COST_MODEL.heap_alloc_bytes(&Op::Add, &chunk), 0);
    }
}

#[cfg(test)]
mod flat_scalar_bridge_tests {
    use super::*;
    use crate::value_layout::ScalarKind;

    type V = Value; // GenericValue<i64, f64>

    // Bundled runtime widths.
    const W8: usize = 8;
    const F8: usize = 8;

    fn roundtrip(v: V, kind: ScalarKind, word_bytes: usize, float_bytes: usize, size: usize) -> V {
        let mut buf = alloc::vec![0u8; size];
        v.write_scalar_le(&mut buf, 0, word_bytes, float_bytes)
            .expect("write_scalar_le in roundtrip");
        V::read_scalar_le(&buf, 0, kind, word_bytes, float_bytes)
            .expect("read_scalar_le in roundtrip")
    }

    #[test]
    fn bool_byte_roundtrip() {
        assert_eq!(
            roundtrip(V::Bool(true), ScalarKind::Bool, W8, F8, 1),
            V::Bool(true)
        );
        assert_eq!(
            roundtrip(V::Bool(false), ScalarKind::Bool, W8, F8, 1),
            V::Bool(false)
        );
        assert_eq!(
            roundtrip(V::Byte(0xAB), ScalarKind::Byte, W8, F8, 1),
            V::Byte(0xAB)
        );
    }

    #[test]
    fn int_roundtrip_full_word() {
        for n in [0i64, 42, -5, i64::MAX, i64::MIN, -1] {
            assert_eq!(roundtrip(V::Int(n), ScalarKind::Int, W8, F8, 8), V::Int(n));
        }
    }

    #[test]
    fn fixed_roundtrip_returns_fixed_kind() {
        assert_eq!(
            roundtrip(V::Fixed(-123), ScalarKind::Fixed, W8, F8, 8),
            V::Fixed(-123)
        );
    }

    #[test]
    fn int_narrow_word_sign_extends() {
        // A 2-byte word: low 16 bits stored, sign-extended on read.
        assert_eq!(roundtrip(V::Int(-5), ScalarKind::Int, 2, F8, 2), V::Int(-5));
        assert_eq!(
            roundtrip(V::Int(1234), ScalarKind::Int, 2, F8, 2),
            V::Int(1234)
        );
        // -32768 is the most-negative 16-bit value.
        assert_eq!(
            roundtrip(V::Int(-32768), ScalarKind::Int, 2, F8, 2),
            V::Int(-32768)
        );
    }

    #[test]
    fn unit_writes_no_bytes() {
        let mut buf = [0xFFu8; 0];
        V::Unit
            .write_scalar_le(&mut buf, 0, W8, F8)
            .expect("write unit");
        assert_eq!(
            V::read_scalar_le(&buf, 0, ScalarKind::Unit, W8, F8).expect("read unit"),
            V::Unit
        );
    }

    #[test]
    fn read_write_scalar_le_are_total() {
        // Audit findings 11, 12, 20, 21: the flat scalar codec returns a clean
        // error instead of panicking on an out-of-range offset, a short
        // buffer, or a reference kind.
        use crate::bytecode::ScalarError;
        let buf = [0u8; 2];
        assert_eq!(
            V::read_scalar_le(&buf, 8, ScalarKind::Int, W8, F8),
            Err(ScalarError::OutOfBounds),
            "offset past the end"
        );
        assert_eq!(
            V::read_scalar_le(&buf, 0, ScalarKind::Int, W8, F8),
            Err(ScalarError::OutOfBounds),
            "an 8-byte word read overruns a 2-byte buffer"
        );
        assert_eq!(
            V::read_scalar_le(&buf, 0, ScalarKind::Text, W8, F8),
            Err(ScalarError::ReferenceKind),
            "a reference kind on the fixed-scalar path"
        );
        let mut dst = [0u8; 1];
        assert_eq!(
            V::Bool(true).write_scalar_le(&mut dst, 4, W8, F8),
            Err(ScalarError::OutOfBounds),
            "write past the end"
        );
    }

    #[cfg(feature = "floats")]
    #[test]
    fn float_roundtrip_f64_and_f32_width() {
        // f64 width is exact.
        assert_eq!(
            roundtrip(V::Float(0.1), ScalarKind::Float, W8, F8, 8),
            V::Float(0.1)
        );
        // 4-byte float width round-trips values exactly representable in f32.
        assert_eq!(
            roundtrip(V::Float(0.5), ScalarKind::Float, W8, 4, 4),
            V::Float(0.5)
        );
    }
}

#[cfg(test)]
mod materialise_kstrings_tests {
    use super::*;
    use crate::kstring::KString;

    type V = Value;

    fn make_arena() -> keleusma_arena::Arena {
        keleusma_arena::Arena::with_capacity(1024)
    }

    #[test]
    fn scalar_values_are_cloned_unchanged() {
        let arena = make_arena();
        assert_eq!(V::Int(42).materialise_kstrings(&arena), V::Int(42));
        assert_eq!(V::Bool(true).materialise_kstrings(&arena), V::Bool(true));
        assert_eq!(V::Unit.materialise_kstrings(&arena), V::Unit);
        assert_eq!(V::None.materialise_kstrings(&arena), V::None);
    }

    #[test]
    fn staticstr_is_cloned_unchanged() {
        let arena = make_arena();
        let v = V::StaticStr(alloc::string::String::from("hello"));
        assert_eq!(v.materialise_kstrings(&arena), v);
    }

    #[test]
    fn kstr_becomes_staticstr_with_arena_contents() {
        let arena = make_arena();
        let handle = KString::alloc(&arena, "the original bytes").expect("alloc");
        let v: V = V::KStr(handle);
        let materialised = v.materialise_kstrings(&arena);
        match materialised {
            V::StaticStr(s) => assert_eq!(s, "the original bytes"),
            other => panic!("expected StaticStr, got {:?}", other),
        }
    }

    #[test]
    fn tuple_walks_recursively() {
        // A `KStr` tuple element now flattens (B28 P3 item 5 C4), so build an
        // explicit boxed tuple to exercise the recursive `materialise_kstrings`
        // walk that still applies to boxed bodies (host-built tuples, `Option`).
        let arena = make_arena();
        let handle = KString::alloc(&arena, "inner").expect("alloc");
        let v = V::Tuple(TupleBody::boxed(alloc::vec![
            V::Int(1),
            V::KStr(handle),
            V::Bool(false),
        ]));
        let materialised = v.materialise_kstrings(&arena);
        match materialised {
            V::Tuple(items) => {
                let items = items.elements();
                assert_eq!(items.len(), 3);
                assert_eq!(items[0], V::Int(1));
                match &items[1] {
                    V::StaticStr(s) => assert_eq!(s, "inner"),
                    other => panic!("expected StaticStr inside tuple, got {:?}", other),
                }
                assert_eq!(items[2], V::Bool(false));
            }
            other => panic!("expected Tuple, got {:?}", other),
        }
    }

    #[test]
    fn enum_with_kstr_payload_walks_recursively() {
        let arena = make_arena();
        let handle = KString::alloc(&arena, "payload").expect("alloc");
        let v = V::Enum(EnumBody::boxed(
            alloc::string::String::from("Option"),
            alloc::string::String::from("Some"),
            alloc::vec![V::KStr(handle)],
        ));
        let materialised = v.materialise_kstrings(&arena);
        match materialised {
            V::Enum(EnumBody::Boxed(b)) => {
                assert_eq!(b.fields.len(), 1);
                match &b.fields[0] {
                    V::StaticStr(s) => assert_eq!(s, "payload"),
                    other => panic!("expected StaticStr inside enum, got {:?}", other),
                }
            }
            other => panic!("expected Enum, got {:?}", other),
        }
    }

    #[test]
    fn struct_walks_recursively() {
        // Built as an explicit boxed struct: `struct_value` now flattens a
        // struct whose fields are all flat (a `Text`/`KStr` field is a
        // two-word flat reference, B28 P3), and a flat struct's text field
        // is an arena reference reattached at access through the epoch
        // wrapper, not a `KStr` that `materialise_kstrings` converts. The
        // recursive walk over a boxed struct is what this test exercises.
        let arena = make_arena();
        let handle = KString::alloc(&arena, "field-value").expect("alloc");
        let v = V::Struct(StructBody::boxed(
            alloc::string::String::from("Point"),
            alloc::vec![
                (alloc::string::String::from("x"), V::Int(7)),
                (alloc::string::String::from("name"), V::KStr(handle)),
            ],
        ));
        let materialised = v.materialise_kstrings(&arena);
        match materialised {
            V::Struct(StructBody::Boxed(b)) => {
                assert_eq!(b.fields.len(), 2);
                assert_eq!(b.fields[0].1, V::Int(7));
                match &b.fields[1].1 {
                    V::StaticStr(s) => assert_eq!(s, "field-value"),
                    other => panic!("expected StaticStr inside struct, got {:?}", other),
                }
            }
            other => panic!("expected Struct, got {:?}", other),
        }
    }
}