rustyfi-lang 0.1.2

Abstract syntax tree, elaboration, evaluator, and primitives for SATySFi
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
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
//! The primitive registry. Shaped so the ~300 vminst instructions can be
//! ported one `prims!` line at a time; primitives are registered under their
//! real v0.0.6 names so later stdlib loading finds them.
//!
//! `document`, `+p` and `\emph` are not natives: they live in the
//! `stdja-mini` stdlib package
//! (`lib-rustyfi/dist/packages/stdja-mini.satyh`), loaded through
//! `rustyfi-loader` and typechecked/evaluated like any other `.satyh`
//! library. See that file's header comment for the primitives it is built
//! from.

use crate::eval::{available_fields, eval_error, DecoEntry, EvalError, Interp};
use crate::quoted::{BText, IText, MathElem};
use crate::value::{BaseEnv, DocumentValue, Env, TextInfo, Value};
use rustyfi_backend::char_script;
use rustyfi_backend::{
    break_into_lines, break_opportunities, chop_page, default_math_variant_char, fit_cell,
    graphics_bbox, linear_transform_graphics, linear_transform_path, measure_block,
    natural_metrics, path_bbox, place_block_at, placed_line_extent, shift_graphics, shift_path,
    Annot, AnnotAction, BreakKind, Cell, Closing, Color, Context, Dash, DecoId, DocExtras, DocInfo,
    FontKey, GraphicsElem, GraphicsFnId, HookId, HorzBox, HorzStringInfo, HyphenLang, ImageId,
    ImageResource, InlineMarkKind, Language, Length, ListMarkKind, MathCharClass, MathConstants,
    MathCorner, MathGlyph, MathKind, MathScriptLevel, NamedDest, OutlineEntry, Paddings, Page,
    PageGeometry, PaperSize, Path, PathSeg, Point, PrePath, PureHorzBox, Script, ScriptFont,
    Subpath, TabularBox, VertBox, VertVariantPolicy, FORCED_BREAK_PENALTY, MIN_FIRST_ASCENDER,
    NO_BREAK_PENALTY,
};
// Only the `load-pdf-image` importer builds these, and it is compiled out
// without the `pdf-image` feature.
#[cfg(feature = "pdf-image")]
use rustyfi_backend::{ImportedObjects, ObjRepr, PdfPageResource};
use rustyfi_syntax::RustyfiVersion;
use std::collections::BTreeMap;
#[cfg(feature = "pdf-image")]
use std::collections::BTreeSet;
use std::rc::Rc;
use std::sync::Arc;
// UAX #15 normalization / UAX #29 grapheme segmentation, for
// `normalize-string-to-nf{c,d}`/`split-grapheme-cluster`.
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;

/// Font keys agreed with this port's base-14 metrics provider.
const FONT_REGULAR: FontKey = FontKey(0);
const FONT_BOLD: FontKey = FontKey(1);
const FONT_OBLIQUE: FontKey = FontKey(2);

/// Which target version(s) a `PrimDef` row is registered under. Mirrors
/// `RustyfiVersion`'s two-variant shape today; `#[non_exhaustive]` for the
/// same reason `RustyfiVersion` is (a future third generation gets a new
/// arm here, not a redesign) — every `match` on this type needs a wildcard.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VersionSpan {
    /// Registered under every version this port implements. The default
    /// for every `prims!` line that omits a tag.
    Both,
    V0_0Only,
    V0_1Only,
}

impl VersionSpan {
    /// Whether a `PrimDef`/type-table row tagged `self` should be visible
    /// under `version`. `Both` always allows; `V0_0Only`/`V0_1Only` allow
    /// exactly their own version — no partial/future-version fallback (a
    /// third generation gets its own new `VersionSpan` arm, not silent
    /// inclusion under an existing one).
    pub fn allows(self, version: RustyfiVersion) -> bool {
        match (self, version) {
            (VersionSpan::Both, _) => true,
            (VersionSpan::V0_0Only, RustyfiVersion::V0_0) => true,
            (VersionSpan::V0_1Only, RustyfiVersion::V0_1) => true,
            _ => false,
        }
    }
}

pub struct PrimDef {
    pub name: &'static str,
    pub arity: usize,
    pub run: fn(&mut Interp, Vec<Value>) -> Result<Value, EvalError>,
    pub version: VersionSpan,
}

impl std::fmt::Debug for PrimDef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "PrimDef({}/{}, {:?})",
            self.name, self.arity, self.version
        )
    }
}

macro_rules! prims {
    ($($($tag:ident)? $name:literal ($arity:literal) => $f:path;)*) => {
        static PRIM_DEFS: &[PrimDef] = &[
            $(PrimDef {
                name: $name,
                arity: $arity,
                run: $f,
                version: prims!(@span $($tag)?),
            },)*
        ];
    };
    (@span) => { VersionSpan::Both };
    (@span v006) => { VersionSpan::V0_0Only };
    (@span v01) => { VersionSpan::V0_1Only };
}

/// Generate the `_v006`/`_v01` `PrimDef`-shaped pair for a primitive body
/// that needs to know the generation of the code that CALLED it.
///
/// The graphics-callback family (the primitives below, and the deco family
/// behind them) needs this: those bodies decide whether a callback returns `graphics
/// list` (0.0.6) or one `graphics` collection (0.1). Do NOT read
/// `interp.version` for that — it is a single whole-program field naming the
/// ENTRY document's generation, while a spliced 0.0.6 package calls these
/// primitives with its OWN convention.
///
/// Registering the body twice fixes it at compile time: `compile.rs`'s
/// `Ast::VersionScope` arm folds a primitive reference against the innermost
/// enclosing scope's version, so a call inside a 0.0.6 dependency picks the
/// `_v006` row and one in the 0.1 entry picks `_v01`, with nothing threaded
/// through the interpreter. The two rows share one type-table entry per
/// version (`prim_types::primitive_type_with_version`).
macro_rules! version_forked_prims {
    ($($v006:ident, $v01:ident => $body:path;)*) => {$(
        fn $v006(interp: &mut Interp, args: Vec<Value>) -> Result<Value, EvalError> {
            $body(interp, RustyfiVersion::V0_0, args)
        }
        fn $v01(interp: &mut Interp, args: Vec<Value>) -> Result<Value, EvalError> {
            $body(interp, RustyfiVersion::V0_1, args)
        }
    )*};
}

version_forked_prims! {
    prim_inline_graphics_v006, prim_inline_graphics_v01 => prim_inline_graphics;
    prim_inline_graphics_outer_v006, prim_inline_graphics_outer_v01
        => prim_inline_graphics_outer;
    prim_tabular_v006, prim_tabular_v01 => prim_tabular;
    prim_inline_frame_outer_v006, prim_inline_frame_outer_v01 => prim_inline_frame_outer;
    prim_inline_frame_inner_v006, prim_inline_frame_inner_v01 => prim_inline_frame_inner;
    prim_inline_frame_breakable_v006, prim_inline_frame_breakable_v01
        => prim_inline_frame_breakable;
    prim_block_frame_breakable_v006, prim_block_frame_breakable_v01
        => prim_block_frame_breakable;
}

prims! {
    "read-inline" (2) => prim_read_inline;
    "read-block" (2) => prim_read_block;
    // v0.0.6 (vminst.ml `BackendLineBreaking`): `bool -> bool -> context ->
    // inline-boxes -> block-boxes` — the two leading bools select whether
    // the paragraph's top/bottom edge is breakable across a page boundary.
    "line-break" (4) => prim_line_break;
    // `page -> (pbinfo -> page-content-scheme) -> (pbinfo -> page-parts) ->
    // block-boxes -> document` (vminst.ml:1024, `BackendPageBreaking`) —
    // v0.0.6's `page` ADT argument. 0.1's `page` ADT is gone; the v01 arm's
    // first argument becomes a plain `length * length` instead, same arity
    // and same `page_break_core` backing loop.
    v006 "page-break" (4) => prim_page_break_v006;
    v01  "page-break" (4) => prim_page_break_v01;

    // `page-break-multicolumn` (vminst.ml:1065
    // `BackendPageBreakingMultiColumn`) / `page-break-two-column`
    // (vminst.ml:1041 `BackendPageBreakingTwoColumn`): same v006/v01 fork
    // shape as `page-break` above.
    v006 "page-break-multicolumn" (7) => prim_page_break_multicolumn_v006;
    v01  "page-break-multicolumn" (7) => prim_page_break_multicolumn_v01;
    v006 "page-break-two-column" (6) => prim_page_break_two_column_v006;
    v01  "page-break-two-column" (6) => prim_page_break_two_column_v01;

    // ---- int arithmetic (vminst.ml: Plus/Minus/Times/Divides/Mod) --------
    "+" (2) => prim_int_add;
    "-" (2) => prim_int_sub;
    "*" (2) => prim_int_mul;
    "/" (2) => prim_int_div;
    "mod" (2) => prim_int_mod;

    // ---- int comparisons (vminst.ml: EqualTo/GreaterThan/LessThan; the "<>"/">="/"<=" trio comes from primitives.cppo.ml's `general_table`,
    // defined there as `LogicalNot (EqualTo ..)` / `LogicalNot (LessThan ..)`
    // / `LogicalNot (GreaterThan ..)`, typed `int -> int -> bool`) ----------
    "==" (2) => prim_int_eq;
    "<>" (2) => prim_int_ne;
    "<" (2) => prim_int_lt;
    ">" (2) => prim_int_gt;
    "<=" (2) => prim_int_le;
    ">=" (2) => prim_int_ge;

    // ---- 0.1 bitwise ops (dev-0-1-0 vminst.ml: PrimitiveBitShiftLeft :2495, PrimitiveBitShiftRight :2477, PrimitiveBand :2527,
    // PrimitiveBor :2541, PrimitiveBxor :2513, PrimitiveBnot :2556).
    // 0.0.6 upstream has none of these; `<<`/`>>` lex as ordinary
    // BinopLt/BinopGt opsymbol runs under BOTH versions (lexer.rs:634-653)
    // and simply stay unbound names under 0.0.6. --
    v01 "<<" (2) => prim_bit_shift_left;
    v01 ">>" (2) => prim_bit_shift_right;
    v01 "band" (2) => prim_band;
    v01 "bor" (2) => prim_bor;
    v01 "bxor" (2) => prim_bxor;
    v01 "bnot" (1) => prim_bnot;

    // ---- bool (vminst.ml: LogicalAnd/LogicalOr/LogicalNot) ----------------
    // NOTE: registered here as strict 2-arg primitives (both arguments are
    // evaluated before the call, since primitive application is call-by-
    // value). Real SATySFi short-circuits "&&"/"||" via elaboration
    // (build-in `if`); that desugaring lives in the (out-of-scope) elaborator.
    "&&" (2) => prim_bool_and;
    "||" (2) => prim_bool_or;
    "not" (1) => prim_bool_not;

    // ---- float (vminst.ml: FloatPlus/FloatMinus/FloatTimes/FloatDivides, PrimitiveFloat, PrimitiveRound) ---------------------------------------
    "+." (2) => prim_float_add;
    "-." (2) => prim_float_sub;
    "*." (2) => prim_float_mul;
    "/." (2) => prim_float_div;
    "float" (1) => prim_float_of_int;
    "round" (1) => prim_round;

    // ---- 0.1 float comparisons (saphe-split@b836d512 vminst.ml:2679-2740:
    // PrimitiveFloatGreaterThan/-LessThan/-GreaterThanOrEqualTo/
    // -LessThanOrEqualTo, named ">."/"<."/">=."/"<=."). Confirmed absent
    // from 0.0.6 upstream (0 hits in either its v0.0.6 tag or dev-0-1-0's
    // vminst.ml/primitives.cppo.ml) — genuinely v01-only, unlike "+."/"-."/
    // "*."/"/." above; float.satyg's `abs`/`max`/`min` need `>=.`/`<=.`.
    // All four lex as ordinary BinopGt/BinopLt opsymbol runs under both
    // versions (lexer.rs:634-653), same as the bitwise "<<"/">>" above.
    v01 ">." (2) => prim_float_gt;
    v01 "<." (2) => prim_float_lt;
    v01 ">=." (2) => prim_float_ge;
    v01 "<=." (2) => prim_float_le;

    // ---- length arithmetic (vminst.ml: LengthPlus/LengthMinus/LengthTimes/ LengthDivides/LengthLessThan/LengthGreaterThan) -----------------------
    "+'" (2) => prim_length_add;
    "-'" (2) => prim_length_sub;
    "*'" (2) => prim_length_scale;
    "/'" (2) => prim_length_div;
    "<'" (2) => prim_length_lt;
    ">'" (2) => prim_length_gt;

    // ---- string (vminst.ml: Concat, PrimitiveArabic, PrimitiveSame) -------
    "^" (2) => prim_string_concat;
    "arabic" (1) => prim_arabic;
    "string-same" (2) => prim_string_same;

    // ---- list cons ----------------------------------------------------------
    // Upstream makes `::` syntax (`UTListCons`/`ListCons`), not a primitive.
    // This port's elaborator flattens every binary operator into
    // `Apply(Apply(Var(op_text), lhs), rhs)` (see `elaborate.rs`'s
    // operator-precedence fold), so `::` needs an env-bound primitive like
    // `+`/`^`.
    "::" (2) => prim_list_cons;

    // ---- mutable-cell dereference (evaluator.cppo.ml `Dereference`) --------
    // Upstream's "!" *constructs* a `Dereference` AST node that a later pass
    // reduces (primitives.cppo.ml: `lambda1 (fun v1 -> Dereference(v1))`);
    // this port has no such two-step split, so "!" is an ordinary strict
    // primitive that dereferences directly — structural deviation only.
    "!" (1) => prim_deref;

    // ---- string, continued (vminst.ml: PrimitiveStringLength/StringSub/ StringExplode; low-priority additions verified against vminst.ml) ----
    "string-length" (1) => prim_string_length;
    "string-sub" (3) => prim_string_sub;
    "string-explode" (1) => prim_string_explode;
    "regexp-of-string" (1) => prim_regexp_of_string;
    "string-match" (2) => prim_string_match;
    "split-on-regexp" (2) => prim_split_on_regexp;

    // ---- text embedding (vminst.ml:1707 PrimitiveEmbed: string -> inline- text; the interp body wraps the string as a one-element quoted text) --
    "embed-string" (1) => prim_embed_string;

    // ---- context ops -----------------------------------------------------
    //
    // vminst.ml:1434 `PrimitiveSetFontSize`: `~% (tLN @-> tCTX @-> tCTX)`.
    "set-font-size" (2) => prim_set_font_size;
    // vminst.ml:1449 `PrimitiveGetFontSize`: `~% (tCTX @-> tLN)`.
    "get-font-size" (1) => prim_get_font_size;
    // vminst.ml:1633 `PrimitiveSetLeading`: `~% (tLN @-> tCTX @-> tCTX)`,
    // sets `ctx.leading` — the baseline-to-baseline distance, which is
    // exactly our existing `Context::leading` field. (There is *also* a
    // `set-min-gap-of-lines`, vminst.ml:1291-1292, which sets a *different*
    // field, `min_gap_of_lines` — the minimum extra gap between two lines'
    // bounding boxes, on top of `leading`. We don't model that separate
    // field, so `set-leading` is the one that matches "baseline distance"
    // and an existing Context field.)
    "set-leading" (2) => prim_set_leading;
    // vminst.ml:1396 `PrimitiveSetParagraphMargin`:
    // `~% (tLN @-> tLN @-> tCTX @-> tCTX)`. Sets the new `paragraph_top`/
    // `paragraph_bottom` fields (see context.rs); not wired into any
    // box-producing primitive yet (a future `+p` would consult them).
    "set-paragraph-margin" (3) => prim_set_paragraph_margin;
    // vminst.ml:1648 `PrimitiveGetTextWidth`: `~% (tCTX @-> tLN)`.
    "get-text-width" (1) => prim_get_text_width;
    // vminst.ml:1247 `PrimitiveGetInitialContext`:
    // `~% (tLN @-> tICMD tMATH @-> tCTX)` — a paragraph width and the
    // *default math command* (the handler used for bare `${...}` math
    // embedded directly in inline text). FAITHFUL: the second argument is
    // interned via `Interp::register_math_command` and installed as
    // `Context::math_command`, consulted by `read_inline`'s `EmbedMath` arm.
    "get-initial-context" (2) => prim_get_initial_context;
    // LOCAL, non-upstream primitive: `set-font-key : int -> context ->
    // context`, sets `Context::font` directly to `FontKey(n)`. v0.0.6 has no
    // primitive shaped like this at all — real font switching there goes
    // through `set-font : script -> (string * float * float) -> context ->
    // context` (choosing a font *by name* per script, vminst.ml's
    // `PrimitiveSetFont`), which is far richer than this port's
    // base-14-metrics-by-`FontKey` model can support. `set-font-key` is the
    // minimal faithful-enough stand-in the `stdja-mini` stdlib package
    // (lib-rustyfi/dist/packages/stdja-mini.satyh) needs to implement
    // `\emph`/`\bold` by switching to the oblique/bold base-14 face
    // (`FONT_OBLIQUE`/`FONT_BOLD` above) without inventing a whole font-name
    // resolution layer. Out-of-range keys are accepted as-is (there is no
    // registry to validate against yet); an unknown `FontKey` simply fails
    // later, when a font metrics lookup for it comes up empty.
    "set-font-key" (2) => prim_set_font_key;

    // ---- box combinators (vminst.ml `HorzConcat`/`VertConcat`/ `BackendVertSkip`/`BackendFixedEmpty`/`BackendOuterEmpty`) ----------
    //
    // vminst.ml:803 `HorzConcat`: `~% (tIB @-> tIB @-> tIB)`.
    "++" (2) => prim_inline_concat;
    // vminst.ml:818 `VertConcat`: `~% (tBB @-> tBB @-> tBB)`.
    "+++" (2) => prim_block_concat;
    // vminst.ml:1757 `BackendFixedEmpty`: `~% (tLN @-> tIB)` — a fixed-width
    // box with no stretch/shrink (`PureHorzBox::FixedEmpty`, hbox.rs).
    "inline-skip" (1) => prim_inline_skip;
    // vminst.ml:1771 `BackendOuterEmpty`: `~% (tLN @-> tLN @-> tLN @-> tIB)`,
    // params `(widnat, widshrink, widstretch)` in that order — exactly the
    // (natural, shrinkable, stretchable) field order `PureHorzBox::OuterEmpty`
    // already uses, so this is a direct wrap, no new box variant needed.
    "inline-glue" (3) => prim_inline_glue;
    // vminst.ml:1171 `BackendVertSkip`: `~% (tLN @-> tBB)`, builds
    // `VertFixedBreakable(len)` — our existing `VertBox::Skip(len)`.
    "block-skip" (1) => prim_block_skip;

    // ---- the reflow marker-box
    // constructors. No vminst.ml entry — these are NEW primitives (not an
    // upstream port), the minimal hook that is unavoidable since
    // list/emphasis structure is 100% interpreted `.satyh` with no existing
    // Rust interception point. Both take a plain `int` tag (there is no
    // surface syntax to pass a Rust enum literal from `.satyh` source) —
    // see `prim_list_mark`/`prim_inline_mark`'s doc comments for the exact
    // tag encoding. Registered for `Both` versions (harmless/unused under
    // 0.0.6 today; the 0.0.6 `itemize.satyh` may be wired to them later). ----
    "list-mark" (1) => prim_list_mark;
    "inline-mark" (1) => prim_inline_mark;

    // `|>` (reverse application) is NOT a primitive: it is elaborated
    // directly to `Apply(f, x)` (see `elaborate.rs`'s `climb`).

    // ---- float trig / log / exp / rounding (vminst.ml 2729-2880) ----------
    "sin" (1) => prim_sin;
    "asin" (1) => prim_asin;
    "cos" (1) => prim_cos;
    "acos" (1) => prim_acos;
    "tan" (1) => prim_tan;
    "atan" (1) => prim_atan;
    "atan2" (2) => prim_atan2;
    "log" (1) => prim_log;
    "exp" (1) => prim_exp;
    // vminst.ml:2865/2880 `PrimitiveCeil`/`PrimitiveFloor`: both `float ->
    // float` (NOT `int` — easy to mistype; contrast `round`, above, which
    // does return `int`).
    "ceil" (1) => prim_ceil;
    "floor" (1) => prim_floor;
    // vminst.ml:2319 `PrimitiveShowFloat`: `float -> string`, OCaml's
    // `string_of_float`.
    "show-float" (1) => prim_show_float;

    // ---- byte-indexed string ops (vminst.ml 2056-2196) ---------------------
    // vminst.ml:2159 `PrimitiveStringByteLength`: counts UTF-8 BYTES, unlike
    // `string-length`'s Unicode-scalar-value count above.
    "string-byte-length" (1) => prim_string_byte_length;
    // vminst.ml:2123 `PrimitiveStringSubBytes`: byte-indexed `string-sub`.
    "string-sub-bytes" (3) => prim_string_sub_bytes;
    // vminst.ml:2196 `PrimitiveStringUnexplode`: inverse of `string-explode`.
    "string-unexplode" (1) => prim_string_unexplode;

    // ---- 0.1 Unicode string prims (dev-0-1-0 vminst.ml :2050/:2066/:2082),
    // via the `unicode-normalization`/`unicode-segmentation` crates. --------
    v01 "normalize-string-to-nfc" (1) => prim_normalize_string_to_nfc;
    v01 "normalize-string-to-nfd" (1) => prim_normalize_string_to_nfd;
    v01 "split-grapheme-cluster" (1) => prim_split_grapheme_cluster;

    // ---- diagnostics (vminst.ml 2056, 3133) --------------------------------
    // vminst.ml:2056 `PrimitiveDisplayMessage`: `string -> unit`. Upstream
    // prints to stdout (`print_endline`); see `prim_display_message`'s doc
    // comment for why this port deliberately prints to stderr instead.
    "display-message" (1) => prim_display_message;
    // vminst.ml:3133 `AbortWithMessage`: `string -> 'a` — raises a dynamic
    // error carrying the message verbatim.
    "abort-with-message" (1) => prim_abort_with_message;
    // ---- images (raster images). Mirrors v0.0.6 vminstdef.yaml:540/:554. -
    "load-image"          (1) => prim_load_image;         // string -> image
    "use-image-by-width"  (2) => prim_use_image_by_width; // image -> length -> inline-boxes
    // `load-pdf-image : string -> int -> image` (v0.0.6 vminstdef.yaml:525;
    // dev-0-1-0 `PrimitiveLoadPdfImage` — same name/type/body across both
    // versions).
    "load-pdf-image" (2) => prim_load_pdf_image;
    // `read-file : string -> list string` (dev-0-1-0 vminst.ml :3073) —
    // REAL, `load-image`'s cwd-relative-path precedent
    // (`prim_load_image`'s doc comment above): job-directory resolution
    // isn't plumbed into `Interp` at all yet, so this resolves against the
    // process cwd instead of upstream's job directory — documented
    // deviation, see `prim_read_file`'s own doc comment.
    v01 "read-file" (1) => prim_read_file;
    // `register-document-information : document-information-dictionary ->
    // unit` (dev-0-1-0 vminst.ml :2978) — REAL:
    // stores into `Interp::doc_info` (last-write-wins), drained into
    // `DocExtras::doc_info`, emitted as the PDF `/Info` dictionary by both
    // writers.
    v01 "register-document-information" (1) => prim_register_document_information;
    // ==== graphics primitives ====
    // Paths, fill/stroke, and the `inline-graphics` on-page sink. Argument
    // order transcribed from `tools/gencode/vminst.ml`: `start-path` :713,
    // `line-to` :727, `terminate-path` :759, `close-with-line` :773,
    // `fill` :2398, `stroke` :2381, `inline-graphics` :1872.
    "start-path" (1) => prim_start_path;
    "line-to" (2) => prim_line_to;
    "terminate-path" (1) => prim_terminate_path;
    "close-with-line" (1) => prim_close_with_line;
    "fill" (2) => prim_fill;
    "stroke" (3) => prim_stroke;
    // These three take a graphics-producing CALLBACK whose result shape
    // forks (`graphics list` vs one `graphics` collection) — see
    // `version_forked_prims!`'s doc comment.
    v006 "inline-graphics" (4) => prim_inline_graphics_v006;
    v01  "inline-graphics" (4) => prim_inline_graphics_v01;
    // `tabular : (cell list) list -> (length list -> length list ->
    // graphics list) -> inline-boxes` (vminst.ml:539);
    v006 "tabular" (2) => prim_tabular_v006;
    v01  "tabular" (2) => prim_tabular_v01;
    // `inline-graphics-outer : length -> length -> (length -> point ->
    // graphics list) -> inline-boxes` (vminst.ml:1891
    // `BackendInlineGraphicsOuter`).
    v006 "inline-graphics-outer" (3) => prim_inline_graphics_outer_v006;
    v01  "inline-graphics-outer" (3) => prim_inline_graphics_outer_v01;
    // ---- gr.satyh prims — see tools/gencode/vminst.ml for exact
    // signatures: `bezier-to` :742, `close-with-bezier` :787, `shift-path`
    // :663, `linear-transform-path` :678, `shift-graphics` :2451,
    // `linear-transform-graphics` :2432, `get-graphics-bbox` :2466,
    // `get-path-bbox` :696, `dashed-stroke` :2414, `draw-text` :2363.
    "bezier-to" (4) => prim_bezier_to;
    "close-with-bezier" (3) => prim_close_with_bezier;
    "shift-path" (2) => prim_shift_path;
    "linear-transform-path" (5) => prim_linear_transform_path;
    "shift-graphics" (2) => prim_shift_graphics;
    "linear-transform-graphics" (5) => prim_linear_transform_graphics;
    // `get-graphics-bbox`: v0.0.6 = un-optioned pair (vminst.ml:2466); v0.1
    // wraps `option` (dev-0-1-0 vminst.ml:2301).
    v006 "get-graphics-bbox" (1) => prim_get_graphics_bbox_v006;
    v01  "get-graphics-bbox" (1) => prim_get_graphics_bbox_v01;
    "get-path-bbox" (1) => prim_get_path_bbox;
    "dashed-stroke" (4) => prim_dashed_stroke;
    "draw-text" (2) => prim_draw_text;
    // ---- 0.1 graphics-collection prims (dev-0-1-0 vminst.ml :3105/:3119).
    // `graphics` is a collection under 0.1 — these two build/wrap it; the 6
    // hidden callback-result retypes that make a `graphics`-producing
    // callback return ONE collection instead of `list graphics` live at
    // their existing (untagged `Both`) rows below, coerced per-version by
    // `coerce_graphics_result`.
    v01 "unite-graphics" (1) => prim_unite_graphics;
    v01 "clip-graphics-by-path" (2) => prim_clip_graphics_by_path;

    // ==== `pervasives.satyh` prims. Argument order transcribed from
    // `tools/gencode/vminst.ml`: `get-natural-metrics` :2020,
    // `inline-frame-outer` :1787, `set-manual-rising` :1661,
    // `script-guard` :1908, `discretionary` :1969. ====
    "get-natural-metrics" (1) => prim_get_natural_metrics;
    // A `deco`'s result shape forks the same way, and its closure fires
    // LONG after (a post-page-break pass), so the generation must be
    // captured here — see `version_forked_prims!`/`DecoEntry`.
    v006 "inline-frame-outer" (3) => prim_inline_frame_outer_v006;
    v01  "inline-frame-outer" (3) => prim_inline_frame_outer_v01;
    // vminst.ml:1807 `BackendInnerFrame`: same `tPADS @-> tDECO @-> tIB @->
    // tIB` as `inline-frame-outer`.
    v006 "inline-frame-inner" (3) => prim_inline_frame_inner_v006;
    v01  "inline-frame-inner" (3) => prim_inline_frame_inner_v01;
    "set-manual-rising" (2) => prim_set_manual_rising;
    "script-guard" (2) => prim_script_guard;
    "discretionary" (4) => prim_discretionary;

    // `get-axis-height` (vminst.ml:1739 `PrimitiveGetAxisHeight`) —
    // STAND-IN, see body; REMOVED in 0.1 (superseded by
    // `get-math-axis-height-ratio`).
    v006 "get-axis-height" (1) => prim_get_axis_height;

    // ==== page-break-hook callback seam + cross-reference fixpoint ====
    "hook-page-break" (1) => prim_hook_page_break;
    "hook-page-break-block" (1) => prim_hook_page_break_block;
    "register-cross-reference" (2) => prim_register_cross_reference;
    "get-cross-reference" (1) => prim_get_cross_reference;
    "probe-cross-reference" (1) => prim_probe_cross_reference;

    // ==== `annot.satyh`'s prim surface (link annotations + the frame/
    // script stand-ins it needs to type-check) ====
    "get-leftmost-script" (1) => prim_get_leftmost_script;
    "get-rightmost-script" (1) => prim_get_rightmost_script;
    v006 "inline-frame-breakable" (3) => prim_inline_frame_breakable_v006;
    v01  "inline-frame-breakable" (3) => prim_inline_frame_breakable_v01;
    "register-destination" (2) => prim_register_destination;
    "register-link-to-uri" (6) => prim_register_link_to_uri;
    "register-link-to-location" (6) => prim_register_link_to_location;

    // ==== the faithful `Value::Math` primitive layer `math.satyh` is built
    // out of. 19 fork into v006/v01 pairs (v006 = zero behavior change; v01
    // consumes/produces `Value::MathBoxes`); 5 more are REMOVED in 0.1
    // outright (v006-tagged, untouched bodies). ====
    v006 "math-char" (2) => prim_math_char_v006;
    v01  "math-char" (3) => prim_math_char_v01;
    v006 "math-big-char" (2) => prim_math_big_char_v006;
    v01  "math-big-char" (3) => prim_math_big_char_v01;
    v006 "math-char-with-kern" (4) => prim_math_char_with_kern_v006;
    v01  "math-char-with-kern" (5) => prim_math_char_with_kern_v01;
    v006 "math-big-char-with-kern" (4) => prim_math_big_char_with_kern_v006;
    v01  "math-big-char-with-kern" (5) => prim_math_big_char_with_kern_v01;
    v006 "math-concat" (2) => prim_math_concat_v006;
    v01  "math-concat" (2) => prim_math_concat_v01;
    v006 "math-group" (3) => prim_math_group_v006;
    v01  "math-group" (3) => prim_math_group_v01;
    v006 "math-sup" (2) => prim_math_sup_v006;
    v01  "math-sup" (3) => prim_math_sup_v01;
    v006 "math-sub" (2) => prim_math_sub_v006;
    v01  "math-sub" (3) => prim_math_sub_v01;
    v006 "math-frac" (2) => prim_math_frac_v006;
    v01  "math-frac" (3) => prim_math_frac_v01;
    v006 "math-radical" (2) => prim_math_radical_v006;
    v01  "math-radical" (3) => prim_math_radical_v01;
    v006 "math-lower" (2) => prim_math_lower_v006;
    v01  "math-lower" (3) => prim_math_lower_v01;
    v006 "math-upper" (2) => prim_math_upper_v006;
    v01  "math-upper" (3) => prim_math_upper_v01;
    // REMOVED in 0.1 outright — v006-tagged, untouched bodies.
    v006 "math-pull-in-scripts" (3) => prim_math_pull_in_scripts;
    v006 "math-color" (2) => prim_math_color;
    v006 "math-char-class" (2) => prim_math_char_class;
    v006 "math-variant-char" (2) => prim_math_variant_char;
    // ==== the `set-math-variant-char`/`get-left-math-class`/
    // `get-right-math-class` trio: no bundled `.satyh` consumer needed yet,
    // built on `Context::math_variant_char_map` + `VariantCharPending`.
    // Forked v006/v01. ====
    v006 "set-math-variant-char" (4) => prim_set_math_variant_char_v006;
    v01  "set-math-variant-char" (3) => prim_set_math_variant_char_v01;
    v006 "get-left-math-class" (2) => prim_get_left_math_class_v006;
    v01  "get-left-math-class" (1) => prim_get_left_math_class_v01;
    v006 "get-right-math-class" (2) => prim_get_right_math_class_v006;
    v01  "get-right-math-class" (1) => prim_get_right_math_class_v01;
    v006 "math-paren" (3) => prim_math_paren_v006;
    v01  "math-paren" (4) => prim_math_paren_v01;
    v006 "math-paren-with-middle" (4) => prim_math_paren_with_middle_v006;
    v01  "math-paren-with-middle" (5) => prim_math_paren_with_middle_v01;
    // REMOVED in 0.1 outright.
    v006 "text-in-math" (2) => prim_text_in_math;
    "convert-string-for-math" (3) => prim_convert_string_for_math;
    v006 "embed-math" (2) => prim_embed_math_v006;
    v01  "embed-math" (2) => prim_embed_math_v01;
    "set-math-command" (2) => prim_set_math_command;
    // `set-math-font` forks in its argument, not its effect: 0.0.6 takes the
    // math face's ABBREV (`string`), saphe-split takes the opaque `font`
    // handle (`tFONTKEY`). Both end at the same `Context::math_font`.
    v006 "set-math-font" (2) => prim_set_math_font_v006;
    v01  "set-math-font" (2) => prim_set_math_font_v01;
    // LOCAL, non-upstream, V0_1-only — the port's spelling for upstream's
    // internal `LoadSingleFont{path}` node; see `prim_load_single_font`.
    v01  "load-single-font" (1) => prim_load_single_font;
    v006 "space-between-maths" (3) => prim_space_between_maths_v006;
    v01  "space-between-maths" (3) => prim_space_between_maths_v01;
    // ==== NEW in 0.1 — `math-text`/`math-boxes` split + `read-math` + the
    // hidden `val math`-without-scripts wrapper prim. ====
    v01 "read-math" (2) => prim_read_math;
    v01 "stringify-math" (2) => prim_stringify_math;
    v01 "set-math-char" (4) => prim_set_math_char;
    v01 "set-math-char-class" (2) => prim_set_math_char_class;
    v01 "get-math-char-class" (1) => prim_get_math_char_class;
    v01 "embed-inline-to-math" (2) => prim_embed_inline_to_math;
    v01 "get-math-axis-height-ratio" (1) => prim_get_math_axis_height_ratio;
    v01 "%math-attach-scripts" (4) => prim_math_attach_scripts;

    // ==== hyphenation/unidata loader + setter stand-ins, V0_1-only
    // (genuinely absent from 0.0.6 upstream). FAITHFUL types
    // (`prim_types.rs`); ACCEPT-AND-RETURN bodies, not hard-error
    // stand-ins like `stringify-math` above — std-ja evaluates `val
    // unidata = load-unicode-char-database …` at module LOAD time, so an
    // erroring stand-in would break every consumer at load, not just at
    // use. ====
    v01 "load-hyphenation-dictionary" (1) => prim_load_hyphenation_dictionary;
    v01 "load-unicode-char-database"  (3) => prim_load_unicode_char_database;
    v01 "set-hyphenation-dictionary"  (2) => prim_set_hyphenation_dictionary;
    v01 "set-unicode-char-database"   (2) => prim_set_unicode_char_database;

    "raise-inline" (2) => prim_raise_inline;
    "embed-block-breakable" (2) => prim_embed_block_breakable;
    "unite-path" (2) => prim_unite_path;
    "set-min-gap-of-lines" (2) => prim_set_min_gap_of_lines;

    // ==== context-setter + box-combinator prims `code.satyh`/
    // `itemize.satyh` need. Argument order from `tools/gencode/vminst.ml`:
    // `set-text-color` :1603, `get-text-color` :1618, `set-hyphen-penalty`
    // :1692, `set-space-ratio` :1309, `split-into-lines` :2269,
    // `block-frame-breakable` :1090, `embed-block-top` :1145, `set-font`
    // :1463; `set-code-text-command`/`get-natural-length` have no
    // vminst.ml entry. ====
    "set-text-color" (2) => prim_set_text_color;
    "get-text-color" (1) => prim_get_text_color;
    "set-hyphen-penalty" (2) => prim_set_hyphen_penalty;
    // `set-hyphen-min : int -> int -> context -> context` (left_hyphen_min,
    // right_hyphen_min).
    "set-hyphen-min" (3) => prim_set_hyphen_min;
    "set-space-ratio" (4) => prim_set_space_ratio;
    "set-space-ratio-between-scripts" (6) => prim_set_space_ratio_between_scripts;
    "split-into-lines" (1) => prim_split_into_lines;
    v006 "block-frame-breakable" (4) => prim_block_frame_breakable_v006;
    v01  "block-frame-breakable" (4) => prim_block_frame_breakable_v01;
    "embed-block-top" (3) => prim_embed_block_top;
    // `set-font` forks in its SECOND argument's head only: 0.0.6's
    // `string * float * float` vs saphe-split's `font * float * float`.
    v006 "set-font" (3) => prim_set_font_v006;
    v01  "set-font" (3) => prim_set_font_v01;
    // `get-font` (vminstdef.yaml:1350) forks in its RESULT's head, for the
    // same reason and along the same seam.
    v006 "get-font" (2) => prim_get_font_v006;
    v01  "get-font" (2) => prim_get_font_v01;
    "set-code-text-command" (2) => prim_set_code_text_command;
    "get-natural-length" (1) => prim_get_natural_length;

    // ==== `set-dominant-wide-script`/`set-dominant-narrow-script`/
    // `set-language` are FAITHFUL stores with real getter round-trips
    // below; `register-outline` is likewise FAITHFUL (drives real PDF
    // `/Outlines` bookmarks). Only `set-every-word-break` remains a
    // STAND-IN (accepted and dropped). ====
    "set-dominant-wide-script" (2) => prim_set_dominant_wide_script;
    "set-dominant-narrow-script" (2) => prim_set_dominant_narrow_script;
    "set-language" (3) => prim_set_language;
    "get-dominant-wide-script" (1) => prim_get_dominant_wide_script;
    "get-dominant-narrow-script" (1) => prim_get_dominant_narrow_script;
    "get-language" (2) => prim_get_language;
    "set-every-word-break" (3) => prim_set_every_word_break;
    "register-outline" (1) => prim_register_outline;
    "extract-string" (1) => prim_extract_string;

    // ==== proof.satyh/footnote-scheme.satyh prims: `embed-block-bottom`
    // :1185, `line-stack-bottom` :1229 (both `tools/gencode/vminst.ml`),
    // `add-footnote` :1130. ====
    "embed-block-bottom" (3) => prim_embed_block_bottom;
    "line-stack-bottom" (1) => prim_line_stack_bottom;
    "line-stack-top" (1) => prim_line_stack_top;
    "add-footnote" (1) => prim_add_footnote;

    // ==== three PURE text-info prims — `get-initial-text-info` :953,
    // `deepen-indent` :921, `break` :935 (tools/gencode/vminst.ml,
    // text-mode). The text/html backends are OUT of scope for this PDF
    // port, so all three live in the single shared env (upstream keys
    // prims per mode).
    //
    // `get-initial-text-info` forks: v0.0.6 (vminst.ml:953) is `unit ->
    // text-info`; v0.1 (dev-0-1-0 vminst.ml:904-925) threads a text-mode
    // default math command + math-scripts stringifier into `tctxsub`. The
    // v01 body ACCEPTS AND DROPS both (STAND-IN, same degenerate policy as
    // `stringify-math`) — both bodies return `TextInfo{indent: 0}`. ====
    v006 "get-initial-text-info" (1) => prim_get_initial_text_info_v006;
    v01  "get-initial-text-info" (2) => prim_get_initial_text_info_v01;
    "deepen-indent" (2) => prim_deepen_indent;
    "break" (1) => prim_break;
}

/// The base environment v0.0.6 `document` programs start in. Back-compat
/// wrapper over `base_env_with_version(V0_0)`.
pub fn base_env() -> BaseEnv {
    base_env_with_version(RustyfiVersion::V0_0)
}

/// The base environment for a given target version — filters `PRIM_DEFS` by
/// `VersionSpan::allows`, so e.g. a `V0_1` env binds `prim_page_break_v01`
/// under the name `"page-break"`, never `prim_page_break_v006`. The five
/// bare-constant `env.define`s below (`inline-fil`/`inline-nil`/`block-nil`/
/// `omit-skip-after`/`clear-page`) live outside `PrimDef`/`VersionSpan` and
/// stay unconditional — all five exist in 0.1 upstream too (audited against
/// `dev-0-1-0:src/frontend/primitives.cppo.ml`); `tests/v01_prims_scalar.rs`'s
/// `bare_constants_bound_under_v01` proves it.
pub fn base_env_with_version(version: RustyfiVersion) -> BaseEnv {
    let mut env = BaseEnv::new();
    for def in PRIM_DEFS {
        if !def.version.allows(version) {
            continue;
        }
        env.define(
            def.name,
            Value::Prim {
                def,
                applied: Vec::new(),
            },
        );
    }
    env.define(
        "inline-fil",
        Value::InlineBoxes(vec![HorzBox::Pure(PureHorzBox::OuterFil)]),
    );
    // `inline-nil`/`block-nil`: no vminst.ml entry — v0.0.6 gets the empty
    // list for free from literal `{}`/`<>` syntax, which this port's syntax
    // layer doesn't produce standalone; these constants are the equivalent
    // value bound to a name.
    env.define("inline-nil", Value::InlineBoxes(Vec::new()));
    env.define("block-nil", Value::BlockBoxes(Vec::new()));
    // `omit-skip-after : inline-boxes` (`primitives.cppo.ml:567`) — a bare
    // CONSTANT marking `HorzOmitSkipAfter`, a line-breaking hint to drop the
    // interword glue that would otherwise follow (used at the tail of
    // `math.satyh`'s `\eqn`/`\math-list`/`\align`). STAND-IN: this port's
    // line-breaker has no such marker box, so it's the empty `inline-boxes`
    // list — never consulted, since none of those wrappers is called by
    // the file itself.
    env.define("omit-skip-after", Value::InlineBoxes(Vec::new()));
    // `clear-page : block-boxes` (`primitives.cppo.ml:569`) — a single-
    // element list carrying `VertBox::ClearPage`, which `chop_page`
    // (rustyfi-backend) treats as "end this page here". FAITHFUL.
    env.define("clear-page", Value::BlockBoxes(vec![VertBox::ClearPage]));
    // `here : string` — upstream `here` is a LEXER keyword expanding at lex
    // time to the source file's directory (`Filename.dirname`). This port
    // has no such lexer entry (`here` lexes as a plain `Token::Var`), so
    // it's a V0_1-only nullary CONSTANT bound to the empty string. Never
    // dereferenced as a real path: its consumers (`unidata.satyh`/
    // `hyph-english.satyh`) feed `here ^ …` into the `load-*` stand-ins
    // above, which drop the path unread.
    if version == RustyfiVersion::V0_1 {
        env.define("here", Value::Str(String::new()));
    }
    env
}

// ---- argument extractors ------------------------------------------------------

fn as_context(v: Value) -> Result<Context, EvalError> {
    match v {
        Value::Context(c) => Ok(*c),
        other => eval_error(format!("expected a context, got {}", other.type_name())),
    }
}

fn as_text_info(v: Value) -> Result<TextInfo, EvalError> {
    match v {
        Value::TextInfo(t) => Ok(t),
        other => eval_error(format!("expected a text-info, got {}", other.type_name())),
    }
}

fn as_hyphenation(v: Value) -> Result<HyphenLang, EvalError> {
    match v {
        Value::Hyphenation(tag) => Ok(tag),
        other => eval_error(format!("expected a hyphenation, got {}", other.type_name())),
    }
}

fn as_inline_text(v: Value) -> Result<(Rc<Vec<IText>>, Env), EvalError> {
    match v {
        Value::InlineText { elems, env } => Ok((elems, env)),
        other => eval_error(format!("expected inline-text, got {}", other.type_name())),
    }
}

fn as_block_text(v: Value) -> Result<(Rc<Vec<BText>>, Env), EvalError> {
    match v {
        Value::BlockText { elems, env } => Ok((elems, env)),
        other => eval_error(format!("expected block-text, got {}", other.type_name())),
    }
}

fn as_inline_boxes(v: Value) -> Result<Vec<HorzBox>, EvalError> {
    match v {
        Value::InlineBoxes(b) => Ok(b),
        other => eval_error(format!("expected inline-boxes, got {}", other.type_name())),
    }
}

fn as_block_boxes(v: Value) -> Result<Vec<VertBox>, EvalError> {
    match v {
        Value::BlockBoxes(b) => Ok(b),
        other => eval_error(format!("expected block-boxes, got {}", other.type_name())),
    }
}

fn as_int(v: Value) -> Result<i64, EvalError> {
    match v {
        Value::Int(n) => Ok(n),
        other => eval_error(format!("expected int, got {}", other.type_name())),
    }
}

fn as_float(v: Value) -> Result<f64, EvalError> {
    match v {
        Value::Float(x) => Ok(x),
        other => eval_error(format!("expected float, got {}", other.type_name())),
    }
}

fn as_bool(v: Value) -> Result<bool, EvalError> {
    match v {
        Value::Bool(b) => Ok(b),
        other => eval_error(format!("expected bool, got {}", other.type_name())),
    }
}

fn as_str(v: Value) -> Result<String, EvalError> {
    match v {
        Value::Str(s) => Ok(s),
        other => eval_error(format!("expected string, got {}", other.type_name())),
    }
}

// `regexp-of-string : string -> regexp` — the port models a `regexp` as its
// underlying pattern string, so this is the identity on the string.
fn prim_regexp_of_string(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    Ok(Value::Str(s))
}

// `string-match : regexp -> string -> bool` — whether `input` matches the
// pattern in full (anchored). Only the character-class subset `satysfi-base`'s
// `char.satyg` uses (`[…]`, with `a-z` ranges and an optional leading `^`
// negation) is modeled; any other pattern is compared literally.
fn prim_string_match(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let input = as_str(args.pop().unwrap())?;
    let pattern = as_str(args.pop().unwrap())?;
    Ok(Value::Bool(regexp_full_match(&pattern, &input)))
}

fn regexp_full_match(pattern: &str, input: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    if p.len() >= 2 && p[0] == '[' && p[p.len() - 1] == ']' {
        // A character class matches exactly one character.
        let mut chars = input.chars();
        match (chars.next(), chars.next()) {
            (Some(c), None) => char_in_class(&p[1..p.len() - 1], c),
            _ => false,
        }
    } else {
        input == pattern
    }
}

// `split-on-regexp : regexp -> string -> (int * string) list` — split `input`
// at every character matching the (single-character) pattern, pairing each
// resulting segment with its starting code-point offset. Handles the pattern
// forms base uses: a `[…]` class, an escaped literal (`\.`), or a bare
// literal character; anything else never matches (one segment = the whole
// string).
fn prim_split_on_regexp(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let input = as_str(args.pop().unwrap())?;
    let pattern = as_str(args.pop().unwrap())?;
    let is_delim = single_char_matcher(&pattern);
    let mut segments: Vec<Value> = Vec::new();
    let mut seg_start = 0usize;
    let mut cur = String::new();
    for (idx, c) in input.chars().enumerate() {
        if is_delim(c) {
            segments.push(Value::Tuple(vec![
                Value::Int(seg_start as i64),
                Value::Str(std::mem::take(&mut cur)),
            ]));
            seg_start = idx + 1;
        } else {
            cur.push(c);
        }
    }
    segments.push(Value::Tuple(vec![
        Value::Int(seg_start as i64),
        Value::Str(cur),
    ]));
    Ok(Value::List(segments))
}

/// A predicate matching one character against a `regexp` pattern's single-char
/// forms (a `[…]` class, an escaped literal `\X`, or a bare literal char).
fn single_char_matcher(pattern: &str) -> Box<dyn Fn(char) -> bool> {
    let p: Vec<char> = pattern.chars().collect();
    if p.len() >= 2 && p[0] == '[' && p[p.len() - 1] == ']' {
        let cls: Vec<char> = p[1..p.len() - 1].to_vec();
        Box::new(move |c| char_in_class(&cls, c))
    } else if p.len() == 2 && p[0] == '\\' {
        let lit = p[1];
        Box::new(move |c| c == lit)
    } else if p.len() == 1 {
        let lit = p[0];
        Box::new(move |c| c == lit)
    } else {
        Box::new(|_| false)
    }
}

fn char_in_class(cls: &[char], c: char) -> bool {
    let (neg, cls) = match cls.first() {
        Some('^') => (true, &cls[1..]),
        _ => (false, cls),
    };
    let mut i = 0;
    let mut found = false;
    while i < cls.len() {
        if i + 2 < cls.len() && cls[i + 1] == '-' {
            if cls[i] <= c && c <= cls[i + 2] {
                found = true;
            }
            i += 3;
        } else {
            if cls[i] == c {
                found = true;
            }
            i += 1;
        }
    }
    found ^ neg
}

fn as_length(v: Value) -> Result<Length, EvalError> {
    match v {
        Value::Length(l) => Ok(l),
        other => eval_error(format!("expected length, got {}", other.type_name())),
    }
}

fn as_list(v: Value) -> Result<Vec<Value>, EvalError> {
    match v {
        Value::List(items) => Ok(items),
        other => eval_error(format!("expected list, got {}", other.type_name())),
    }
}

fn as_image(v: Value) -> Result<ImageId, EvalError> {
    match v {
        Value::Image(id) => Ok(id),
        other => eval_error(format!("expected image, got {}", other.type_name())),
    }
}

// ---- graphics argument extractors ------------------------------------------

/// `point` = `Value::Tuple([Length, Length])` (mirrors `evalUtil.ml:228`'s
/// point extraction).
fn as_point(v: Value) -> Result<Point, EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 2 => {
            let mut it = vs.into_iter();
            let x = as_length(it.next().unwrap())?;
            let y = as_length(it.next().unwrap())?;
            Ok((x, y))
        }
        other => eval_error(format!(
            "expected a point (length * length), got {}",
            other.type_name()
        )),
    }
}

/// `color` = `Value::Ctor("Gray"|"RGB"|"CMYK", ..)` (mirrors
/// `evalUtil.ml:124`'s `get_color` exactly — a wrong shape here would
/// surface only at draw time).
fn as_color(v: Value) -> Result<Color, EvalError> {
    match v {
        Value::Ctor(name, payload) => match (name.as_str(), payload.map(|b| *b)) {
            ("Gray", Some(p)) => Ok(Color::Gray(as_float(p)?)),
            ("RGB", Some(Value::Tuple(vs))) if vs.len() == 3 => {
                let mut it = vs.into_iter();
                let r = as_float(it.next().unwrap())?;
                let g = as_float(it.next().unwrap())?;
                let b = as_float(it.next().unwrap())?;
                Ok(Color::Rgb(r, g, b))
            }
            ("CMYK", Some(Value::Tuple(vs))) if vs.len() == 4 => {
                let mut it = vs.into_iter();
                let c = as_float(it.next().unwrap())?;
                let m = as_float(it.next().unwrap())?;
                let y = as_float(it.next().unwrap())?;
                let k = as_float(it.next().unwrap())?;
                Ok(Color::Cmyk(c, m, y, k))
            }
            (other, _) => eval_error(format!(
                "expected a color (Gray/RGB/CMYK), got variant '{other}'"
            )),
        },
        other => eval_error(format!("expected a color, got {}", other.type_name())),
    }
}

/// `script` = nullary `Value::Ctor` (prim_types.rs `script_decl`); mirrors
/// upstream `get_script` (evalUtil.ml:235-241).
fn as_script(v: Value) -> Result<Script, EvalError> {
    match v {
        Value::Ctor(name, None) => match name.as_str() {
            "HanIdeographic" => Ok(Script::HanIdeographic),
            "Kana" => Ok(Script::Kana),
            "Latin" => Ok(Script::Latin),
            "OtherScript" => Ok(Script::OtherScript),
            other => eval_error(format!("expected a script, got variant '{other}'")),
        },
        other => eval_error(format!("expected a script, got {}", other.type_name())),
    }
}

/// Inverse of [`as_script`] (upstream `make_script_value`, evalUtil.ml:244).
fn make_script_value(s: Script) -> Value {
    let name = match s {
        Script::HanIdeographic => "HanIdeographic",
        Script::Kana => "Kana",
        Script::Latin => "Latin",
        Script::OtherScript => "OtherScript",
    };
    Value::Ctor(name.to_string(), None)
}

/// `language` = nullary `Value::Ctor` (prim_types.rs `language_decl`);
/// mirrors upstream `get_language_system` (evalUtil.ml:262).
fn as_language(v: Value) -> Result<Language, EvalError> {
    match v {
        Value::Ctor(name, None) => match name.as_str() {
            "Japanese" => Ok(Language::Japanese),
            "English" => Ok(Language::English),
            "NoLanguageSystem" => Ok(Language::NoLanguageSystem),
            other => eval_error(format!("expected a language, got variant '{other}'")),
        },
        other => eval_error(format!("expected a language, got {}", other.type_name())),
    }
}

/// Inverse of [`as_language`] (upstream `make_language_system_value`).
fn make_language_value(l: Language) -> Value {
    let name = match l {
        Language::Japanese => "Japanese",
        Language::English => "English",
        Language::NoLanguageSystem => "NoLanguageSystem",
    };
    Value::Ctor(name.to_string(), None)
}

/// `page` = `Value::Ctor("A4Paper"|.., None | Some(Tuple[Length;2]))`
/// — `page-break`'s first argument, mapped to the backend's
/// `PaperSize`.
fn as_page(v: Value) -> Result<PaperSize, EvalError> {
    match v {
        Value::Ctor(name, payload) => match (name.as_str(), payload.map(|b| *b)) {
            ("A0Paper", None) => Ok(PaperSize::A0),
            ("A1Paper", None) => Ok(PaperSize::A1),
            ("A2Paper", None) => Ok(PaperSize::A2),
            ("A3Paper", None) => Ok(PaperSize::A3),
            ("A4Paper", None) => Ok(PaperSize::A4),
            ("A5Paper", None) => Ok(PaperSize::A5),
            ("USLetter", None) => Ok(PaperSize::USLetter),
            ("USLegal", None) => Ok(PaperSize::USLegal),
            ("UserDefinedPaper", Some(Value::Tuple(vs))) if vs.len() == 2 => {
                let mut it = vs.into_iter();
                let w = as_length(it.next().unwrap())?;
                let h = as_length(it.next().unwrap())?;
                Ok(PaperSize::UserDefined(w, h))
            }
            (other, _) => eval_error(format!(
                "expected a page (A4Paper/.../UserDefinedPaper), got variant '{other}'"
            )),
        },
        other => eval_error(format!("expected a page, got {}", other.type_name())),
    }
}

/// v0.1's `page-break`'s first argument: a plain `(length * length)` tuple
/// — the `page` ADT (`as_page` above) no longer exists upstream in 0.1.
/// Maps straight into `PaperSize::UserDefined`, the exact same backend
/// value `as_page`'s own `UserDefinedPaper` arm produces: the retype drops
/// the ADT wrapper without changing what geometry `page-break` can
/// express, so only the source `Value` shape differs.
fn as_page_v01(v: Value) -> Result<PaperSize, EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 2 => {
            let mut it = vs.into_iter();
            let w = as_length(it.next().unwrap())?;
            let h = as_length(it.next().unwrap())?;
            Ok(PaperSize::UserDefined(w, h))
        }
        other => eval_error(format!(
            "expected a page as (length * length), got {}",
            other.type_name()
        )),
    }
}

/// `paddings` = `Value::Tuple([Length; 4])` in `(paddingL, paddingR,
/// paddingT, paddingB)` order (mirrors `evalUtil.ml`'s `get_paddings`).
/// `inline-frame-outer`'s first argument.
fn as_paddings(v: Value) -> Result<(Length, Length, Length, Length), EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 4 => {
            let mut it = vs.into_iter();
            let l = as_length(it.next().unwrap())?;
            let r = as_length(it.next().unwrap())?;
            let t = as_length(it.next().unwrap())?;
            let b = as_length(it.next().unwrap())?;
            Ok((l, r, t, b))
        }
        other => eval_error(format!(
            "expected paddings (length * length * length * length), got {}",
            other.type_name()
        )),
    }
}

/// `cell` = `Value::Ctor("NormalCell"|"EmptyCell"|"MultiCell", ..)` (mirrors
/// `evalUtil.ml:102`'s `get_cell`) — `tabular`'s grid entries;
fn as_cell(v: Value) -> Result<Cell, EvalError> {
    match v {
        Value::Ctor(name, payload) => match (name.as_str(), payload.map(|b| *b)) {
            ("NormalCell", Some(Value::Tuple(vs))) if vs.len() == 2 => {
                let mut it = vs.into_iter();
                let (l, r, t, b) = as_paddings(it.next().unwrap())?;
                let ib = as_inline_boxes(it.next().unwrap())?;
                Ok(Cell::Normal(Paddings { l, r, t, b }, ib))
            }
            ("EmptyCell", None) => Ok(Cell::Empty),
            ("MultiCell", Some(Value::Tuple(vs))) if vs.len() == 4 => {
                let mut it = vs.into_iter();
                let numrow = as_int(it.next().unwrap())?;
                let numcol = as_int(it.next().unwrap())?;
                let (l, r, t, b) = as_paddings(it.next().unwrap())?;
                let ib = as_inline_boxes(it.next().unwrap())?;
                Ok(Cell::Multi(
                    numrow.max(0) as usize,
                    numcol.max(0) as usize,
                    Paddings { l, r, t, b },
                    ib,
                ))
            }
            (other, _) => eval_error(format!(
                "expected a cell (NormalCell/EmptyCell/MultiCell), got variant '{other}'"
            )),
        },
        other => eval_error(format!("expected a cell, got {}", other.type_name())),
    }
}

/// `(cell list) list` — `tabular`'s first argument.
fn as_cell_grid(v: Value) -> Result<Vec<Vec<Cell>>, EvalError> {
    as_list(v)?
        .into_iter()
        .map(|row| -> Result<Vec<Cell>, EvalError> {
            as_list(row)?.into_iter().map(as_cell).collect()
        })
        .collect()
}

fn as_prepath(v: Value) -> Result<PrePath, EvalError> {
    match v {
        Value::PrePath(p) => Ok(p),
        other => eval_error(format!("expected pre-path, got {}", other.type_name())),
    }
}

fn as_path(v: Value) -> Result<Path, EvalError> {
    match v {
        Value::Path(p) => Ok(p),
        other => eval_error(format!("expected path, got {}", other.type_name())),
    }
}

fn as_graphics(v: Value) -> Result<GraphicsElem, EvalError> {
    match v {
        Value::Graphics(g) => Ok(g),
        other => eval_error(format!("expected graphics, got {}", other.type_name())),
    }
}

/// `dash` = `length * length * length` (mirrors `evalUtil.ml`'s `get_tuple3
/// get_length`) — `dashed-stroke`'s 2nd argument, `(d1, d2, d0)` = on-length,
/// off-length, phase.
fn as_dash(v: Value) -> Result<Dash, EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 3 => {
            let mut it = vs.into_iter();
            let d1 = as_length(it.next().unwrap())?;
            let d2 = as_length(it.next().unwrap())?;
            let d0 = as_length(it.next().unwrap())?;
            Ok((d1, d2, d0))
        }
        other => eval_error(format!(
            "expected a dash pattern (length * length * length), got {}",
            other.type_name()
        )),
    }
}

/// The inverse of `as_point` (mirrors `evalUtil.ml:228`'s point
/// construction) — used by `inline-graphics` to build the `(0pt, 0pt)`
/// origin its callback is (eagerly) invoked with; see that primitive's doc
/// comment for the shift-covariance caveat this stands in for.
fn make_point_value(pt: Point) -> Value {
    Value::Tuple(vec![Value::Length(pt.0), Value::Length(pt.1)])
}

/// `length list` construction (mirrors `evalUtil.ml:709`) — builds the
/// box-local grid-line coordinates `tabular`'s rule callback is (eagerly)
/// invoked with; see `prim_tabular`'s doc comment.
fn make_length_list(lens: &[Length]) -> Value {
    Value::List(lens.iter().map(|l| Value::Length(*l)).collect())
}

// ---- primitive-body macros ----------------------------------------------------
//
// The arithmetic, comparison, boolean, and unary-conversion primitives all
// share one strict-call shape: the (already-evaluated) operands are popped
// right-to-left through a type extractor, then the result is re-wrapped as a
// `Value`. These macros capture that shape so each primitive is a single line.
// The vminst.ml citations for each stay on the `prims!` registration table
// above; per-primitive notes ride along on the invocations below.

/// A strict binary primitive. Pops `b` then `a` (i.e. rightmost argument
/// first, matching application order) through the given extractor(s) and wraps
/// `body` as `Value::$ctor`. Accepts either one extractor for both operands or
/// a `(as_a, as_b)` pair when the operands have different types.
macro_rules! binop_prim {
    ($name:ident, ($as_a:path, $as_b:path), $ctor:ident, |$a:ident, $b:ident| $body:expr) => {
        fn $name(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
            let $b = $as_b(args.pop().unwrap())?;
            let $a = $as_a(args.pop().unwrap())?;
            Ok(Value::$ctor($body))
        }
    };
    ($name:ident, $as:path, $ctor:ident, |$a:ident, $b:ident| $body:expr) => {
        binop_prim!($name, ($as, $as), $ctor, |$a, $b| $body);
    };
}

/// A strict binary comparison: like `binop_prim!` but always wraps as
/// `Value::Bool`.
macro_rules! cmp_prim {
    ($name:ident, $as:path, |$a:ident, $b:ident| $body:expr) => {
        binop_prim!($name, ($as, $as), Bool, |$a, $b| $body);
    };
}

/// A strict unary primitive: pops one operand through `as` and wraps `body`
/// as `Value::$ctor`.
macro_rules! unop_prim {
    ($name:ident, $as:path, $ctor:ident, |$a:ident| $body:expr) => {
        fn $name(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
            let $a = $as(args.pop().unwrap())?;
            Ok(Value::$ctor($body))
        }
    };
}

/// A strict binary primitive with a fallible body: `body` is the function's
/// tail expression and must itself yield `Result<Value, EvalError>`, so it can
/// guard cases like division by zero.
macro_rules! binop_prim_try {
    ($name:ident, $as:path, |$a:ident, $b:ident| $body:expr) => {
        fn $name(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
            let $b = $as(args.pop().unwrap())?;
            let $a = $as(args.pop().unwrap())?;
            $body
        }
    };
}

// ---- text conversion ----------------------------------------------------------

/// Convert quoted inline text to boxes under `ctx` (the core of
/// `read-inline`): words become measured `InnerString`s, whitespace becomes
/// glue, embedded commands are applied to `ctx` and their arguments.
pub fn read_inline(
    interp: &mut Interp,
    ctx: &Context,
    elems: &[IText],
    env: &Env,
) -> Result<Vec<HorzBox>, EvalError> {
    let mut out = Vec::new();
    for elem in elems {
        match elem {
            IText::Text(text) => text_to_boxes(interp, ctx, text, &mut out)?,
            // `ImInputHorzEmbeddedCodeText` (`evaluator.cppo.ml:768-779`): hand
            // the literal to the context's code-text command if one is
            // installed, else set it as ordinary text
            // (`DefaultCodeTextCommand`).
            IText::CodeText(text) => match ctx.code_text_command {
                Some(id) => {
                    let cmd = interp.math_commands[id.0].clone();
                    let v = interp.apply(cmd, Value::Context(Box::new(ctx.clone())))?;
                    let v = interp.apply(v, Value::Str(text.clone()))?;
                    out.extend(as_inline_boxes(v)?);
                }
                None => text_to_boxes(interp, ctx, text, &mut out)?,
            },
            IText::Cmd { cmd, args } => {
                // Resolved at compile time (`crate::quoted`); running it can
                // still raise the same "unbound inline command" error for the
                // defensive case the compiler could not resolve.
                let cmd = cmd.run(env, interp)?;
                let mut v = interp.apply(cmd, Value::Context(Box::new(ctx.clone())))?;
                for arg in args {
                    let mut opt_vals = Vec::with_capacity(arg.opts.len());
                    for (label, e) in &arg.opts {
                        opt_vals.push((label.clone(), e.run(env, interp)?));
                    }
                    let arg_v = arg.arg.run(env, interp)?;
                    v = interp.apply_with_opts(v, opt_vals, arg_v)?;
                }
                out.extend(as_inline_boxes(v)?);
            }
            IText::Embed { expr, span } => {
                let v = expr.run(env, interp)?;
                match v {
                    Value::InlineText {
                        elems: sub_elems,
                        env: cap_env,
                    } => {
                        out.extend(read_inline(interp, ctx, &sub_elems, &cap_env)?);
                    }
                    other => {
                        return Err(EvalError {
                            span: Some(*span),
                            msg: format!(
                                "expected inline-text in '#…;' embed, got {}",
                                other.type_name()
                            ),
                        });
                    }
                }
            }
            IText::EmbedMath { elems, .. } => {
                // Upstream: a bare `${…}` in inline text evaluates by
                // applying the context's installed `[math] inline-cmd` to
                // (ctx, the math value) — `apply(cmd, ctx)` then
                // `apply(_, math)`, exactly like `IText::Cmd` above.
                let installed = ctx
                    .math_command
                    .and_then(|id| interp.math_commands.get(id.0).cloned());
                match installed {
                    Some(cmd) => {
                        let v = interp.apply(cmd, Value::Context(Box::new(ctx.clone())))?;
                        let v = interp.apply(
                            v,
                            Value::MathText {
                                elems: Rc::clone(elems),
                                env: env.clone(),
                            },
                        )?;
                        out.extend(as_inline_boxes(v)?);
                    }
                    None => {
                        // No installed command (contexts built by
                        // `Context::initial` directly, i.e. unit tests):
                        // reflect + lay out through the faithful engine so
                        // `\cmd`/`#var` still evaluate — the same machinery
                        // `+math(${…})` uses via `as_math`. This fallback
                        // dispatches on `interp.version`
                        // — the installed-command path above is version-
                        // blind already (an ordinary `[math-text] inline-
                        // cmd` applied to `(ctx, math-text)`).
                        let mut atoms = Vec::new();
                        if interp.version.math_is_split() {
                            for e in elems.iter() {
                                reflect_math_elem_v01(interp, ctx, e, env, &mut atoms)?;
                            }
                        } else {
                            for e in elems.iter() {
                                reflect_math_elem(interp, e, env, &mut atoms)?;
                            }
                        }
                        out.push(HorzBox::Pure(layout_math_value(interp, ctx, &atoms)?));
                    }
                }
            }
        }
    }
    // Space inline `\code(…)`/`${…}` boxes against adjacent CJK prose the way
    // SATySFi does (the text-run glue in `text_to_boxes` can't see these
    // cross-element boundaries). Idempotent — a boundary already carrying glue
    // is skipped.
    Ok(insert_box_interscript_glue(out, ctx))
}

/// Convert quoted block text to vertical boxes (the core of `read-block`).
fn read_block(
    interp: &mut Interp,
    ctx: &Context,
    elems: &[BText],
    env: &Env,
) -> Result<Vec<VertBox>, EvalError> {
    let mut out = Vec::new();
    for elem in elems {
        match elem {
            BText::Cmd { cmd, args } => {
                let cmd = cmd.run(env, interp)?;
                let mut v = interp.apply(cmd, Value::Context(Box::new(ctx.clone())))?;
                for arg in args {
                    let mut opt_vals = Vec::with_capacity(arg.opts.len());
                    for (label, e) in &arg.opts {
                        opt_vals.push((label.clone(), e.run(env, interp)?));
                    }
                    let arg_v = arg.arg.run(env, interp)?;
                    v = interp.apply_with_opts(v, opt_vals, arg_v)?;
                }
                out.extend(as_block_boxes(v)?);
            }
            BText::Embed { expr, span } => {
                let v = expr.run(env, interp)?;
                match v {
                    Value::BlockText {
                        elems: sub_elems,
                        env: cap_env,
                    } => {
                        out.extend(read_block(interp, ctx, &sub_elems, &cap_env)?);
                    }
                    other => {
                        return Err(EvalError {
                            span: Some(*span),
                            msg: format!(
                                "expected block-text in '#…;' embed, got {}",
                                other.type_name()
                            ),
                        });
                    }
                }
            }
        }
    }
    Ok(out)
}

/// UAX#14 byte offsets in `text` that are a real, content-driven break
/// candidate: every `break_opportunities` boundary except the one always
/// reported at `text.len()` (the segmenter's "always break at the end of
/// text" convention — an artifact of segmenting this one run in isolation,
/// not a signal about what follows it in the paragraph, since
/// `text_to_boxes` is called once per `IText::Text` leaf and more content
/// may follow via a sibling `Cmd`, `Embed`, or `EmbedMath`).
fn uax14_boundaries(text: &str) -> Vec<Option<BreakKind>> {
    let mut boundary = vec![None; text.len() + 1];
    for (offset, kind) in break_opportunities(text) {
        if offset < text.len() {
            boundary[offset] = Some(kind);
        }
    }
    boundary
}

/// This run's `(font, size, rising)` for `script` (see `Context::font_scheme`'s
/// doc comment): `Latin` reads `ctx.font` itself (NOT `font_scheme[Latin].font`)
/// so `set-font-key`/`\bold`/`\emph` keep working unchanged, while still
/// picking up `font_scheme[Latin]`'s ratio/rising (written in lockstep by
/// `set-font Latin ..`).
///
/// `OtherScript` first goes through `normalize_script` (`horzBox.ml:472`):
/// upstream's `CommonNarrow`/`Inherited` resolve to `ctx.dominant_narrow_script`
/// rather than to a scheme slot of their own; this port's `char_script` has no
/// separate Common bucket, so everything outside Latin-1..Latin-Ext-B and the
/// CJK ranges lands in `OtherScript` and gets the same treatment — the only
/// WIDE Common chars (`U+3000` fullwidth forms) already fall in
/// `char_script`'s `HanIdeographic` range, so this costs nothing there.
///
/// Real effect, not a niceness: without `set-dominant-narrow-script Kana`, a
/// document's `□`/`✓` both resolve to a Latin face with NEITHER glyph, degrade
/// to the same `.notdef` glyph id and `ToUnicode` entry, and one of the two
/// simply vanishes from the extracted text — enumitem's three missing `✓`,
/// each overprinted onto a `□` by the document's own `ooalign`.
///
/// Defaults to `OtherScript` (`Context::initial`, matching upstream), so a
/// document that never calls the primitive is unaffected and the recursion is
/// one step deep at most.
fn script_font(ctx: &Context, script: Script) -> ScriptFont {
    if script == Script::OtherScript && ctx.dominant_narrow_script != Script::OtherScript {
        return script_font(ctx, ctx.dominant_narrow_script);
    }
    if script == Script::Latin {
        ScriptFont {
            font: ctx.font,
            ..ctx.font_scheme[Script::Latin as usize]
        }
    } else {
        ctx.font_scheme[script as usize]
    }
}

/// Measure `text` (already known to be one script run) at `size` under
/// `font`, falling back per-glyph to `fallback_font` (`ctx.font`) when
/// `font` has no glyph for a character — the "CJK per-glyph metrics path
/// stubbed" case: a character within a script-run's bucket
/// that its assigned font happens to lack (e.g. a fullwidth-form character
/// absent from a narrow CJK face) still measures via the Latin default
/// rather than failing the whole run. Errors (both fonts lack the glyph)
/// name the offending character and font key.
///
/// **Known limitation** (documented, not fixed): the
/// measurement here can fall back per-glyph, but `PureHorzBox::InnerString`
/// carries one `HorzStringInfo::font` for its WHOLE text run — so if a
/// fallback glyph is actually used, the PDF writer's `emit_box` still tries
/// to look it up in `font`'s face at render time and fails there instead.
/// Splitting a run into sub-boxes at the source-font-only/fallback boundary
/// (a faithful fix) is future work; every stdja default face configuration
/// covers its script's whole repertoire, so this path is not expected to
/// trigger in practice.
fn measure_run(
    interp: &Interp,
    font: FontKey,
    fallback_font: FontKey,
    text: &str,
    size: Length,
) -> Result<Length, EvalError> {
    let mut width = Length::ZERO;
    for c in text.chars() {
        // A character absent from BOTH the run font and the fallback degrades
        // to a `.notdef`-style box (half-em advance) rather than aborting the
        // whole document — the way real typesetters render an uncovered glyph.
        // (satysfi-base's `enumitem`/the SATySFi Book use a few glyphs — `□`,
        // `〚` — that the bundled Latin face lacks; a faithful per-glyph
        // font-fallback via run-splitting is the documented follow-up.) This
        // only ever changes behavior for a glyph that would otherwise be a
        // hard error, so covered-glyph documents are byte-identical.
        let advance = interp
            .metrics
            .advance(font, c, size)
            .or_else(|| interp.metrics.advance(fallback_font, c, size))
            .unwrap_or(size * 0.5);
        width += advance;
    }
    Ok(width)
}

/// Build one `InnerString` box for `text`, measured through [`measure_run`]
/// with `sf`'s font/size/rising — the single construction site shared by
/// `text_to_boxes`'s `flush_word` for both the plain (no-hyphenation) path
/// and each hyphenated fragment / hyphen glyph. Factored out so both paths
/// measure/build identically — this is part of what makes the width-identity
/// argument hold: `measure_run` is purely additive per char (no
/// kerning/ligatures), so concatenating the fragments this produces
/// reconstructs exactly the box a single un-split call would have produced.
fn make_inner_string_pure_box(
    interp: &Interp,
    ctx: &Context,
    sf: ScriptFont,
    size: Length,
    rising: Length,
    text: String,
) -> Result<PureHorzBox, EvalError> {
    let width = measure_run(interp, sf.font, ctx.font, &text, size)?;
    // SATySFi measures a run's height/depth from the ACTUAL per-glyph bounding
    // boxes (fontInfo.ml `get_metrics_of_word`), not the font-level
    // ascender/descender — so a no-descender run (CJK, digits, TOC dots) is
    // shorter and packs tighter at block boundaries.
    let (height, depth) = interp.metrics.run_vextent(sf.font, &text, size);
    Ok(PureHorzBox::InnerString {
        info: HorzStringInfo {
            font: sf.font,
            size,
            rising,
            color: ctx.text_color,
        },
        height,
        depth,
        text,
        width,
    })
}

/// Whether two adjacent runs' scripts form a Latin↔CJK boundary that gets
/// SATySFi's default inter-script glue (`primitives.ml:517-524`: entries for
/// `(Latin, Kana)`, `(Kana, Latin)`, `(Latin, Han)`, `(Han, Latin)` only —
/// NOT Kana↔Han, and not same-script).
fn is_latin_cjk_boundary(a: Script, b: Script) -> bool {
    let is_cjk = |s| matches!(s, Script::HanIdeographic | Script::Kana);
    (a == Script::Latin && is_cjk(b)) || (is_cjk(a) && b == Script::Latin)
}

/// Upstream `is_open_punctuation` (`charBasis.ml:133`: `OP | QU | JLOP`) —
/// opening brackets and quotes. Consulted for the LEFT edge of a script
/// boundary only.
fn is_open_punct(c: char) -> bool {
    matches!(
        c,
        '(' | '['
            | '{'
            | '"'
            | '\''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
    )
}

/// Upstream `is_close_punctuation` (`charBasis.ml:139`: `CL | CP | QU | NS |
/// JLCP | JLNS | JLCM | JLFS`) — closing brackets, quotes, and the kuten/touten
/// family. Consulted for the RIGHT edge of a script boundary only.
///
/// Two families the port used to list are NOT in that set, and their absence is
/// upstream's own, not an oversight:
/// - `!` `?` `!` `?` are line-break class `EX` (`LineBreak.txt:2566,2582` for
///   the fullwidth pair), which appears in no arm of `is_close_punctuation`;
/// - `,` `.` `;` `:` are `IS`, likewise absent.
///
/// Their FULLWIDTH cousins are a different matter and stay: `,`/`.` are
/// overridden to `JLCM`/`JLFS` (`lineBreakDataMap.ml:95-96`) and `:`/`;` are
/// `NS` (`LineBreak.txt:2580`).
///
/// Listing the six suppressed the 0.24em inter-script glue — and, since that
/// glue is the boundary's only break candidate, the break opportunity with it —
/// before every sentence-final mark that is not a kuten.
fn is_close_punct(c: char) -> bool {
    matches!(
        c,
        ')' | ']'
            | '}'
            | '"'
            | '\''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
            | ''
    )
}

/// Whether SATySFi's default inter-script glue is suppressed between a
/// left-hand character `l` and a right-hand `r`.
///
/// `pure_space_between_scripts` (`convertText.ml:31`) drops the glue when
/// `is_open_punctuation lbc1 || is_close_punctuation lbc2` — the LEFT edge being
/// OPENING punctuation, or the RIGHT edge being CLOSING punctuation. The aki
/// that would otherwise sit there is supplied by the separate JLreq
/// class-spacing layer.
///
/// The port used to test one symmetric "is punctuation" predicate against BOTH
/// edges, which suppressed far more than upstream: `、` before a Latin/math run
/// is a *closing* mark on the LEFT, which upstream does not suppress. Since this
/// glue is also the only break opportunity at such a boundary, suppressing it
/// left the breaker with nowhere to break — latexcmds ran
/// `…、${dropcolor}` 32pt past the margin because there was no legal break
/// between the touten and the math box.
fn interscript_glue_suppressed(l: char, r: char) -> bool {
    is_open_punct(l) || is_close_punct(r)
}

/// JLreq character classes SATySFi's inter-CJK spacing distinguishes
/// (`charBasis.ml:116-122`). Only the classes that actually change spacing are
/// modelled; every other CJK character is `None` ("ordinary").
#[derive(Clone, Copy, PartialEq, Eq)]
enum JlClass {
    /// cl-01, fullwidth OPEN punctuation — carries a leading half-width kern.
    Open,
    /// cl-02, fullwidth CLOSE punctuation — trailing half-width kern.
    Close,
    /// cl-06, kuten (fullwidth full stop) — trailing half-width kern.
    FullStop,
    /// cl-07, touten (fullwidth comma) — trailing half-width kern.
    Comma,
    /// cl-05, nakaten (fullwidth middle dot) — quarter-width kern BOTH sides.
    MiddleDot,
}

fn jl_class(c: char) -> Option<JlClass> {
    match c {
        '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' => {
            Some(JlClass::Open)
        }
        '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | '' => {
            Some(JlClass::Close)
        }
        '' | '' => Some(JlClass::FullStop),
        '' | '' => Some(JlClass::Comma),
        '' | '' | '' => Some(JlClass::MiddleDot),
        _ => None,
    }
}

/// `ideographic_single`'s TRAILING kern for `c` (`convertText.ml:266-283`), as a
/// negative ratio of `font_size`: JLCP/JLFS/JLCM are `[glyph; hwkern]`, JLMD is
/// `[qwkern; glyph; qwkern]`.
///
/// A kern belongs to the CHARACTER, not to the boundary — `ideographic_single`
/// runs per chunk and never consults its neighbours. Hence one char per
/// function, even though the only caller today is the pair-shaped
/// [`cjk_pair_space`]: at a CJK↔Latin boundary the CJK side still carries its own
/// kern upstream, and this port does not yet emit it there (see the
/// `PreventBreak` arm of `text_to_boxes` for what that costs and what unblocking
/// it needs).
fn cjk_trailing_kern(c: char) -> f64 {
    match jl_class(c) {
        Some(JlClass::Close) | Some(JlClass::FullStop) | Some(JlClass::Comma) => -0.5,
        Some(JlClass::MiddleDot) => -0.25,
        _ => 0.0,
    }
}

/// `ideographic_single`'s LEADING kern for `c` — JLOP is `[hwkern; glyph]`,
/// JLMD `[qwkern; glyph; qwkern]`. See [`cjk_trailing_kern`].
fn cjk_leading_kern(c: char) -> f64 {
    match jl_class(c) {
        Some(JlClass::Open) => -0.5,
        Some(JlClass::MiddleDot) => -0.25,
        _ => 0.0,
    }
}

/// The glue SATySFi puts between two directly adjacent CJK characters, as an
/// absolute `(natural, shrink, stretch)` — `space_between_chunks`
/// (`convertText.ml:220`) with `ideographic_single`'s compensating kerns
/// (`convertText.ml:266`) folded in.
///
/// Upstream renders CJK punctuation at its full em and kerns it back:
/// `。`/`、`/`)` carry a trailing −0.5em kern, `(` a leading one, `・` −0.25em
/// on both sides. `pure_space_between_classes` (`convertText.ml:194`) then adds
/// a half-width space back — natural 0.5em, stretch 0.25em, shrink 0.25em
/// unless the pair is "hard" (after a full stop). Net natural width is
/// unchanged, but each punctuation mark contributes **0.25em of stretch** — ten
/// times the 0.025em `adjacent_stretch` between ordinary characters, and the
/// bulk of a Japanese line's elasticity. Two punctuation marks in a row
/// (`」、`, `」。`) get NO space back, so the pair sets 0.5em tighter.
///
/// **Which font size each part scales against is not uniform, and that is the
/// point of taking three sizes rather than one.** Upstream applies the kerns
/// (`halfwidth_kern`/`quarterwidth_kern`, `convertText.ml:110-118`) and all
/// four `pure_halfwidth_space_*` sizes to `get_corrected_font_size ctx script`
/// (`convertText.ml:76-79`) — the font size TIMES the script's own ratio, 0.88
/// for stdja's CJK face, so a half-width kern at 12pt is −5.28pt and not −6pt.
/// Only `adjacent_space` (`:101-106`) takes the RAW `ctx.font_size`. Scaling
/// everything by the raw size made every JLreq class space 13.6% too elastic
/// (0.25 × 12 = 3pt of stretch where upstream has 0.25 × 10.56 = 2.64pt);
/// since punctuation carries ten times the stretch of an ordinary
/// inter-character gap, that error set the stretch budget of a whole Japanese
/// line and so its justified glyph positions.
///
/// `size_a`/`size_b` are the corrected sizes of the LEFT and RIGHT characters,
/// upstream's `size1`/`size2` (`convertText.ml:196-198`); the `hwsoftM`/
/// `hwhardM` arms take `Length::max` of the two, exactly as `sizeM` does. They
/// differ only when the two characters resolve to different `font_scheme` slots
/// (`Kana` vs `HanIdeographic`) carrying different ratios.
fn cjk_pair_space(
    a: char,
    size_a: Length,
    b: char,
    size_b: Length,
    raw_size: Length,
    adjacent_stretch: f64,
) -> (Length, Length, Length) {
    use JlClass::*;
    let (ca, cb) = (jl_class(a), jl_class(b));
    // Kerns from `ideographic_single`, each a NEGATIVE ratio of its OWN
    // character's corrected size. Between two CJK characters the pair's kern is
    // exactly `a`'s trailing plus `b`'s leading one, which is what makes the
    // pair form equivalent to upstream's per-character one here.
    let kern = size_a * cjk_trailing_kern(a) + size_b * cjk_leading_kern(b);
    let size_m = Length::max(size_a, size_b);
    // `pure_space_between_classes`, in its own match order. The third component
    // of each arm is the size that arm's space scales against.
    let hwsoft = |s: Length| (s * 0.5, s * 0.25, s * 0.25);
    let hwhard = |s: Length| (s * 0.5, Length::ZERO, s * 0.25);
    let cls = match (ca, cb) {
        (Some(Close), Some(Open)) | (Some(Comma), Some(Open)) => Some(hwsoft(size_m)),
        (Some(FullStop), Some(Open)) => Some(hwhard(size_m)),
        (_, Some(Open)) => Some(hwsoft(size_b)),
        (Some(Close), Some(Comma)) | (Some(Close), Some(FullStop)) => None,
        (Some(Close), _) | (Some(Comma), _) => Some(hwsoft(size_a)),
        (Some(FullStop), _) => Some(hwhard(size_a)),
        _ => None,
    };
    match cls {
        Some((n, sh, st)) => (kern + n, sh, st),
        // No class space: `adjacent_space` (natural 0, shrink 0, stretch
        // `adjacent_stretch` × the RAW size), plus whatever kern the pair
        // carries.
        None => (kern, Length::ZERO, raw_size * adjacent_stretch),
    }
}

/// A box's LEADING glyph for inter-script spacing, or `None` for
/// glue/discretionary/skip/image (a "transparent" separator — an inter-script
/// space is never inserted adjacent to one) and for math (reported as a Latin
/// `'x'`, matching SATySFi where a `${…}` chunk spaces against CJK like Western
/// text). The char lets the caller apply the `is_interscript_punct` guard.
fn box_leading_char(b: &HorzBox) -> Option<char> {
    match b {
        HorzBox::Pure(PureHorzBox::InnerString { text, .. }) => text.chars().next(),
        HorzBox::Pure(PureHorzBox::Math { .. }) => Some('x'),
        _ => None,
    }
}

/// A box's TRAILING glyph (see `box_leading_char`).
fn box_trailing_char(b: &HorzBox) -> Option<char> {
    match b {
        HorzBox::Pure(PureHorzBox::InnerString { text, .. }) => text.chars().last(),
        HorzBox::Pure(PureHorzBox::Math { .. }) => Some('x'),
        _ => None,
    }
}

/// Insert SATySFi's inter-script glue (`default_script_space_map`) between two
/// DIRECTLY-adjacent boxes whose touching edges are Latin↔CJK — the boundary
/// that `text_to_boxes` can't see because it spans separate inline elements: a
/// `\code(…)`/`${…}` box against surrounding CJK prose ("cellfmt 型", "𝑛 番目").
/// A boundary already carrying a glue/discretionary reads as `None` on one edge
/// and is skipped, so this is idempotent and never doubles the text-run glue.
/// The Latin↔CJK inter-script space, `pure_space_between_scripts`
/// (`convertText.ml:29-50`).
///
/// **RIGID — natural `0.24 * font_size`, no shrink, no stretch** — and that is
/// upstream's behaviour, not a simplification. `default_script_space_map`
/// (`primitives.cppo.ml:488`) really does carry the triple
/// `(0.24, 0.08, 0.16)`, but `pure_space_between_scripts` spends it like this:
///
/// ```ocaml
/// Some(LBAtom((natural (size *% r0), size *% r1, size *% r2), EvHorzEmpty))
/// ```
///
/// `LBAtom`'s first field is `metrics = length_info * length * length`, i.e.
/// *(width info, HEIGHT, DEPTH)* (`lineBreakBox.ml:7`), and `natural wid`
/// builds `{natural = wid; shrinkable = zero; stretchable = zero}`
/// (`lineBreakBox.ml:54-59`). So `r1` and `r2` land in the height and depth
/// slots; only `r0` reaches the width. Contrast the sibling
/// `pure_halfwidth_space_soft` (`convertText.ml:83-85`), which builds its
/// elasticity with `make_width_info` and passes `Length.zero, Length.zero` for
/// height and depth — the correct shape, right next door. The commented-out
/// predecessor at `convertText.ml:58` has the same misplacement, so v0.0.6 has
/// never had an elastic inter-script space.
///
/// The stray height (`0.08 * size`) and depth (`0.16 * size`) are swallowed by
/// `get_total_metrics`'s `max hacc h` / `min dacc d` (`lineBreak.ml:55-59`) —
/// a 0.96pt height never exceeds a real glyph's and a POSITIVE depth never
/// wins a `min` against a descender — so rigidity is the only observable
/// consequence, and it is the one that matters: this glue sits at every
/// Japanese/Latin junction, and giving it 0.16em of stretch let the port soak
/// up justification slack that upstream is forced to push into the
/// inter-character `adjacent_space` inside the CJK runs themselves.
///
/// Still a break point: upstream wraps this box in `discretionary_if_breakable`
/// (`convertText.ml:228`) exactly as it does the elastic glues, and an
/// `OuterEmpty` with zero shrink and stretch is still `is_glue()` — which is
/// also why a ratio of 0.0 emits a zero-width box rather than nothing.
///
/// The ratio comes from `ctx.script_space_map`, so
/// `set-space-ratio-between-scripts` reaches it (slydifi's arctic theme zeroes
/// all four Latin↔CJK directions).
fn interscript_glue(ctx: &Context, left: Script, right: Script) -> PureHorzBox {
    PureHorzBox::OuterEmpty {
        natural: ctx.font_size * ctx.script_space_map[left as usize][right as usize],
        shrinkable: Length::ZERO,
        stretchable: Length::ZERO,
    }
}

fn insert_box_interscript_glue(boxes: Vec<HorzBox>, ctx: &Context) -> Vec<HorzBox> {
    if boxes.len() < 2 {
        return boxes;
    }
    let mut out: Vec<HorzBox> = Vec::with_capacity(boxes.len());
    for b in boxes {
        if let (Some(pc), Some(cc)) = (out.last().and_then(box_trailing_char), box_leading_char(&b))
        {
            let (ls, rs) = (char_script(pc), char_script(cc));
            if is_latin_cjk_boundary(ls, rs) && !interscript_glue_suppressed(pc, cc) {
                out.push(HorzBox::Pure(interscript_glue(ctx, ls, rs)));
            }
        }
        out.push(b);
    }
    out
}

fn text_to_boxes(
    interp: &mut Interp,
    ctx: &Context,
    text: &str,
    out: &mut Vec<HorzBox>,
) -> Result<(), EvalError> {
    // Interword glue is upstream's
    // `context_main.space_natural`/`space_shrink`/`space_stretch`
    // (`set-space-ratio`), each a ratio of `font_size` — NOT a measured
    // glyph-advance of the space character and NOT a fraction of the natural
    // width. `ctx.space_*` always carries a value (defaults 0.33/0.08/0.16,
    // matching `Context::initial`'s own upstream-faithful defaults), so this
    // is a plain formula, no fallback needed.
    let space_width = ctx.font_size * ctx.space_natural;
    let boundary = uax14_boundaries(text);
    let mut word = String::new();
    let flush_word =
        |word: &mut String, script: Script, out: &mut Vec<HorzBox>| -> Result<(), EvalError> {
            if word.is_empty() {
                return Ok(());
            }
            let sf = script_font(ctx, script);
            let size = ctx.font_size * sf.ratio;
            // The script-font's own baseline raise (a ratio of font_size) PLUS the
            // manual raise from `set-manual-rising` (`ctx.manual_rising`, an
            // absolute Length). Both feed `HorzStringInfo.rising`, which every
            // render path adds to the baseline before `Tj`. `manual_rising`
            // defaults to `Length::ZERO` (`Context::initial`), so a document that
            // never calls `set-manual-rising` is byte-identical. Real effect: the
            // `\SATySFi`/`\LaTeX`/`\TeX` logo kerning.
            let rising = ctx.font_size * sf.rising + ctx.manual_rising;

            // Knuth-Liang hyphenation opt-in injection: fires ONLY when a
            // dictionary has been installed (`ctx.hyphen_dictionary ==
            // Some(tag)`) and the run's script is Latin. With `hyphen_dictionary
            // == None` (the `Context::initial` default), `breaks` is always
            // empty and the code below falls straight through to the
            // single-`InnerString` path.
            let breaks = match ctx.hyphen_dictionary {
                Some(tag) if script == Script::Latin => {
                    // An explicit soft hyphen (U+00AD) authored in the word
                    // takes priority over dictionary-derived breaks (matches the
                    // `hyphenation` crate's own `Standard::hyphenate` priority
                    // rule). Only reachable here with a soft hyphen still
                    // embedded in `word` because the tokenizer above
                    // (`text_to_boxes`'s per-char loop) defers to this branch
                    // instead of splitting on it as an ordinary UAX#14 boundary
                    // — gated on this same `Some(tag) && Latin` condition, so
                    // `hyphen_dictionary == None` never reaches
                    // `strip_soft_hyphens` and reproduces exactly today's
                    // split-at-soft-hyphen behavior.
                    let (clean, shy_breaks) = crate::hyphenation::strip_soft_hyphens(word);
                    if !shy_breaks.is_empty() {
                        *word = clean;
                        shy_breaks
                    } else {
                        crate::hyphenation::hyphenate_word(
                            tag,
                            word,
                            ctx.left_hyphen_min.max(0) as usize,
                            ctx.right_hyphen_min.max(0) as usize,
                        )
                    }
                }
                _ => Vec::new(),
            };

            if breaks.is_empty() {
                out.push(HorzBox::Pure(make_inner_string_pure_box(
                    interp,
                    ctx,
                    sf,
                    size,
                    rising,
                    std::mem::take(word),
                )?));
                return Ok(());
            }

            // Width-identity invariant (also see
            // `make_inner_string_pure_box`'s doc comment): `measure_run` is
            // purely additive per char (no
            // kerning/ligatures), so splitting `word` into fragments here and
            // rejoining them via empty-slot `Discretionary`s (taken only at a
            // chosen line break) reproduces the exact width/height/depth of the
            // un-split box when no break is actually taken — only words the DP
            // *does* break render differently, which is the intended new
            // behavior, confined to documents that opt in.
            let chars: Vec<char> = word.chars().collect();
            let penalty = ctx.hyphen_badness.clamp(i32::MIN as i64, i32::MAX as i64) as i32;
            let mut prev = 0usize;
            for &b in &breaks {
                let fragment: String = chars[prev..b].iter().collect();
                out.push(HorzBox::Pure(make_inner_string_pure_box(
                    interp, ctx, sf, size, rising, fragment,
                )?));
                let hyphen_box =
                    make_inner_string_pure_box(interp, ctx, sf, size, rising, "-".to_string())?;
                out.push(HorzBox::Pure(PureHorzBox::Discretionary {
                    penalty,
                    pre_break: vec![hyphen_box],
                    post_break: Vec::new(),
                    no_break: Vec::new(),
                }));
                prev = b;
            }
            let tail: String = chars[prev..].iter().collect();
            out.push(HorzBox::Pure(make_inner_string_pure_box(
                interp, ctx, sf, size, rising, tail,
            )?));
            word.clear();
            Ok(())
        };
    // `Some(s)` exactly when `word` is non-empty — the script of the run
    // currently being accumulated (a run also breaks on a script
    // change, not just on whitespace/UAX#14, see `char_script`).
    let mut word_script: Option<Script> = None;
    // The script of the immediately-preceding *typeset* character (persists
    // across the UAX#14 discretionary flushing that resets `word_script`), so
    // an inter-script boundary can be detected even between two single-char
    // CJK/Latin runs. Reset by an explicit space (no auto inter-script glue is
    // added adjacent to a real space). See the `is_latin_cjk_boundary` insert.
    let mut prev_script: Option<Script> = None;
    // The preceding typeset char itself, for the `is_interscript_punct` guard.
    let mut prev_char: Option<char> = None;
    for (i, c) in text.char_indices() {
        // Whitespace normalization around CJK — upstream's rewrite table
        // (`lineBreakDataMap.ml:143-157`, applied before any box is built):
        //
        //   CJK + (SP|BR) + Latin -> deleted      Latin + (SP|BR) + CJK -> deleted
        //   CJK + BR      + CJK   -> deleted      CJK   + SP      + CJK -> KEPT
        //   any remaining (SP|BR) touching CJK -> deleted; a leftover BR -> space
        //
        // Every space/line break adjacent to CJK is dropped EXCEPT a single
        // literal space between two CJK characters — the Latin/CJK boundary's
        // spacing is supplied by the inter-script glue below (0.24em), not by
        // the author's whitespace, so keeping it both double-counted that
        // boundary and turned every source line break into a space (the port
        // set `あります。 1 つは`/`これは 指定した` where SATySFi sets both
        // tight — figbox `manual.saty:116-120`). Deleting is a plain
        // `continue`: the characters either side still space against each
        // other through the inter-script rule, as if the whitespace had never
        // been written.
        if c == ' ' || c == '\n' {
            let is_cjk_script = |s| matches!(s, Script::HanIdeographic | Script::Kana);
            let prev_cjk = prev_script.is_some_and(is_cjk_script);
            let rest = &text[i + c.len_utf8()..];
            // Whether more whitespace follows: upstream's rules only ever match
            // ONE space between the two CJK characters (a longer run falls
            // through to the delete-everything rules), so a run collapses away.
            let run_continues = rest
                .chars()
                .next()
                .is_some_and(|ch| matches!(ch, ' ' | '\n'));
            let next_cjk = rest
                .chars()
                .find(|ch| !matches!(ch, ' ' | '\n'))
                .is_some_and(|ch| is_cjk_script(char_script(ch)));
            if prev_cjk || next_cjk {
                let keep = c == ' ' && !run_continues && prev_cjk && next_cjk;
                if !keep {
                    continue;
                }
            }
        }
        if c == ' ' || c == '\n' {
            if let Some(s) = word_script.take() {
                flush_word(&mut word, s, out)?;
            }
            prev_script = None;
            prev_char = None;
            // Avoid piling up doubled glue at text-run boundaries — but ONLY
            // for elastic (prose) spaces. A RIGID space (shrink == stretch == 0,
            // i.e. `code.satyh`'s `set-space-ratio (charwid/fs) 0. 0.`) is a
            // fixed-width verbatim column: SATySFi never collapses consecutive
            // ones, so the aligned source in a `+code` block keeps its spacing
            // (`| How       | I`, not the collapsed `| How | I`). Collapsing them
            // shortened code lines and let the port pack code blocks too tight.
            let rigid_space = ctx.space_shrink == 0.0 && ctx.space_stretch == 0.0;
            if rigid_space
                || !matches!(
                    out.last(),
                    Some(HorzBox::Pure(PureHorzBox::OuterEmpty { .. }))
                )
            {
                out.push(HorzBox::Pure(PureHorzBox::OuterEmpty {
                    natural: space_width,
                    // Upstream derives shrink/stretch directly as a ratio
                    // of `font_size` (`ctx.space_shrink`/`space_stretch`),
                    // NOT as a fraction of `space_width` — the previous
                    // `space_width * 0.25`/`* 0.5` was a port-invented
                    // approximation.
                    shrinkable: ctx.font_size * ctx.space_shrink,
                    stretchable: ctx.font_size * ctx.space_stretch,
                }));
            }
            continue;
        }
        let script = char_script(c);
        // Inter-script glue (`primitives.ml:517-524` `default_script_space_map`,
        // applied in `convertText.ml` `pure_space_between_scripts`): SATySFi's
        // default context inserts a `0.24 * size` space between a Latin run and
        // an adjacent CJK (Kana/Han) run — the space visible as "2 つ" /
        // "+easytable は" that the port otherwise packs tight ("2つ"). Emitted
        // at the boundary using `prev_script` (a CJK char resets `word_script`
        // via its UAX#14 discretionary, so this can't rely on `word_script`
        // alone). The glue is also an `is_break_point`, matching upstream (the
        // boundary is a legal break). See [`interscript_glue`] for why it is
        // RIGID even though `default_script_space_map` carries a triple.
        if let (Some(prev), Some(pc)) = (prev_script, prev_char) {
            if is_latin_cjk_boundary(prev, script) && !interscript_glue_suppressed(pc, c) {
                if let Some(s) = word_script.take() {
                    if !word.is_empty() {
                        flush_word(&mut word, s, out)?;
                    }
                }
                out.push(HorzBox::Pure(interscript_glue(ctx, prev, script)));
            }
        }
        if let Some(cur) = word_script {
            if cur != script {
                flush_word(&mut word, cur, out)?;
            }
        }
        word_script = Some(script);
        prev_script = Some(script);
        prev_char = Some(c);
        word.push(c);
        // Only non-ASCII text gets UAX#14 discretionaries: plain ASCII stays
        // on exactly today's space/newline-only splitter, so existing Latin
        // fixtures wrap identically (a real, tested divergence otherwise —
        // UAX#14 allows a break after a hyphen, which would fragment e.g.
        // "SATySFi-in-Rust" into three `InnerString`s instead of one,
        // changing the PDF content stream even though the zero-width
        // discretionaries between them render no differently when unchosen).
        // CJK and other non-ASCII scripts have no such existing behavior to
        // preserve, and are exactly where UAX#14 breaking is the whole point
        // (no interword glue at all otherwise, see `is_break_point`'s doc).
        // A soft hyphen (U+00AD) inside a run that the Knuth-Liang injection
        // above will consume (dictionary installed, Latin script) must NOT
        // be split here as an ordinary UAX#14 break-after point — doing so
        // would flush/fragment the word right at the soft hyphen before
        // `flush_word`'s hyphenation branch ever sees the whole word,
        // pre-empting `strip_soft_hyphens`'s explicit-break handling.
        // Instead let it accumulate into `word` like any other Latin letter.
        // Gated on the exact same `Some(_) && Latin` condition as that
        // branch, so `hyphen_dictionary == None` (or a non-Latin run)
        // reproduces exactly today's split-at-soft-hyphen behavior.
        let is_gated_soft_hyphen =
            c == '\u{ad}' && script == Script::Latin && ctx.hyphen_dictionary.is_some();
        // UAX#14 break opportunities apply to ALL text, ASCII included — that
        // is simply what upstream's line-break engine does (it runs over the
        // whole run with no script gate). Do NOT narrow this to non-ASCII, or
        // to the explicit hyphen — both approximations leave a load-bearing
        // gap:
        //
        //   - `+fig-center` (54.7pt, unbreakable) made the candidate widths jump
        //     clean over the feasible window — 400.32pt (ratio 2.72, dropped) to
        //     455.00pt (overfull) with nothing between — so the breaker fell back
        //     to a degenerate one-character line.
        //   - a `+code` line `…?:(drop) ?:(dropcolor)` ran 80pt past the column
        //     and clean off the paper, because the only break the port allowed
        //     was at a space, and breaking there left a rigid line 7.7pt short
        //     (dropped). UAX#14 grants a break between `:` and `(` — offset 2 of
        //     `?:(drop)…` — which is exactly where SATySFi breaks it.
        //
        // Cost: an ASCII run is now split into one `InnerString` per break
        // opportunity. Widths are unaffected (`measure_run` is purely additive,
        // see `make_inner_string_pure_box`), so this only changes how the text
        // is CHUNKED, not where any glyph lands.
        if !is_gated_soft_hyphen {
            let after = i + c.len_utf8();
            // The inter-chunk spacing between two DIRECTLY ADJACENT CJK
            // characters: `cjk_pair_space` folds `pure_space_between_classes` /
            // `adjacent_space` (`convertText.ml:101/194`) together with
            // `ideographic_single`'s compensating kerns (`convertText.ml:266`).
            //
            // The elastic part is the give a Japanese line justifies with.
            // Without it a CJK line's only give was whatever incidental Latin
            // spaces it happened to contain — a handful of points across a whole
            // line — so the breaker could neither fill to the column nor accept a
            // break that needed a hair of stretch.
            //
            // Only between two CJK characters: a CJK/Latin boundary is
            // `pure_space_between_scripts`'s job (the inter-script glue
            // above), and upstream falls through to `adjacent_space` only
            // once that has returned `None` (`space_between_chunks`,
            // `convertText.ml:220`).
            let is_cjk = |s| matches!(s, Script::HanIdeographic | Script::Kana);
            let next_char = text[after..].chars().next();
            let next_is_cjk = next_char.is_some_and(|nc| is_cjk(char_script(nc)));
            let pair = if is_cjk(script) && next_is_cjk {
                let nc = next_char.expect("checked");
                // `get_corrected_font_size` per SIDE (`convertText.ml:76-79`):
                // font size times the script's own `font_scheme` ratio. The
                // kerns and the JLreq class spaces scale against these; only
                // `adjacent_space` takes the raw size. See `cjk_pair_space`.
                let size_a = ctx.font_size * script_font(ctx, script).ratio;
                let size_b = ctx.font_size * script_font(ctx, char_script(nc)).ratio;
                Some(cjk_pair_space(
                    c,
                    size_a,
                    nc,
                    size_b,
                    ctx.font_size,
                    ctx.adjacent_stretch,
                ))
            } else {
                None
            };
            // `discretionary_if_breakable alw badns lphb`
            // (`convertText.ml:183-190`) — the ONE decision upstream makes at a
            // chunk boundary. The spacing is computed the same way either way;
            // only its container depends on whether UAX#14 grants a break:
            //
            //   AllowBreak    -> LBDiscretionary(badns, id, [glue], [], [])
            //   PreventBreak  -> LBPure(glue)
            //
            // The port used to emit the `AllowBreak` arm and *nothing* for
            // `PreventBreak`, so at every prohibited boundary — and in Japanese
            // prose that is one boundary in several, since LB13 forbids a break
            // before `、`/`。`/`」`/`)` and LB14 after `(`/`「` — a CJK line
            // carried give only at the subset of its boundaries that happened to
            // be breakable. A line with no give has to FILL its measure with
            // characters, which is part of why the port packs more per line than
            // SATySFi.
            match boundary[after] {
                Some(kind) => {
                    flush_word(&mut word, script, out)?;
                    word_script = None;
                    let mut no_break = Vec::new();
                    if let Some((n, sh, st)) = pair {
                        // The kern part is RIGID and must never be a break point,
                        // so it rides as a `FixedEmpty` rather than as glue.
                        if n != Length::ZERO {
                            no_break.push(PureHorzBox::FixedEmpty { width: n });
                        }
                        no_break.push(PureHorzBox::OuterEmpty {
                            natural: Length::ZERO,
                            shrinkable: sh,
                            stretchable: st,
                        });
                    }
                    out.push(HorzBox::Pure(PureHorzBox::Discretionary {
                        penalty: match kind {
                            BreakKind::Allowed => 0,
                            BreakKind::Mandatory => FORCED_BREAK_PENALTY,
                        },
                        pre_break: Vec::new(),
                        post_break: Vec::new(),
                        no_break,
                    }));
                }
                // The `PreventBreak` arm: `LBPure(glue)`, spelled as a
                // `Discretionary` whose every break slot is empty and whose
                // penalty is `NO_BREAK_PENALTY` (a bare `OuterEmpty` IS a
                // breakpoint in this box model, so a pure elastic box has no
                // other spelling).
                //
                // Only the ELASTIC half, deliberately — the one place this
                // port knowingly diverges from `discretionary_if_breakable`.
                // Landing the RIGID half too was written and MEASURED: it makes
                // the kern model ASYMMETRIC, since `cjk_pair_space`'s kern is a
                // property of the PAIR while upstream's is a property of the
                // CHARACTER, and the two agree only when BOTH neighbours are
                // CJK — `生成・変換` would get the nakaten's kern on both sides
                // while `(例:textbox` gets only its leading one (the trailing
                // side faces Latin, unreached by `cjk_pair_space`) — figbox's
                // largest intra-line divergence from upstream (mean |dx| on
                // that line 2.5pt -> 6.5pt).
                //
                // Completing it needs the per-character kerns at CJK<->Latin
                // boundaries and run edges too, which needs the source-
                // whitespace rewrite applied BEFORE `uax14_boundaries` rather
                // than during this loop (upstream's own order). Without that a
                // `。` before a deleted source newline gets its trailing kern
                // while the class space that pays it back is skipped (the
                // lookahead sees the newline, not the character after it), and
                // the layout-fidelity gate fails 12 ways. So the natural-width
                // bug the rigid half would fix — `」。`/`」、` a half-em too
                // wide, `末・雲` a quarter — stays exactly as open as before.
                None => {
                    if let Some((_, sh, st)) = pair {
                        if sh != Length::ZERO || st != Length::ZERO {
                            flush_word(&mut word, script, out)?;
                            word_script = None;
                            out.push(HorzBox::Pure(PureHorzBox::Discretionary {
                                penalty: NO_BREAK_PENALTY,
                                pre_break: Vec::new(),
                                post_break: Vec::new(),
                                no_break: vec![PureHorzBox::OuterEmpty {
                                    natural: Length::ZERO,
                                    shrinkable: sh,
                                    stretchable: st,
                                }],
                            }));
                        }
                    }
                }
            }
        }
    }
    match word_script {
        Some(s) => flush_word(&mut word, s, out),
        None => Ok(()),
    }
}

// ---- math conversion ----------------------
//
// Walks the already-elaborated `MathElem` tree straight into one
// `PureHorzBox::Math`, fixed-constant shift/scale (no MATH table).

/// Superscript/subscript size ratio, used ONLY as `MathC`'s fallback when
/// the current math font has no OpenType MATH table (`script_percent_scale_down
/// / 100`). Not read anywhere outside `MathC` — every layout site goes
/// through `MathC::script_scale`/`sup_shift_clamped`/etc. so a MATH-table
/// font gets the real per-font ratio instead.
const SCRIPT_SCALE: f64 = 0.7;
/// Superscript raise, as a fraction of `ctx.font_size` — `MathC`'s
/// no-MATH-table fallback (`superscript_shift_up` clamped per
/// `math.ml:527`). Not read outside `MathC`.
const SUP_SHIFT: f64 = 0.5;
/// Cramped-style superscript raise fallback — the no-MATH-table fallback
/// `sup_shift_clamped` uses in place of `SuperscriptShiftUpCramped` when there
/// is no real MATH table to read. Deliberately set EQUAL to `SUP_SHIFT`: every
/// checked-in fixture font has no MATH table, so cramped and uncramped
/// superscripts get the identical fallback shift there. Only a real MATH
/// font (host-installed, test-guarded) makes cramped/uncramped diverge.
const SUP_SHIFT_CRAMPED: f64 = SUP_SHIFT;
/// Subscript drop, as a fraction of `ctx.font_size` — `MathC`'s
/// no-MATH-table fallback (`subscript_shift_down` per
/// `math.ml:545`). Not read outside `MathC`.
const SUB_SHIFT: f64 = 0.25;
/// `MathC::frac_numer_shift`'s no-MATH-table fallback: a flat,
/// content-independent numerator raise, as a fraction of the fraction's own
/// LOCAL size (mirrors `sup_shift_clamped`'s None-branch style, which
/// also ignores ink extent with no MATH table). Not read outside `MathC`.
const FRAC_NUMER_SHIFT_FALLBACK: f64 = 0.33;
/// `MathC::frac_denom_shift`'s no-MATH-table fallback (mirrors
/// `FRAC_NUMER_SHIFT_FALLBACK`; applied as a downward, i.e. negative, shift
/// by the caller). Not read outside `MathC`.
const FRAC_DENOM_SHIFT_FALLBACK: f64 = 0.33;

/// MATH-table resolver: one query of `interp.metrics.math_constants(font)`
/// per laid-out math run, memoized here so every shift/scale/kern site in
/// that run reads the SAME `Option` instead of re-querying — and so a font
/// with no MATH table (every `Base14Metrics` call, and any TTF that lacks
/// one) transparently falls back to the flat pre-MATH-table constants
/// above. Fields are ratios of
/// the font size; callers multiply by whichever size is in scope
/// (`ctx.font_size` for the shift magnitudes — matching the pre-existing
/// "shift doesn't shrink with nesting" behavior these constants always had
/// — or the atom's own local `size` for glyph-relative queries like
/// `script_scale`/kerning).
struct MathC {
    c: Option<MathConstants>,
    /// `ctx.math_cramped` at the point this `MathC` was built — whether the
    /// current math sub-formula is laid out cramped. Consulted only by
    /// `sup_shift`/`sup_shift_clamped`, the sole positioning formula cramped
    /// changes in this port's feature set.
    cramped: bool,
}

impl MathC {
    fn of(interp: &Interp, ctx: &Context) -> Self {
        Self {
            c: interp.metrics.math_constants(ctx.math_font),
            cramped: ctx.math_cramped,
        }
    }

    /// Flat, unclamped superscript raise (`math.ml:527`'s `h_supstd` alone,
    /// no `math.ml:524-533` clamp) — the shape `layout_math_atom`'s callers
    /// need when no base/script ink extent is at hand yet.
    fn sup_shift(&self, s: Length) -> Length {
        match self.c {
            None => {
                s * if self.cramped {
                    SUP_SHIFT_CRAMPED
                } else {
                    SUP_SHIFT
                }
            }
            Some(c) => {
                s * if self.cramped {
                    c.superscript_shift_up_cramped
                } else {
                    c.superscript_shift_up
                }
            }
        }
    }

    /// Flat, unclamped subscript drop (mirrors `sup_shift`).
    fn sub_shift(&self, s: Length) -> Length {
        self.c
            .map(|c| s * c.subscript_shift_down)
            .unwrap_or(s * SUB_SHIFT)
    }

    /// `script_percent_scale_down / 100`, or the fixed `SCRIPT_SCALE`
    /// fallback. Nesting-level scale gap: upstream
    /// switches to `script_script_percent_scale_down` one level deeper;
    /// this port applies `script_scale_down` uniformly at every depth.
    fn script_scale(&self) -> f64 {
        self.c.map(|c| c.script_scale_down).unwrap_or(SCRIPT_SCALE)
    }

    /// `math.ml`'s `h_bar` (axis height): the vertical center math content
    /// (fraction bars, `get-axis-height`) aligns to. Falls back to a fixed
    /// `0.25` ratio with no MATH table.
    fn axis(&self, s: Length) -> Length {
        self.c.map(|c| s * c.axis_height).unwrap_or(s * 0.25)
    }

    /// `math.ml:524-533` `superscript_baseline_height`, clamped: the
    /// MAGNITUDE of the upward shift a superscript needs given the base's
    /// own ink height (`h_base`, a positive extent above ITS baseline) and
    /// the superscript's own ink depth (`d_sup`, a positive extent below
    /// ITS baseline — i.e. `MathGlyph.height`/`.depth`, not upstream's
    /// signed `Length.negate`d fields). Falls back to the flat `sup_shift`
    /// (ignoring `h_base`/`d_sup`) when there's no MATH table, so base-14
    /// output is untouched by this clamp.
    fn sup_shift_clamped(&self, s: Length, h_base: Length, d_sup: Length) -> Length {
        match self.c {
            None => self.sup_shift(s),
            Some(c) => {
                let shift_up = if self.cramped {
                    c.superscript_shift_up_cramped
                } else {
                    c.superscript_shift_up
                };
                let cand1 = s * shift_up;
                let cand2 = h_base - s * c.superscript_baseline_drop_max;
                let cand3 = s * c.superscript_bottom_min + d_sup;
                cand1.max(cand2).max(cand3)
            }
        }
    }

    /// `math.ml:545-553` `subscript_baseline_depth`, clamped: the MAGNITUDE
    /// of the downward shift, given the base's own ink depth (`d_base`) and
    /// the subscript's own ink height (`h_sub`). Mirrors
    /// `sup_shift_clamped`'s fallback behavior.
    fn sub_shift_clamped(&self, s: Length, d_base: Length, h_sub: Length) -> Length {
        match self.c {
            None => self.sub_shift(s),
            Some(c) => {
                let cand1 = s * c.subscript_shift_down;
                let cand2 = d_base + s * c.subscript_baseline_drop_min;
                let cand3 = h_sub - s * c.subscript_top_max;
                cand1.max(cand2).max(cand3)
            }
        }
    }

    /// `math.ml:562-573` `correct_script_baseline_heights`: when a base
    /// carries BOTH a subscript and a superscript, nudge the two
    /// already-clamped shift magnitudes apart so their ink keeps at least
    /// `sub_superscript_gap_min` clearance. `d_sup`/`h_sub` are the same ink
    /// extents `sup_shift_clamped`/`sub_shift_clamped` took; `sup`/`sub` are
    /// their (already clamped) outputs. A no-op when there's no MATH table
    /// — the flat fallback shifts are never additionally corrected, so
    /// base-14 output stays exactly `(sup, sub)`.
    fn correct_script_gap(
        &self,
        s: Length,
        d_sup: Length,
        h_sub: Length,
        sup: Length,
        sub: Length,
    ) -> (Length, Length) {
        let Some(c) = self.c else {
            return (sup, sub);
        };
        let gap_min = s * c.sub_superscript_gap_min;
        let gap = (sup - d_sup) - (h_sub - sub);
        if gap < gap_min {
            let corr = (gap_min - gap) * 0.5;
            (sup + corr, sub + corr)
        } else {
            (sup, sub)
        }
    }

    /// `math.ml:596-602` `upper_limit_baseline_height`, clamped: the
    /// MAGNITUDE of the upward shift for an `\overset`-like upper limit,
    /// given the base's own ink height (`h_base`) and the limit content's
    /// own ink depth (`d_up`). Falls back to the flat `sup_shift` (same
    /// shape upstream's superscript raise uses) with no MATH table.
    fn upper_limit_shift(&self, s: Length, h_base: Length, d_up: Length) -> Length {
        match self.c {
            None => self.sup_shift(s),
            Some(c) => {
                let cand1 = h_base + s * c.upper_limit_baseline_rise_min;
                let cand2 = h_base + s * c.upper_limit_gap_min + d_up;
                cand1.max(cand2)
            }
        }
    }

    /// `math.ml:605-611` `lower_limit_baseline_depth`, clamped: mirrors
    /// `upper_limit_shift` for a lower limit, given the base's own ink
    /// depth (`d_base`) and the limit content's own ink height (`h_low`).
    fn lower_limit_shift(&self, s: Length, d_base: Length, h_low: Length) -> Length {
        match self.c {
            None => self.sub_shift(s),
            Some(c) => {
                let cand1 = d_base + s * c.lower_limit_baseline_drop_min;
                let cand2 = d_base + s * c.lower_limit_gap_min + h_low;
                cand1.max(cand2)
            }
        }
    }

    /// `math.ml:982-991` `horz_fraction_bar`'s rule thickness (also
    /// `radical_bar_metrics`'s `t_bar` — both are "the same generic rule
    /// ratio" in the pre-MATH-table fixed-constant world):
    /// `fraction_rule_thickness`, or the fixed `0.04` fallback. Multiplied
    /// by the ambient LOCAL nesting `size` (not `ctx.font_size` — a
    /// fraction/radical's own metrics DO shrink with nesting, matching
    /// upstream's `FontInfo.actual_math_font_size`, unlike the sup/sub shift
    /// constants' documented `ctx.font_size` simplification above).
    fn frac_rule(&self, s: Length) -> Length {
        self.c
            .map(|c| s * c.fraction_rule_thickness)
            .unwrap_or(s * 0.04)
    }

    /// `math.ml:574-583` `numerator_baseline_height`, clamped: the
    /// MAGNITUDE of the upward shift a numerator needs given its own ink
    /// depth (`d_numer`, a positive extent below ITS baseline — this port's
    /// convention, see `sup_shift_clamped`'s doc comment; upstream's
    /// `Length.negate d_numer` becomes a plain ADD of `d_numer` here, not a
    /// subtract — getting this sign wrong would shrink the raise for a
    /// deeper numerator instead of growing it, overlapping the bar). Falls
    /// back to a flat, content-independent ratio with no MATH table
    /// (mirrors `sup_shift_clamped`'s None-branch style).
    fn frac_numer_shift(&self, s: Length, d_numer: Length) -> Length {
        match self.c {
            None => s * FRAC_NUMER_SHIFT_FALLBACK,
            Some(c) => {
                let std = s * c.fraction_numer_shift_up;
                let gap =
                    self.axis(s) + self.frac_rule(s) * 0.5 + s * c.fraction_numer_gap_min + d_numer;
                std.max(gap)
            }
        }
    }

    /// `math.ml:585-594` `denominator_baseline_depth`, clamped: mirrors
    /// `frac_numer_shift`. Returns the SIGNED (already-negative) drop the
    /// caller applies straight to `dy` — unlike the sup/sub methods'
    /// positive-magnitude-then-caller-negates convention — because
    /// upstream's own `d_denombl` is signed too, so there's no sign flip to
    /// make here (and `h_denom`, a HEIGHT not a depth, is subtracted
    /// directly, matching upstream's un-negated use of it).
    fn frac_denom_shift(&self, s: Length, h_denom: Length) -> Length {
        match self.c {
            None => -(s * FRAC_DENOM_SHIFT_FALLBACK),
            Some(c) => {
                let std = -(s * c.fraction_denom_shift_down);
                let gap =
                    self.axis(s) - self.frac_rule(s) * 0.5 - s * c.fraction_denom_gap_min - h_denom;
                std.min(gap)
            }
        }
    }

    /// `math.ml:620-626` `radical_bar_metrics`: `(h_bar, t_bar, l_extra)` —
    /// the bar's height above baseline (radicand height + gap, so the bar
    /// always clears the radicand with no separate raise needed), its rule
    /// thickness, and the extra ascender the WHOLE radical run reports
    /// above the bar. Fallback ratios (no MATH table):
    /// vertical_gap=0.06, rule=0.04 (same fixed ratio `frac_rule` falls back
    /// to), extra_ascender=0.06.
    fn radical_bar_metrics(&self, s: Length, h_cont: Length) -> (Length, Length, Length) {
        match self.c {
            Some(c) => (
                h_cont + s * c.radical_vertical_gap,
                s * c.radical_rule_thickness,
                s * c.radical_extra_ascender,
            ),
            None => (h_cont + s * 0.06, s * 0.04, s * 0.06),
        }
    }
}

/// The ink height/depth of an already-laid-out run, as positive magnitudes
/// (`MathGlyph.dy` is signed, up-positive; `.height`/`.depth` are always
/// non-negative extents from EACH glyph's own local baseline) — the same
/// aggregate `read_math`/`layout_math_value` compute for a whole
/// `PureHorzBox::Math`, reused here per sub-run so `MathC`'s clamp formulas
/// have an `h_base`/`d_sup`/etc to clamp against. Empty input -> `(ZERO,
/// ZERO)` (an empty base/script contributes no clamp pressure).
fn glyphs_extent(glyphs: &[MathGlyph]) -> (Length, Length) {
    let mut height = Length::ZERO;
    let mut depth = Length::ZERO;
    for g in glyphs {
        height = height.max(g.dy + g.height);
        depth = depth.max(g.depth - g.dy);
    }
    (height, depth)
}

/// `glyphs_extent` plus `rules`' own bounding boxes folded in — exactly the
/// aggregate `layout_math_value` computes for a whole `PureHorzBox::Math`
/// (see that function's doc comment on why a bare `Fill`, e.g. a fraction
/// bar/radical sign, needs its own bbox folded in rather than being silently
/// undercounted). Also reused to size a stretchy delimiter to its
/// enclosed run's REAL ink (glyphs + any drawn rules), not just its glyphs.
///
/// This — NOT bare `glyphs_extent` — is what every `layout_math_value` arm
/// must use for a sub-run's `h_base`/`d_base`/`d_sup`/`h_sub`/`d_numer`/…,
/// because it is upstream's `convert_to_low` return value: each arm's
/// `(_, h, d, _, _)` is the whole sub-run's `h_whole`/`d_whole`, and a
/// `MathParen`'s is `max(hC, hL, hR)` / `min(dC, dL, dR)` over the
/// DELIMITER boxes too (`math.ml:908-909`). A `math.satyh` delimiter is
/// `inline-graphics` ink, so it lands in `rules` and in nothing else: with
/// `glyphs_extent` a `\paren{…}` base reported only its CONTENT's height,
/// which is smaller than the delimiter it just sized, and
/// `sup_shift_clamped`'s `h_base - SuperscriptBaselineDropMax` candidate
/// therefore lost when upstream's wins. `${\paren{\frac{1}{1-v}}^{2}}` at
/// 12pt: `h_base` 16.116pt (content) vs upstream's 17.316pt (`hgtaxis +
/// halflen`, the paren's own declared box), i.e. a 1.2pt-too-low superscript
/// — `layout-tests/probes/math_box_extent.saty` row 4. The bbox of
/// `math.satyh`'s `paren-left`/`angle-left`/… path is exactly that declared
/// box (its extreme points ARE `ycenter ± halflen`), so folding the rule in
/// reproduces upstream's number rather than approximating it.
fn inner_ink_extent(glyphs: &[MathGlyph], rules: &[GraphicsElem]) -> (Length, Length) {
    let (mut height, mut depth) = glyphs_extent(glyphs);
    for r in rules {
        // `graphics_bbox` is now `Option` (`None` for an empty `Group`
        // — unreachable here under 0.0.6 math rules, but the fold is
        // version-blind and correct either way: a `None` rule contributes
        // nothing to the ink extent).
        if let Some(((_, min_y), (_, max_y))) = graphics_bbox(r) {
            height = height.max(max_y);
            depth = depth.max(-min_y);
        }
    }
    (height, depth)
}

/// `math.ml:1040-1075`'s superscript kern tuck: the italic correction of
/// the base's TRAILING glyph plus the two corner kerns — the base's
/// top-right sampled at the height the raised superscript's ink starts
/// (`l_base = sup_shift - d_sup`, `superscript_correction_heights`'s first
/// component), and the superscript's own bottom-left sampled (at the
/// superscript's OWN size) at the height the base's ink ends (`l_sup =
/// h_base - sup_shift`, that function's second component) — the extra
/// horizontal gap upstream inserts between a base and a raised superscript
/// so slanted glyphs (an italic integral, say) don't collide with what's
/// stacked above them. `size`/`script_size` are the local sizes the base/
/// script glyphs were actually measured at (NOT `ctx.font_size`, unlike the
/// shift magnitude — these feed a design-units conversion that must match
/// each glyph's own em square). Every lookup misses to `Length::ZERO` (no
/// MATH table, no glyph, no kern data, ...), so base-14 output is
/// untouched: this returns exactly `Length::ZERO` whenever `ctx.math_font`
/// has no MATH table.
#[allow(clippy::too_many_arguments)]
fn superscript_kern(
    interp: &Interp,
    ctx: &Context,
    size: Length,
    script_size: Length,
    base_glyphs: &[MathGlyph],
    script_glyphs: &[MathGlyph],
    sup_shift: Length,
    h_base: Length,
    d_sup: Length,
) -> Length {
    let font = ctx.math_font;
    let last_base = base_glyphs.last().and_then(|g| g.text.chars().last());
    let first_script = script_glyphs.first().and_then(|g| g.text.chars().next());
    let l_italic = last_base
        .and_then(|c| interp.metrics.italic_correction(font, c, size))
        .unwrap_or(Length::ZERO);
    let l_base = sup_shift - d_sup;
    let l_sup = h_base - sup_shift;
    let l_kernbase = last_base
        .and_then(|c| {
            interp
                .metrics
                .math_kern(font, c, size, MathCorner::TopRight, l_base)
        })
        .unwrap_or(Length::ZERO);
    let l_kernsup = first_script
        .and_then(|c| {
            interp
                .metrics
                .math_kern(font, c, script_size, MathCorner::BottomLeft, l_sup)
        })
        .unwrap_or(Length::ZERO);
    l_italic + l_kernbase + l_kernsup
}

/// A minimal stand-in for v0.0.6's per-codepoint math-class table
/// (`primitives.cppo.ml`) + `normalize_math_kind` (`math.ml:240`) — just
/// enough for `${a+b}` to get binary-operator spacing. Letters/digits/
/// everything else default to `Ord`.
fn ascii_math_kind(c: char) -> MathKind {
    match c {
        '+' | '-' | '*' | '/' => MathKind::Bin,
        '=' | '<' | '>' => MathKind::Rel,
        ',' | ';' | ':' | '.' => MathKind::Punct,
        _ => MathKind::Ord,
    }
}

/// `normalize_math_kind` (`math.ml:238-277`): a BINARY atom whose neighbours
/// make it unary is really an ORDINARY one, and gets none of `Bin`'s spacing.
/// Upstream demotes on `mkprev in {Op, Bin, Rel, Open, Punct}` or `mknext in
/// {Rel, Close, Punct}`; `MathEnd` — the sentinel `math.ml:1270` passes for
/// both ends of a formula — is included here on the LEFT, which is what makes
/// `${-------}` set seven tight glyphs rather than a leading binary minus
/// followed by six ordinaries, and what keeps `${-N, -N + 1}`'s minus signs
/// tight against their operands the way the reference sets them. Every other
/// class passes through unchanged.
///
/// Reachable at all only since the math lexer stopped gluing a run of symbols
/// into one token: before that a `--` was a single `Ord` atom and there was no
/// adjacent pair to normalize.
fn normalize_math_kind(prev: MathKind, next: MathKind, raw: MathKind) -> MathKind {
    if raw != MathKind::Bin {
        return raw;
    }
    let unary_left = matches!(
        prev,
        MathKind::Op
            | MathKind::Bin
            | MathKind::Rel
            | MathKind::Open
            | MathKind::Punct
            | MathKind::End
    );
    let unary_right = matches!(next, MathKind::Rel | MathKind::Close | MathKind::Punct);
    if unary_left || unary_right {
        MathKind::Ord
    } else {
        MathKind::Bin
    }
}

/// The six inter-atom space ratios `space_between_math_kinds` multiplies the
/// math font size by — `primitives.cppo.ml:528-533`'s `space_math_bin`, `_rel`,
/// `_op`, `_punct`, `_inner`, `_prefix`. Upstream keeps them as a
/// natural/shrink/stretch triple on `HorzBox.context_main` that no v0.0.6
/// primitive writes, and this port's math spacer emits a fixed kern rather than
/// glue, so only the natural component is needed.
const SPACE_MATH_BIN: f64 = 0.25;
const SPACE_MATH_REL: f64 = 0.375;
const SPACE_MATH_OP: f64 = 0.125;
const SPACE_MATH_PUNCT: f64 = 0.125;
const SPACE_MATH_INNER: f64 = 0.125;
const SPACE_MATH_PREFIX: f64 = 0.125;

/// `space_between_math_kinds` (`math.ml:319-410`), arm for arm and in the same
/// ORDER: OCaml's `match` is first-match, so `(Punct, Close)` must reach the
/// `(Punct, _)` arm and not `(_, Close)`. Every ratio is
/// `primitives.cppo.ml:528-533`'s.
///
/// `in_script` is `not (MathContext.is_in_base_level mathctx)` — inside a
/// sub/superscript upstream suppresses the whole table except the five operator
/// pairs. `font_size` is `FontInfo.actual_math_font_size mathctx`, the size of
/// the LEVEL being laid out and not the ambient base size, which is why callers
/// pass their local `size`.
///
/// Upstream's `space_correction` channel is pinned at `NoSpace` here, so the
/// three arms that read it — `(_, Close)`, `(Ord|Prefix, Open)` and the
/// fallthrough — all yield nothing: exact for `NoSpace`, and the conservative
/// reading of a trailing italics correction and the MATH table's
/// `space_after_script`.
fn space_before(prev: MathKind, cur: MathKind, in_script: bool, font_size: Length) -> Length {
    use MathKind::*;
    let ratio = if in_script {
        match (prev, cur) {
            (Op, Ord) | (Ord, Op) | (Op, Op) | (Close, Op) | (Inner, Op) => SPACE_MATH_OP,
            _ => return Length::ZERO,
        }
    } else {
        match (prev, cur) {
            (Punct, _) => SPACE_MATH_PUNCT,

            (Inner, Ord) | (Inner, Open) | (Inner, Punct) | (Inner, Inner) | (Ord, Inner)
            | (Prefix, Inner) | (Close, Inner) => SPACE_MATH_INNER,

            // `corr = NoSpace`: no italics correction to append.
            (_, Close) => return Length::ZERO,

            // `corr = NoSpace`: no `space_after_script` either.
            (Ord, Open) | (Prefix, Open) => return Length::ZERO,

            (Bin, Ord) | (Bin, Prefix) | (Bin, Op) | (Bin, Open) | (Bin, Inner) | (Ord, Bin)
            | (Close, Bin) | (Inner, Bin) => SPACE_MATH_BIN,

            (Rel, Ord) | (Rel, Op) | (Rel, Inner) | (Rel, Open) | (Rel, Prefix) | (Ord, Rel)
            | (Op, Rel) | (Inner, Rel) | (Close, Rel) => SPACE_MATH_REL,

            (Op, Ord) | (Op, Op) | (Op, Inner) | (Op, Prefix) | (Ord, Op) | (Close, Op)
            | (Inner, Op) => SPACE_MATH_OP,

            (Ord, Prefix) | (Inner, Prefix) => SPACE_MATH_PREFIX,

            (_, End) | (End, _) => return Length::ZERO,

            _ => return Length::ZERO,
        }
    };
    font_size * ratio
}

/// `not (MathContext.is_in_base_level mathctx)` for the `(ctx, size)` pair this
/// port threads instead of upstream's `math_context`. BOTH witnesses are
/// needed: `layout_math_atom`'s script arms shrink only the local `size` and
/// pass the ambient `ctx` down, while `enter_script` (`attach_scripts`,
/// `read-math`'s `Math::WithContext`) advances `Context::math_script_level` and
/// scales `font_size` together — so a `WithContext` captured under a script
/// arrives with `size == ctx.font_size` and is recognisable only by its level.
fn math_in_script(ctx: &Context, size: Length) -> bool {
    size != ctx.font_size || ctx.math_script_level != MathScriptLevel::Base
}

/// FontKey a math glyph c@size should measure/emit in: dedicated ctx.math_font
/// when it can render c, else text ctx.font. The one place math diverges from
/// text font; the MATH-table slice keys lookups on the same returned FontKey.
fn math_glyph_font(interp: &Interp, ctx: &Context, c: char, size: Length) -> FontKey {
    if interp.metrics.advance(ctx.math_font, c, size).is_some() {
        ctx.math_font
    } else {
        ctx.font
    }
}

/// gap-5 metrics-probe predicate, now math-font-aware.
fn math_char_available(interp: &Interp, ctx: &Context, c: char, size: Length) -> bool {
    interp.metrics.advance(ctx.math_font, c, size).is_some()
        || interp.metrics.advance(ctx.font, c, size).is_some()
}

/// Measure one math character at `size` under `math_glyph_font(ctx, c)` and
/// push it as a `MathGlyph` at the running `*x` (`dy = 0`; callers shift
/// scripts afterward), advancing `*x` past it.
fn push_char_glyph(
    interp: &mut Interp,
    ctx: &Context,
    c: char,
    size: Length,
    out: &mut Vec<MathGlyph>,
    x: &mut Length,
) -> Result<(), EvalError> {
    let font = math_glyph_font(interp, ctx, c, size);
    // `fontInfo.ml:379-383`: a math glyph below base level is set in the font's
    // `ssty` variant — a purpose-drawn form with its own advance, not the base
    // glyph shrunk (see `FontMetrics::math_script_variant`). Any miss falls
    // through to the base glyph unchanged.
    if math_in_script(ctx, size) {
        if let Some(v) = interp.metrics.math_script_variant(font, c, size) {
            out.push(MathGlyph {
                info: HorzStringInfo {
                    font,
                    size,
                    rising: Length::ZERO,
                    color: ctx.text_color,
                },
                text: c.to_string(),
                gid: Some(v.gid),
                dx: *x,
                dy: Length::ZERO,
                width: v.advance,
                height: v.height,
                depth: v.depth,
            });
            *x += v.advance;
            return Ok(());
        }
    }
    // Graceful degradation for a math character neither the math font nor the
    // text font can render (e.g. `⋯` U+22EF under the bundled faces): fall back
    // to a half-em advance and let the glyph degrade to `.notdef` at render
    // time (`gid: None`, resolved by `cid::encode_glyph_run`), exactly as the
    // text path does in `measure_run` — a missing glyph must not abort the whole
    // document. This only ever changes behavior for a glyph that would otherwise
    // be a hard error, so covered-glyph documents stay byte-identical.
    let advance = interp.metrics.advance(font, c, size).unwrap_or(size * 0.5);
    let (height, depth) = math_glyph_vextent(interp, font, c, size);
    out.push(MathGlyph {
        info: HorzStringInfo {
            font,
            size,
            rising: Length::ZERO,
            color: ctx.text_color,
        },
        text: c.to_string(),
        gid: None,
        dx: *x,
        dy: Length::ZERO,
        width: advance,
        height,
        depth,
    });
    *x += advance;
    Ok(())
}

/// One math glyph's vertical ink extent, the way upstream measures it:
/// `FontFormat.get_math_glyph_metrics` (`fontFormat.ml:2257-2264`) takes the
/// glyph's OWN bounding box and truncates each side towards the baseline —
/// `hgt = truncate_negative ymax` (so a wholly-subscripted glyph reports
/// height 0, never a negative height) and `dpt = truncate_positive ymin` (so a
/// glyph entirely above the baseline, `*` at ymin=+320, reports depth 0).
///
/// This is NOT the font-level ascender/descender:
/// `MathC::sub_shift_clamped`/`sup_shift_clamped` clamp against these extents
/// (`math.ml:527-552`), so feeding them latinmodern-math's hhea ascender
/// (806/1000 em) and descender (194/1000 em) instead of `m`'s real ink box
/// (ymax 442, ymin 0) made the `superscript_baseline_drop_max` /
/// `subscript_baseline_drop_min` candidate win every time. At 12pt that is
/// `9.672 - 3.0 = 6.672pt` of superscript rise where upstream's own clamp
/// picks `SuperscriptShiftUp = 4.356pt` (plus a gap correction, 4.525pt), and
/// `2.328 + 2.4 = 4.728pt` of subscript drop where upstream picks
/// `SubscriptShiftDown = 2.964pt` — measured by `layout-tests/probes/
/// math_script_drop.saty`.
///
/// Falls back to `ascender`/`descender` when the provider exposes no per-glyph
/// bbox (base-14 metrics, test stubs).
fn math_glyph_vextent(interp: &Interp, font: FontKey, c: char, size: Length) -> (Length, Length) {
    match interp.metrics.glyph_vextent(font, c, size) {
        Some((h, d)) => (h.max(Length::ZERO), d.max(Length::ZERO)),
        None => (
            interp.metrics.ascender(font, size),
            interp.metrics.descender(font, size),
        ),
    }
}

/// `push_char_glyph`'s big-operator sibling: try the v0.0.6 `BigOp`
/// vertical variant (`fontInfo.ml:386-401` — the 2nd `MathVariants` record if
/// present, else the 1st) unconditionally. Upstream's own guard is
/// `is_in_display && is_big`, but `math.ml`'s `convert_math_char` hardcodes
/// `is_in_display = true`, so it reduces to just `is_big` — a big operator
/// grows even inline, even at script size, exactly like upstream; the port
/// tracks no display/inline distinction and needs none here. On any miss (no
/// MATH table, no vertical construction for `c`, or a variant/hmtx/bbox
/// lookup failure — every base-14 call, always) falls back to
/// `push_char_glyph`, byte-identical to the base output.
fn push_big_char_glyph(
    interp: &mut Interp,
    ctx: &Context,
    c: char,
    size: Length,
    out: &mut Vec<MathGlyph>,
    x: &mut Length,
) -> Result<(), EvalError> {
    let font = math_glyph_font(interp, ctx, c, size);
    match interp
        .metrics
        .math_vertical_variant(font, c, size, VertVariantPolicy::BigOp)
    {
        Some(v) => {
            out.push(MathGlyph {
                info: HorzStringInfo {
                    font,
                    size,
                    rising: Length::ZERO,
                    color: ctx.text_color,
                },
                text: c.to_string(),
                gid: Some(v.gid),
                dx: *x,
                dy: Length::ZERO,
                width: v.advance,
                height: v.height,
                depth: v.depth,
            });
            *x += v.advance;
            Ok(())
        }
        None => push_char_glyph(interp, ctx, c, size, out, x),
    }
}

/// One stretchy-delimiter glyph: the smallest `MathVariants`
/// record whose `advance_measurement` covers `target` (else the largest
/// record — `VertVariantPolicy::AtLeast`), centered on the math axis
/// (`dy = axis - (h - d) / 2`; y-**up**, same sign convention as
/// `shift_and_append`'s `dy_shift` — see that function's doc comment on the
/// mirroring trap a flipped sign causes). Falls back to the baseline
/// base glyph (`push_char_glyph`) when there's no vertical construction.
fn push_delimiter_glyph(
    interp: &mut Interp,
    ctx: &Context,
    c: char,
    size: Length,
    target: Length,
    axis: Length,
    out: &mut Vec<MathGlyph>,
    x: &mut Length,
) -> Result<(), EvalError> {
    let font = math_glyph_font(interp, ctx, c, size);
    let variant =
        interp
            .metrics
            .math_vertical_variant(font, c, size, VertVariantPolicy::AtLeast(target));
    // `GlyphAssembly`: if even the largest discrete variant's own ink
    // extent (`height + depth`) still doesn't span `target` — a delimiter
    // taller than anything the font enumerates as a prepared variant — grow
    // it from the assembly parts instead (stack top + repeated extenders +
    // bottom). `None` (no MATH table / no assembly / base-14) leaves the
    // discrete/base path below byte-identical.
    let discrete_covers = variant
        .map(|v| (v.height + v.depth).0 >= target.0)
        .unwrap_or(false);
    if !discrete_covers {
        if let Some(parts) = interp.metrics.math_vertical_assembly(font, c, size, target) {
            if !parts.is_empty() {
                // Horizontal advance of the delimiter column: the largest
                // discrete variant's own hmtx advance when we have one (the
                // parts share the same nominal delimiter width), else the base
                // glyph's advance.
                let hadv = match variant {
                    Some(v) => v.advance,
                    None => interp
                        .metrics
                        .advance(font, c, size)
                        .unwrap_or(Length::ZERO),
                };
                // Total vertical extent of the stacked assembly (local, from
                // the bottom part's baseline at 0), then center it on the math
                // axis exactly like the discrete path centers a variant's ink.
                let total = parts
                    .last()
                    .map(|(_, dy, adv)| *dy + *adv)
                    .unwrap_or(Length::ZERO);
                let base_off = axis - total * 0.5;
                for (i, (gid, dy_local, adv)) in parts.iter().enumerate() {
                    out.push(MathGlyph {
                        info: HorzStringInfo {
                            font,
                            size,
                            rising: Length::ZERO,
                            color: ctx.text_color,
                        },
                        text: c.to_string(),
                        gid: Some(*gid),
                        dx: *x,
                        dy: base_off + *dy_local,
                        // Only the first part carries the column's horizontal
                        // width (all parts are stacked in the SAME x column);
                        // its baseline-relative extent is the part's vertical
                        // advance (up), so `glyphs_extent` folds the whole
                        // stacked column into the box's height/depth.
                        width: if i == 0 { hadv } else { Length::ZERO },
                        height: *adv,
                        depth: Length::ZERO,
                    });
                }
                *x += hadv;
                return Ok(());
            }
        }
    }
    match variant {
        Some(v) => {
            let dy = axis - (v.height - v.depth) * 0.5;
            out.push(MathGlyph {
                info: HorzStringInfo {
                    font,
                    size,
                    rising: Length::ZERO,
                    color: ctx.text_color,
                },
                text: c.to_string(),
                gid: Some(v.gid),
                dx: *x,
                dy,
                width: v.advance,
                height: v.height,
                depth: v.depth,
            });
            *x += v.advance;
            Ok(())
        }
        None => push_char_glyph(interp, ctx, c, size, out, x),
    }
}

/// Lay out `elems` in isolation (its own local `x` starting at 0, its own
/// spacing state) at `size` — the shape a `Sup`/`Sub`/`Primes` script needs
/// before its glyphs get re-anchored onto the base's running `x` and
/// shifted by the caller. `size` is the caller's `MathC::script_scale`-
/// derived script size (real MATH-table ratio when available, `SCRIPT_SCALE`
/// otherwise). Returns the glyphs (still at local coordinates) and
/// the script's total width.
fn layout_script(
    interp: &mut Interp,
    ctx: &Context,
    elems: &[MathElem],
    size: Length,
) -> Result<(Vec<MathGlyph>, Length), EvalError> {
    let mut glyphs = Vec::new();
    let mut x = Length::ZERO;
    let mut last_kind: Option<MathKind> = None;
    for e in elems {
        layout_math_elem(interp, ctx, e, size, &mut glyphs, &mut x, &mut last_kind)?;
    }
    Ok((glyphs, x))
}

/// Re-anchor an isolated script's glyphs (`layout_script`'s output) onto the
/// base's running `*x`, adding `dy_shift` to every glyph's vertical offset —
/// `dy_shift > 0` raises (superscript), `< 0` lowers (subscript). Advances
/// `*x` past the whole script.
fn place_script(
    out: &mut Vec<MathGlyph>,
    x: &mut Length,
    script_glyphs: Vec<MathGlyph>,
    script_width: Length,
    dy_shift: Length,
) {
    let base_x = *x;
    for mut g in script_glyphs {
        g.dx = base_x + g.dx;
        g.dy = g.dy + dy_shift;
        out.push(g);
    }
    *x = base_x + script_width;
}

/// The recursive core of `read_math`: lays out one `MathElem` into `out`,
/// advancing `*x` and threading `*last_kind` (the trailing `MathKind` of
/// whatever was laid out immediately before, for `space_before`) through
/// siblings — the analog of `convert_to_low` + `horz_of_low_math`
/// (`math.ml:753`/`:1016`), fused and with fixed constants.
fn layout_math_elem(
    interp: &mut Interp,
    ctx: &Context,
    elem: &MathElem,
    size: Length,
    out: &mut Vec<MathGlyph>,
    x: &mut Length,
    last_kind: &mut Option<MathKind>,
) -> Result<(), EvalError> {
    match elem {
        MathElem::Chars(s) => {
            for c in s.chars() {
                let kind = ascii_math_kind(c);
                if let Some(prev) = *last_kind {
                    *x += space_before(prev, kind, math_in_script(ctx, size), size);
                }
                push_char_glyph(interp, ctx, c, size, out, x)?;
                *last_kind = Some(kind);
            }
            Ok(())
        }
        MathElem::Group(elems) => {
            for e in elems {
                layout_math_elem(interp, ctx, e, size, out, x, last_kind)?;
            }
            Ok(())
        }
        MathElem::Sup(base, script) => {
            let base_start = out.len();
            layout_math_elem(interp, ctx, base, size, out, x, last_kind)?;
            let mc = MathC::of(interp, ctx);
            let script_size = ctx.font_size * mc.script_scale();
            let (h_base, _) = glyphs_extent(&out[base_start..]);
            let (script_glyphs, script_width) = layout_script(interp, ctx, script, script_size)?;
            let (_, d_sup) = glyphs_extent(&script_glyphs);
            let sup_shift = mc.sup_shift_clamped(ctx.font_size, h_base, d_sup);
            let kern = superscript_kern(
                interp,
                ctx,
                size,
                script_size,
                &out[base_start..],
                &script_glyphs,
                sup_shift,
                h_base,
                d_sup,
            );
            *x += kern;
            place_script(out, x, script_glyphs, script_width, sup_shift);
            Ok(())
        }
        MathElem::Sub(base, script) => {
            let base_start = out.len();
            layout_math_elem(interp, ctx, base, size, out, x, last_kind)?;
            let mc = MathC::of(interp, ctx);
            let script_size = ctx.font_size * mc.script_scale();
            let (_, d_base) = glyphs_extent(&out[base_start..]);
            let (script_glyphs, script_width) = layout_script(interp, ctx, script, script_size)?;
            let (h_sub, _) = glyphs_extent(&script_glyphs);
            let sub_shift = mc.sub_shift_clamped(ctx.font_size, d_base, h_sub);
            place_script(out, x, script_glyphs, script_width, -sub_shift);
            Ok(())
        }
        MathElem::Primes(base, n) => {
            let base_start = out.len();
            layout_math_elem(interp, ctx, base, size, out, x, last_kind)?;
            let mc = MathC::of(interp, ctx);
            let script_size = ctx.font_size * mc.script_scale();
            let (h_base, _) = glyphs_extent(&out[base_start..]);
            // Upstream desugars primes to exactly this: a superscript of `n`
            // U+2032 `′` chars (`parser.mly:1082`).
            let primes = vec![MathElem::Chars("\u{2032}".repeat(*n))];
            let (script_glyphs, script_width) = layout_script(interp, ctx, &primes, script_size)?;
            let (_, d_sup) = glyphs_extent(&script_glyphs);
            let sup_shift = mc.sup_shift_clamped(ctx.font_size, h_base, d_sup);
            let kern = superscript_kern(
                interp,
                ctx,
                size,
                script_size,
                &out[base_start..],
                &script_glyphs,
                sup_shift,
                h_base,
                d_sup,
            );
            *x += kern;
            place_script(out, x, script_glyphs, script_width, sup_shift);
            Ok(())
        }
        MathElem::Cmd { name, span, .. } => Err(EvalError {
            span: Some(*span),
            msg: format!("math command `{name}` needs the math package (phase 7 roadmap A)"),
        }),
        MathElem::Embed { span, .. } => Err(EvalError {
            span: Some(*span),
            msg: "embedding a program value in math needs the math package \
                  (phase 7 roadmap A)"
                .into(),
        }),
    }
}

/// Walk an elaborated `${…}` tree (`read_inline`'s `EmbedMath` arm) into one
/// `PureHorzBox::Math`, measuring every glyph through `interp.metrics` at
/// `ctx.font`/`ctx.font_size` — the same `FontMetrics` seam `text_to_boxes`
/// uses. Box-model rationale: a math run carries its own pre-shifted
/// sub-glyphs, since the line model has no per-box vertical slot.
pub fn read_math(
    interp: &mut Interp,
    ctx: &Context,
    elems: &[MathElem],
) -> Result<PureHorzBox, EvalError> {
    let mut glyphs: Vec<MathGlyph> = Vec::new();
    let mut x = Length::ZERO;
    let mut last_kind: Option<MathKind> = None;
    for e in elems {
        layout_math_elem(
            interp,
            ctx,
            e,
            ctx.font_size,
            &mut glyphs,
            &mut x,
            &mut last_kind,
        )?;
    }
    let width = x;
    let mut height = Length::ZERO;
    let mut depth = Length::ZERO;
    for g in &glyphs {
        height = height.max(g.dy + g.height);
        depth = depth.max(g.depth - g.dy);
    }
    Ok(PureHorzBox::Math {
        width,
        height,
        depth,
        glyphs,
        rules: Vec::new(),
    })
}

// ---- primitive bodies ----------------------------------------------------------

fn prim_read_inline(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let it = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let (elems, env) = as_inline_text(it)?;
    Ok(Value::InlineBoxes(read_inline(interp, &ctx, &elems, &env)?))
}

fn prim_read_block(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let bt = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let (elems, env) = as_block_text(bt)?;
    Ok(Value::BlockBoxes(read_block(interp, &ctx, &elems, &env)?))
}

/// `line-break : bool -> bool -> context -> inline-boxes -> block-boxes`
/// (vminst.ml `BackendLineBreaking`). The two leading bools tell the real
/// line breaker whether the paragraph's top/bottom edge may break across a
/// page; this port's `break_into_lines` does not yet model breakability
/// at all, so both are accepted (to keep the arity/signature faithful to
/// v0.0.6) and ignored for now.
///
/// This is upstream's `form_paragraph` seam — every stdlib caller
/// (`form-paragraph = line-break true true`, and every direct `line-break _
/// _ (ctx |> set-paragraph-margin …)` call for headings/itemize/footnotes)
/// relies on `line-break` itself to apply
/// `ctx.paragraph_top`/`paragraph_bottom` around the formed lines,
/// unconditionally of the two breakability bools (those only ever gate
/// page-break eligibility upstream, never whether the margin applies).
/// Prepending/appending `VertBox::Skip` here is a no-op in extent for a
/// caller that already zeroed the margin (e.g. `footnote-scheme.satyh`'s
/// `set-paragraph-margin 0pt 0pt`), and the leading skip specifically is
/// further discarded by `chop_page` when it lands at the very top of a
/// page/column (see that function's `pending_skip` handling) — mirroring
/// upstream's page-top glue suppression so a page's first paragraph does not
/// get a spurious gap above it.
fn prim_line_break(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ib = as_inline_boxes(args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    let _is_breakable_bottom = as_bool(args.pop().unwrap())?;
    let _is_breakable_top = as_bool(args.pop().unwrap())?;
    let lines = break_into_lines(&ctx, ib);
    // No lines were actually formed (empty inline content, `break_into_lines`'s
    // own `n == 0` early return) — don't manufacture a margin around nothing.
    let mut out = Vec::with_capacity(lines.len() + 2);
    if !lines.is_empty() {
        // `min_first_line_ascender` (9pt, `primitives.cppo.ml:516`) is folded
        // into the paragraph's OWN top margin, exactly as `lineBreak.ml:855-857`
        // does — `margin_top = paragraph_margin_top + max(0, 9pt - hgt)` over
        // the FIRST formed line's height. That padded value is what
        // `pageBreak.ml`'s `squash_margins` (`:596-601`) then max-collapses
        // against the previous block's bottom margin, so a larger predecessor
        // ABSORBS the pad instead of stacking it on top. Applying the floor
        // downstream to the line HEIGHT, after the collapse, is a different
        // function: it over-spaced every block whose predecessor had the larger
        // bottom margin — 5pt at every stdjabook section heading, whose 4pt
        // rule lines are shorter than the floor.
        //
        // The BOTTOM margin takes no pad: `min_last_descender` is assigned at
        // `lineBreak.ml:1144` and never read.
        let first_height = lines
            .iter()
            .find_map(|vb| match vb {
                VertBox::Line { height, .. } => Some(*height),
                _ => None,
            })
            .unwrap_or(Length::ZERO);
        let pad = (MIN_FIRST_ASCENDER - first_height).max(Length::ZERO);
        out.push(VertBox::ParagTop(ctx.paragraph_top + pad));
        out.extend(lines);
        out.push(VertBox::Skip(ctx.paragraph_bottom));
    }
    for vb in &mut out {
        if let VertBox::Line { contents, .. } = vb {
            resolve_outer_graphics_in_contents(interp, contents)?;
        }
    }
    Ok(Value::BlockBoxes(out))
}

/// Look up `field` in a scheme record's fields, erroring with the
/// available-fields hint (mirrors `evalUtil.ml`'s `report_bug_value` arms
/// for a missing/mistyped scheme field) if it's absent.
fn record_field(
    fields: &BTreeMap<String, Value>,
    record_name: &str,
    field: &str,
) -> Result<Value, EvalError> {
    match fields.get(field) {
        Some(v) => Ok(v.clone()),
        None => eval_error(format!(
            "{record_name} record is missing field '{field}' (available fields: {})",
            available_fields(fields)
        )),
    }
}

/// Extract `(text-origin, text-height)` from a `page-content-scheme`
/// record (`{| text-origin : point; text-height : length |}`) — the direct
/// port of `make_page_content_scheme_func`'s field pull (`evalUtil.ml:558-
/// 565`).
fn read_content_scheme(v: Value) -> Result<(Point, Length), EvalError> {
    let fields = match v {
        Value::Record(m) => m,
        other => {
            return eval_error(format!(
                "a page-content-scheme closure must return a record, got {}",
                other.type_name()
            ))
        }
    };
    let origin = as_point(record_field(&fields, "page-content-scheme", "text-origin")?)?;
    let height = as_length(record_field(&fields, "page-content-scheme", "text-height")?)?;
    Ok((origin, height))
}

/// Extract `(header-origin, header-content, footer-origin, footer-content)`
/// from a `page-parts` record — the direct port of
/// `make_page_parts_scheme_func`'s field pull (`evalUtil.ml:576-595`).
fn read_parts_scheme(v: Value) -> Result<(Point, Vec<VertBox>, Point, Vec<VertBox>), EvalError> {
    let fields = match v {
        Value::Record(m) => m,
        other => {
            return eval_error(format!(
                "a page-parts closure must return a record, got {}",
                other.type_name()
            ))
        }
    };
    let header_origin = as_point(record_field(&fields, "page-parts", "header-origin")?)?;
    let header_content = as_block_boxes(record_field(&fields, "page-parts", "header-content")?)?;
    let footer_origin = as_point(record_field(&fields, "page-parts", "footer-origin")?)?;
    let footer_content = as_block_boxes(record_field(&fields, "page-parts", "footer-content")?)?;
    Ok((header_origin, header_content, footer_origin, footer_content))
}

/// Upstream's `--page-number-limit` default (main.ml:1029). v0.0.6 guards
/// only the multicolumn loop (pageBreak.ml:765, `PageNumberLimitExceeded`);
/// the port guards the shared loop unconditionally — a hook-less run is
/// already bounded by the vbox count (`chop_page`'s progress guarantee), so
/// the guard can only fire when column hooks inject content, exactly the
/// case upstream added it for.
const PAGE_NUMBER_LIMIT: i64 = 10_000;

/// The real 4-arg `page-break`, v0.0.6 arm — upstream `BCDocument(pagesize,
/// SingleColumn, (fun () -> []), (fun () -> []), …)` (vminst.ml:1039): one
/// zero-shift column, no hooks. Forked from the v0.1 arm below ONLY in its
/// first-argument extraction (`as_page` vs `as_page_v01`) — deliberately two
/// separate functions per tag rather than one branching on a `version`
/// parameter, so that a "shared" function is genuinely shared code.
/// `page_break_core` below IS that shared code.
fn prim_page_break_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let pagepartsf = args.pop().unwrap();
    let pagecontf = args.pop().unwrap();
    let paper = as_page(args.pop().unwrap())?;
    page_break_core(
        interp,
        paper,
        vec![Length::ZERO],
        None,
        None,
        pagecontf,
        pagepartsf,
        bb,
    )
}

/// v0.1 arm of `page-break`. Identical to `prim_page_break_v006` above
/// except `as_page_v01` in place of `as_page`; everything downstream
/// (`page_break_core`, `chop_page`, `place_block_at`, `DocumentValue`
/// assembly) is the SAME shared code both arms call, unedited by this fork.
fn prim_page_break_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let pagepartsf = args.pop().unwrap();
    let pagecontf = args.pop().unwrap();
    let paper = as_page_v01(args.pop().unwrap())?;
    page_break_core(
        interp,
        paper,
        vec![Length::ZERO],
        None,
        None,
        pagecontf,
        pagepartsf,
        bb,
    )
}

/// `page-break-two-column : page -> length -> (unit -> block-boxes) ->
/// (pbinfo -> page-content-scheme) -> (pbinfo -> page-parts) ->
/// block-boxes -> document` (vminst.ml:1041 `BackendPageBreakingTwoColumn`),
/// v0.0.6 arm — upstream builds `MultiColumn([origin_shift])` with the
/// user's column hook and a trivial column-end hook (vminst.ml:1062); the
/// `length` is the x-shift of the SECOND column's origin. See
/// `prim_page_break_v006`'s doc comment for the fork rationale.
fn prim_page_break_two_column_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let pagepartsf = args.pop().unwrap();
    let pagecontf = args.pop().unwrap();
    let columnhookf = args.pop().unwrap();
    let origin_shift = as_length(args.pop().unwrap())?;
    let paper = as_page(args.pop().unwrap())?;
    page_break_core(
        interp,
        paper,
        vec![Length::ZERO, origin_shift],
        Some(columnhookf),
        None,
        pagecontf,
        pagepartsf,
        bb,
    )
}

/// v0.1 arm of `page-break-two-column`, using `as_page_v01` in place of
/// `as_page`.
fn prim_page_break_two_column_v01(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let pagepartsf = args.pop().unwrap();
    let pagecontf = args.pop().unwrap();
    let columnhookf = args.pop().unwrap();
    let origin_shift = as_length(args.pop().unwrap())?;
    let paper = as_page_v01(args.pop().unwrap())?;
    page_break_core(
        interp,
        paper,
        vec![Length::ZERO, origin_shift],
        Some(columnhookf),
        None,
        pagecontf,
        pagepartsf,
        bb,
    )
}

/// `page-break-multicolumn : page -> length list -> (unit -> block-boxes)
/// -> (unit -> block-boxes) -> (pbinfo -> page-content-scheme) -> (pbinfo
/// -> page-parts) -> block-boxes -> document` (vminst.ml:1065
/// `BackendPageBreakingMultiColumn`), v0.0.6 arm — FAITHFUL: the shift list
/// gives columns 2..N's x-origin shifts; upstream prepends `Length.zero` for
/// column 1 (pageBreak.ml:762), so `stdjareport.satyh:403`'s `[]` is a
/// one-column layout whose hooks still fire per column/page.
fn prim_page_break_multicolumn_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let pagepartsf = args.pop().unwrap();
    let pagecontf = args.pop().unwrap();
    let columnendhookf = args.pop().unwrap();
    let columnhookf = args.pop().unwrap();
    let mut origin_shifts = vec![Length::ZERO];
    for v in as_list(args.pop().unwrap())? {
        origin_shifts.push(as_length(v)?);
    }
    let paper = as_page(args.pop().unwrap())?;
    page_break_core(
        interp,
        paper,
        origin_shifts,
        Some(columnhookf),
        Some(columnendhookf),
        pagecontf,
        pagepartsf,
        bb,
    )
}

/// v0.1 arm of `page-break-multicolumn`, using `as_page_v01` in place of
/// `as_page`.
fn prim_page_break_multicolumn_v01(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let pagepartsf = args.pop().unwrap();
    let pagecontf = args.pop().unwrap();
    let columnendhookf = args.pop().unwrap();
    let columnhookf = args.pop().unwrap();
    let mut origin_shifts = vec![Length::ZERO];
    for v in as_list(args.pop().unwrap())? {
        origin_shifts.push(as_length(v)?);
    }
    let paper = as_page_v01(args.pop().unwrap())?;
    page_break_core(
        interp,
        paper,
        origin_shifts,
        Some(columnhookf),
        Some(columnendhookf),
        pagecontf,
        pagepartsf,
        bb,
    )
}

/// Apply a `unit -> block-boxes` column hook and PREPEND its result to the
/// remaining content — the port of `chop_single_column_with_insertion`
/// (pageBreak.ml:699-702; the upstream `normalize` is a no-op here because
/// block-boxes are already solid `Vec<VertBox>`).
fn apply_column_hook(
    interp: &mut Interp,
    hook: &Value,
    remaining: &mut Vec<VertBox>,
) -> Result<(), EvalError> {
    let inserted = as_block_boxes(interp.apply(hook.clone(), Value::Unit)?)?;
    remaining.splice(0..0, inserted);
    Ok(())
}

/// The shared per-page loop backing `page-break`, `page-break-two-column`,
/// and `page-break-multicolumn` — the port of `PageBreak.main` /
/// `main_multicolumn` (pageBreak.ml:705-781). Lang-side because it is the
/// one place that legally holds `&mut Interp` to apply the scheme/hook
/// closures (the `fire_hooks` seam). `origin_shifts` is the FULL column
/// list (leading zero included by the callers); `None` hooks are upstream's
/// `(fun () -> [])`.
///
/// Per page: apply `pagecontf` once; per column: fire `columnhookf`
/// (start of EVERY column, pageBreak.ml:700), chop one column at
/// `(x0 + shift, y0)` (footnotes bottom-place per column inside
/// `chop_page`), stop early when content runs out; then fire
/// `columnendhookf` exactly once (both upstream arms — exhausted
/// mid-columns `:751` and shifts-exhausted `:736` — reduce to "prepend its
/// output to the remainder"); then apply `pagepartsf` and place the parts.
#[allow(clippy::too_many_arguments)]
fn page_break_core(
    interp: &mut Interp,
    paper: PaperSize,
    origin_shifts: Vec<Length>,
    columnhookf: Option<Value>,
    columnendhookf: Option<Value>,
    pagecontf: Value,
    pagepartsf: Value,
    bb: Vec<VertBox>,
) -> Result<Value, EvalError> {
    let (paper_w, paper_h) = paper.dims();

    // Capture the flat pre-page-break `Vec<VertBox>` BEFORE
    // `chop_page`/`apply_column_hook` below start draining/mutating
    // `remaining` — this clone is the document's natural linear flow exactly
    // as `bb` arrived here (no pages, no injected headers/footers, no
    // column-hook-inserted content). Unconditional (not gated on which
    // output format was requested — see `DocumentValue::reflow_source`'s doc
    // comment): PDF and the faithful HTML backend never read the field, so
    // this costs them only the clone itself, never a byte of their rendered
    // output.
    let reflow_source = bb.clone();

    let mut remaining = bb;
    let mut pages: Vec<Page> = Vec::new();
    let mut pageno: i64 = 1;
    loop {
        if pageno > PAGE_NUMBER_LIMIT {
            return eval_error(format!(
                "page number limit exceeded ({PAGE_NUMBER_LIMIT}); a column hook keeps injecting content"
            ));
        }
        let mut pb_fields = BTreeMap::new();
        pb_fields.insert("page-number".to_string(), Value::Int(pageno));
        let pbinfo = Value::Record(pb_fields);

        // ---- content scheme: this page's text area (applied ONCE per page, shared by all its columns — pageBreak.ml:769) ----
        let sch = interp.apply(pagecontf.clone(), pbinfo.clone())?;
        let (origin, height) = read_content_scheme(sch)?;
        let (x0, y0) = origin;

        // ---- columns ----
        let mut lines = Vec::new();
        for shift in &origin_shifts {
            if let Some(hook) = &columnhookf {
                apply_column_hook(interp, hook, &mut remaining)?;
            }
            lines.extend(chop_page((x0 + *shift, y0), height, &mut remaining));
            if remaining.is_empty() {
                break; // content exhausted: remaining columns are skipped
            }
        }
        if let Some(hook) = &columnendhookf {
            apply_column_hook(interp, hook, &mut remaining)?;
        }

        // A trailing pure-skip/glue (e.g. the last block's `paragraph_bottom`)
        // can roll past the previous page's bottom into a final `chop_page`
        // that places NO real line — `chop_page` discards it as a page-top
        // skip, leaving an empty body. SATySFi never emits such a trailing
        // blank page (glue at the end of the vertical list is dropped), so when
        // the body is empty AND content is now exhausted, stop before turning
        // that leftover into a spurious blank page (header/footer included).
        if remaining.is_empty() && !lines.iter().any(|l| placed_line_extent(l).is_some()) {
            break;
        }

        // ---- parts scheme: this page's header + footer ----
        // Everything placed so far is body/column content; the header and
        // footer append AFTER it (see `Page::body_lines`).
        let body_lines = lines.len();
        let parts = interp.apply(pagepartsf.clone(), pbinfo)?;
        let (header_origin, header_content, footer_origin, footer_content) =
            read_parts_scheme(parts)?;
        lines.extend(place_block_at(header_origin, header_content));
        lines.extend(place_block_at(footer_origin, footer_content));

        pages.push(Page { lines, body_lines });
        if remaining.is_empty() {
            break;
        }
        pageno += 1;
    }

    // Every image `load-image` decoded while evaluating this document (see
    // `Interp::images`'s doc comment) rides along in the packaged
    // `DocumentValue` so the PDF writer can emit XObjects for the ones
    // actually placed on a page.
    let images = interp.images.clone();
    Ok(Value::Document(Rc::new(DocumentValue {
        geometry: PageGeometry::for_paper(paper_w, paper_h),
        pages,
        images,
        // Filled in by `compile_document_cst_with_trials` once `fire_hooks`
        // has walked the final trial's placed geometry (see
        // `DocumentValue::extras`'s doc comment) — hooks/decos haven't fired
        // yet at this point in `page-break`'s own evaluation.
        extras: DocExtras::default(),
        reflow_source: Some(reflow_source),
        // Filled in alongside `extras` once `fire_hooks` has run — see
        // `DocumentValue::reflow_links`'s doc comment.
        reflow_links: Vec::new(),
        reflow_dests: Vec::new(),
        reflow_frame_decos: Vec::new(),
    })))
}

// ---- int arithmetic -------------------------------------------------------

// Wrapping arithmetic to match OCaml's native `int` (SATySFi's `int` is an
// OCaml int, which wraps on overflow) — and, decisively, so a debug build does
// not panic on the large intermediate products base's float bit-twiddling
// (`exp2i`, `ldexp`, `frexp`) computes.
binop_prim!(prim_int_add, as_int, Int, |a, b| a.wrapping_add(b));
binop_prim!(prim_int_sub, as_int, Int, |a, b| a.wrapping_sub(b));
binop_prim!(prim_int_mul, as_int, Int, |a, b| a.wrapping_mul(b));

// OCaml catches `Division_by_zero` and reports `"division by zero"`; `mod`
// (see `Mod` in vminst.ml) shares that behavior.
binop_prim_try!(prim_int_div, as_int, |a, b| if b == 0 {
    eval_error("division by zero")
} else {
    Ok(Value::Int(a / b))
});
binop_prim_try!(prim_int_mod, as_int, |a, b| if b == 0 {
    eval_error("division by zero")
} else {
    Ok(Value::Int(a % b))
});

// ---- int comparisons -------------------------------------------------------

cmp_prim!(prim_int_eq, as_int, |a, b| a == b);
cmp_prim!(prim_int_ne, as_int, |a, b| a != b);
cmp_prim!(prim_int_lt, as_int, |a, b| a < b);
cmp_prim!(prim_int_gt, as_int, |a, b| a > b);
cmp_prim!(prim_int_le, as_int, |a, b| a <= b);
cmp_prim!(prim_int_ge, as_int, |a, b| a >= b);

// ---- 0.1 bitwise ops -------------------------------------------------------
//
// `band`/`bor`/`bxor` mirror OCaml's `land`/`lor`/`lxor`; `bnot` mirrors
// `lnot` (bitwise complement). DOCUMENTED DEVIATION: this port's `int` is a
// 64-bit two's-complement `i64`, vs upstream's 63-bit boxed OCaml `int` — a
// value that actually uses bit 62 (the port's sign-adjacent bit upstream
// doesn't have) will complement/shift differently than upstream on that
// platform; upstream's own results are themselves platform-width-dependent
// there, and no bundled package relies on it.
binop_prim!(prim_band, as_int, Int, |a, b| a & b);
binop_prim!(prim_bor, as_int, Int, |a, b| a | b);
binop_prim!(prim_bxor, as_int, Int, |a, b| a ^ b);
unop_prim!(prim_bnot, as_int, Int, |a| !a);

// `<<`/`>>` (dev-0-1-0 vminst.ml :2495/:2477): logical shifts (OCaml's
// `lsl`/`lsr`, NOT arithmetic — `>>` on a negative int does NOT sign-extend,
// see the `-16 >> 2` witness in the test suite), with upstream's exact
// dynamic-error message when the shift amount is out of `0..=63`.
binop_prim_try!(
    prim_bit_shift_left,
    as_int,
    |a, b| if !(0..=63).contains(&b) {
        eval_error("Bit offset out of bounds for '<<'")
    } else {
        Ok(Value::Int(((a as u64) << b) as i64))
    }
);
binop_prim_try!(
    prim_bit_shift_right,
    as_int,
    |a, b| if !(0..=63).contains(&b) {
        eval_error("Bit offset out of bounds for '>>'")
    } else {
        Ok(Value::Int(((a as u64) >> b) as i64))
    }
);

// ---- bool -------------------------------------------------------------------

// Strict (both arguments already evaluated by the caller before these natives
// run): real SATySFi source-level `&&`/`||` short-circuit via elaboration into
// `if`, which is out of scope here.
binop_prim!(prim_bool_and, as_bool, Bool, |a, b| a && b);
binop_prim!(prim_bool_or, as_bool, Bool, |a, b| a || b);
unop_prim!(prim_bool_not, as_bool, Bool, |a| !a);

// ---- float --------------------------------------------------------------------

binop_prim!(prim_float_add, as_float, Float, |a, b| a + b);
binop_prim!(prim_float_sub, as_float, Float, |a, b| a - b);
binop_prim!(prim_float_mul, as_float, Float, |a, b| a * b);
binop_prim!(prim_float_div, as_float, Float, |a, b| a / b);
unop_prim!(prim_float_of_int, as_int, Float, |n| n as f64);

// `PrimitiveRound` in vminst.ml is, despite the name, `int_of_float`
// (truncation toward zero), not rounding to nearest.
unop_prim!(prim_round, as_float, Int, |x| x as i64);

// ---- 0.1 float comparisons (saphe-split vminst.ml:2679-2740) ----
cmp_prim!(prim_float_gt, as_float, |a, b| a > b);
cmp_prim!(prim_float_lt, as_float, |a, b| a < b);
cmp_prim!(prim_float_ge, as_float, |a, b| a >= b);
cmp_prim!(prim_float_le, as_float, |a, b| a <= b);

// ---- length ---------------------------------------------------------------------

binop_prim!(prim_length_add, as_length, Length, |a, b| a + b);
binop_prim!(prim_length_sub, as_length, Length, |a, b| a - b);
binop_prim!(prim_length_scale, (as_length, as_float), Length, |a, b| a
    * b);
binop_prim!(prim_length_div, as_length, Float, |a, b| a / b);
cmp_prim!(prim_length_lt, as_length, |a, b| a < b);

// `LengthGreaterThan` in vminst.ml is implemented as `len2 <% len1`, i.e.
// `a >' b` iff `b <' a` — the same ordering, just flipped operands.
cmp_prim!(prim_length_gt, as_length, |a, b| b < a);

// ---- string -----------------------------------------------------------------------

binop_prim!(prim_string_concat, as_str, Str, |a, b| a + &b);
unop_prim!(prim_arabic, as_int, Str, |n| n.to_string());
cmp_prim!(prim_string_same, as_str, |a, b| a == b);

// ---- list -----------------------------------------------------------------

/// `x :: xs` — prepend `x` onto the list `xs`.
fn prim_list_cons(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let tail = args.pop().unwrap();
    let head = args.pop().unwrap();
    let mut list = match tail {
        Value::List(v) => v,
        other => return eval_error(format!("expected list, got {}", other.type_name())),
    };
    list.insert(0, head);
    Ok(Value::List(list))
}

// ---- mutable-cell dereference ----------------------------------------------

/// `!` — read the current contents of a mutable cell (see the `prims!`
/// registration above for how this differs structurally, not semantically,
/// from v0.0.6's `Dereference`/`Location` handling).
fn prim_deref(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let v = args.pop().unwrap();
    match v {
        Value::Ref(cell) => Ok(cell.borrow().clone()),
        other => eval_error(format!(
            "expected a mutable cell for '!', got {}",
            other.type_name()
        )),
    }
}

// ---- string, continued -----------------------------------------------------

// `string-length : string -> int` (vminst.ml `PrimitiveStringLength`) —
// counts Unicode scalar values (`BatUTF8.length`), not UTF-8 bytes.
unop_prim!(prim_string_length, as_str, Int, |s| s.chars().count()
    as i64);

/// `string-sub : string -> int -> int -> string` (vminst.ml
/// `PrimitiveStringSub`) — a substring addressed by Unicode-scalar-value
/// offset/width (`BatUTF8.sub`), not byte offset. Upstream raises a dynamic
/// error ("illegal index for string-sub") on an out-of-range index; we do
/// the same.
fn prim_string_sub(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let wid = as_int(args.pop().unwrap())?;
    let pos = as_int(args.pop().unwrap())?;
    let s = as_str(args.pop().unwrap())?;
    if wid < 0 || pos < 0 {
        return eval_error("illegal index for string-sub");
    }
    let chars: Vec<char> = s.chars().collect();
    let pos = pos as usize;
    let wid = wid as usize;
    match pos.checked_add(wid) {
        Some(end) if end <= chars.len() => Ok(Value::Str(chars[pos..end].iter().collect())),
        _ => eval_error("illegal index for string-sub"),
    }
}

// `string-explode : string -> int list` (vminst.ml `PrimitiveStringExplode`)
// — the string's Unicode scalar values (code points) in order, not its bytes.
unop_prim!(prim_string_explode, as_str, List, |s| s
    .chars()
    .map(|c| Value::Int(c as i64))
    .collect());

fn prim_embed_string(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    Ok(Value::InlineText {
        elems: Rc::new(vec![IText::Text(s)]),
        env: Env::root(),
    })
}

// ---- context ops ------------------------------------------------------------

/// `set-font-size : length -> context -> context` (vminst.ml
/// `PrimitiveSetFontSize`).
fn prim_set_font_size(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let size = as_length(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        font_size: size,
        ..ctx
    })))
}

/// `get-font-size : context -> length` (vminst.ml `PrimitiveGetFontSize`).
fn prim_get_font_size(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    Ok(Value::Length(ctx.font_size))
}

/// `set-leading : length -> context -> context` (vminst.ml
/// `PrimitiveSetLeading`; see the `prims!` table comment for why this is
/// the baseline-distance setter and not `set-min-gap-of-lines`).
fn prim_set_leading(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let leading = as_length(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context { leading, ..ctx })))
}

/// `set-paragraph-margin : length -> length -> context -> context`
/// (vminst.ml `PrimitiveSetParagraphMargin`).
fn prim_set_paragraph_margin(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let bottom = as_length(args.pop().unwrap())?;
    let top = as_length(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        paragraph_top: top,
        paragraph_bottom: bottom,
        ..ctx
    })))
}

/// `get-text-width : context -> length` (vminst.ml `PrimitiveGetTextWidth`).
fn prim_get_text_width(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    Ok(Value::Length(ctx.paragraph_width))
}

/// `get-initial-context : length -> [math] inline-cmd -> context`
/// (vminst.ml `PrimitiveGetInitialContext`) — the second argument is the
/// default math command a bare `${…}` in inline text dispatches to (v0.0.6
/// `context_main.math_command`); interned via
/// `Interp::register_math_command`, carried as `Context::math_command`.
fn prim_get_initial_context(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let cmd = args.pop().unwrap();
    let width = as_length(args.pop().unwrap())?;
    let mut ctx = Context::initial(width);
    ctx.math_command = Some(interp.register_math_command(cmd));
    // Overlay the configured `default-font.satysfi-hash` `scripts`
    // block, if any, so a bare document with a configured font root renders
    // CJK/etc. with zero `set-font` calls (`interp.metrics.
    // default_script_font` is `None` for every script on a provider with no
    // such config — `Base14Metrics` and a bare `TtfFontStore::load` both —
    // so this loop is a no-op there).
    for (idx, script) in [
        Script::HanIdeographic,
        Script::Kana,
        Script::Latin,
        Script::OtherScript,
    ]
    .into_iter()
    .enumerate()
    {
        if let Some((font, ratio, rising)) = interp.metrics.default_script_font(script) {
            ctx.font_scheme[idx] = ScriptFont {
                font,
                ratio,
                rising,
            };
            if script == Script::Latin {
                ctx.font = font;
            }
        }
    }
    // Overlay the configured `default-font.satysfi-hash` `"math"`
    // abbrev, if any, so a document with a bundled MATH-table font renders
    // real cramped/uncramped math metrics with zero `set-math-font` calls.
    // `interp.metrics.default_math_font` is `None` on a provider with no such
    // config, the same no-op-by-default shape as the `scripts` overlay above.
    if let Some(font) = interp.metrics.default_math_font() {
        ctx.math_font = font;
    }
    Ok(Value::Context(Box::new(ctx)))
}

/// `set-font-key : int -> context -> context` — LOCAL, non-upstream
/// primitive; see the `prims!` table comment on `"set-font-key"` for why it
/// exists. Sets `Context::font` directly to `FontKey(n)`.
fn prim_set_font_key(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let key = as_int(args.pop().unwrap())?;
    if key < 0 || key > i64::from(u16::MAX) {
        return eval_error(format!("set-font-key: font key {key} is out of range"));
    }
    Ok(Value::Context(Box::new(Context {
        font: FontKey(key as u16),
        ..ctx
    })))
}

// ---- box combinators ---------------------------------------------------------

/// `++ : inline-boxes -> inline-boxes -> inline-boxes` (vminst.ml
/// `HorzConcat`).
fn prim_inline_concat(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut b = as_inline_boxes(args.pop().unwrap())?;
    let mut a = as_inline_boxes(args.pop().unwrap())?;
    a.append(&mut b);
    Ok(Value::InlineBoxes(a))
}

/// `+++ : block-boxes -> block-boxes -> block-boxes` (vminst.ml
/// `VertConcat`).
fn prim_block_concat(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut b = as_block_boxes(args.pop().unwrap())?;
    let mut a = as_block_boxes(args.pop().unwrap())?;
    a.append(&mut b);
    Ok(Value::BlockBoxes(a))
}

/// `inline-skip : length -> inline-boxes` (vminst.ml `BackendFixedEmpty`).
fn prim_inline_skip(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let width = as_length(args.pop().unwrap())?;
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::FixedEmpty { width },
    )]))
}

/// `inline-glue : length -> length -> length -> inline-boxes` (vminst.ml
/// `BackendOuterEmpty`; params `(widnat, widshrink, widstretch)`, i.e.
/// natural, then shrink, then stretch — the same order `OuterEmpty`'s
/// fields are already declared in).
fn prim_inline_glue(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let stretchable = as_length(args.pop().unwrap())?;
    let shrinkable = as_length(args.pop().unwrap())?;
    let natural = as_length(args.pop().unwrap())?;
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::OuterEmpty {
            natural,
            shrinkable,
            stretchable,
        },
    )]))
}

/// `block-skip : length -> block-boxes` (vminst.ml `BackendVertSkip`).
fn prim_block_skip(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let len = as_length(args.pop().unwrap())?;
    Ok(Value::BlockBoxes(vec![VertBox::Skip(len)]))
}

/// `list-mark : int -> block-boxes` — the block-level reflow marker
/// constructor `itemize.satyh`'s `listing`/`listing-item`/`listing-item-
/// breakable`/`enumerate`/`enumerate-item` call to fence list/item
/// boundaries. Returns a single-element `block-boxes` carrying an INERT
/// `VertBox::ListMark` — zero height/depth, stripped with zero contribution
/// by `chop_page`/`place_block_at`/`measure_block` before it can ever reach a
/// `PlacedLine`, so PDF and faithful HTML render identically whether or not
/// a document's stdlib calls this. Only `page_break_core`'s `reflow_source`
/// clone (taken BEFORE `chop_page` drains its input) retains it, for the
/// `html-support` branch's reflow HTML walker to read back.
///
/// `tag` encoding (the only "int tag" scheme any caller needs to know,
/// since this primitive is never reflected through the type system beyond
/// `int -> block-boxes`):
/// - `0` = `ListStart { ordered: false }` (opens a `<ul>`)
/// - `1` = `ListStart { ordered: true }` (opens an `<ol>`)
/// - `2` = `ListEnd`
/// - `3` = `ItemStart`
/// - `4` = `ItemEnd`
fn prim_list_mark(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let tag = as_int(args.pop().unwrap())?;
    let kind = match tag {
        0 => ListMarkKind::ListStart { ordered: false },
        1 => ListMarkKind::ListStart { ordered: true },
        2 => ListMarkKind::ListEnd,
        3 => ListMarkKind::ItemStart,
        4 => ListMarkKind::ItemEnd,
        other => return eval_error(format!("list-mark: unknown tag {other}")),
    };
    Ok(Value::BlockBoxes(vec![VertBox::ListMark(kind)]))
}

/// `inline-mark : int -> inline-boxes` — the inline-level reflow marker
/// constructor: `itemize.satyh`'s `make-bullet`/`enumerate-item` fence the
/// drawn bullet/number glyph run with `BulletStart`/`BulletEnd`, and the
/// repo-controlled `\emph`/`\bold` definitions (an opt-in, per-command wrap)
/// fence their body with `EmphStart`/`EmphEnd`. Same INERT-marker contract as
/// `list-mark` above — a zero-size `PureHorzBox::InlineMark`, ignored by
/// `measure`/`natural_metrics`/`justify_line`
/// (rustyfi-backend's `linebreak.rs`),
/// `math_glyphs_of_inline_boxes`/`math_boxes_of_inline_boxes` below, and both
/// the PDF and faithful HTML writers; read only by the `html-support`
/// branch's reflow HTML walker.
///
/// `tag` encoding:
/// - `0` = `EmphStart { strong: false }` (opens `<em>`)
/// - `1` = `EmphStart { strong: true }` (opens `<strong>`)
/// - `2` = `EmphEnd`
/// - `3` = `BulletStart`
/// - `4` = `BulletEnd`
fn prim_inline_mark(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let tag = as_int(args.pop().unwrap())?;
    let kind = match tag {
        0 => InlineMarkKind::EmphStart { strong: false },
        1 => InlineMarkKind::EmphStart { strong: true },
        2 => InlineMarkKind::EmphEnd,
        3 => InlineMarkKind::BulletStart,
        4 => InlineMarkKind::BulletEnd,
        other => return eval_error(format!("inline-mark: unknown tag {other}")),
    };
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::InlineMark(kind),
    )]))
}

// ---- pure float primitives --------------------------------------------------
//
// All bodies below are `float -> float` (or `float -> float -> float`)
// straight wraps of the matching `f64` method — vminst.ml's OCaml bodies
// (`make_float (sin flt1)`, etc.) are themselves direct wraps of the same
// IEEE-754 libm functions, so there is no behavioral daylight here.

binop_prim!(prim_atan2, as_float, Float, |a, b| a.atan2(b));
unop_prim!(prim_sin, as_float, Float, |x| x.sin());
unop_prim!(prim_asin, as_float, Float, |x| x.asin());
unop_prim!(prim_cos, as_float, Float, |x| x.cos());
unop_prim!(prim_acos, as_float, Float, |x| x.acos());
unop_prim!(prim_tan, as_float, Float, |x| x.tan());
unop_prim!(prim_atan, as_float, Float, |x| x.atan());
// vminst.ml:2834 `FloatLogarithm`: OCaml's `log` is the NATURAL logarithm
// (`ln`), not `log10`.
unop_prim!(prim_log, as_float, Float, |x| x.ln());
unop_prim!(prim_exp, as_float, Float, |x| x.exp());
// `ceil`/`floor` return `float`, unlike `round` (above), which returns
// `int` — see this file's `prims!` table comment on `"ceil"`/`"floor"`.
unop_prim!(prim_ceil, as_float, Float, |x| x.ceil());
unop_prim!(prim_floor, as_float, Float, |x| x.floor());

// `show-float : float -> string` (vminst.ml:2319 `PrimitiveShowFloat`) —
// OCaml's `string_of_float`. See `ocaml_show_float`'s doc comment (below)
// for the emulation and its known fidelity limits.
unop_prim!(prim_show_float, as_float, Str, |x| ocaml_show_float(x));

/// A from-scratch emulation of OCaml's `Stdlib.string_of_float`: format via
/// a C `%.12g` equivalent (12 significant digits; fixed-point when the
/// decimal exponent falls in `-4..12`, scientific otherwise; trailing
/// fractional zeros trimmed), then apply `valid_float_lexem`'s post-pass —
/// append a trailing `.` when the result would otherwise print as a bare
/// integer (`"1."`, never `"1"`, so a `float`'s printed form always reads
/// as a float, not an `int`). Known limitation: this is a Rust
/// reimplementation of the same specification (OCaml itself defers to the
/// platform C library's `%.12g`), so it may disagree with OCaml in obscure
/// corner cases, though it agrees on ordinary values (verified by hand
/// against real OCaml output for `0.`, `-0.`, `1.`, `100.`, `0.0025`,
/// `1e+20`, `1e-05`).
fn ocaml_show_float(x: f64) -> String {
    if x.is_nan() {
        return "nan".to_string();
    }
    if x.is_infinite() {
        return if x < 0.0 { "-infinity" } else { "infinity" }.to_string();
    }
    const PREC: i32 = 12;
    // Style-E rendering at precision PREC-1 recovers the correctly-rounded
    // decimal exponent (a naive `log10().floor()` can be off by one right
    // at a power of ten, because of binary/decimal rounding).
    let sci = format!("{:.*e}", (PREC - 1) as usize, x);
    let epos = sci
        .find('e')
        .expect("scientific formatting always emits 'e'");
    let exp: i32 = sci[epos + 1..].parse().expect("well-formed exponent");
    let body = if exp < -4 || exp >= PREC {
        let mantissa = trim_trailing_fractional_zeros(&sci[..epos]);
        format!(
            "{mantissa}e{}{:02}",
            if exp < 0 { "-" } else { "+" },
            exp.abs()
        )
    } else {
        let decimals = (PREC - 1 - exp).max(0) as usize;
        trim_trailing_fractional_zeros(&format!("{:.*}", decimals, x)).to_string()
    };
    if body.bytes().all(|b| b.is_ascii_digit() || b == b'-') {
        format!("{body}.")
    } else {
        body
    }
}

/// Strip trailing zeros after a decimal point, then the point itself if
/// nothing remains after it (`"3.140" -> "3.14"`, `"5.000" -> "5"`);
/// already-integer-shaped strings (no `.`) pass through unchanged.
fn trim_trailing_fractional_zeros(s: &str) -> &str {
    if !s.contains('.') {
        return s;
    }
    s.trim_end_matches('0').trim_end_matches('.')
}

// `string-byte-length : string -> int` (vminst.ml:2159
// `PrimitiveStringByteLength`) — UTF-8 BYTE count (`String.length` in
// OCaml, whose native strings are raw byte sequences), unlike
// `string-length`'s Unicode-scalar-value count.
unop_prim!(prim_string_byte_length, as_str, Int, |s| s.len() as i64);

/// `string-sub-bytes : string -> int -> int -> string` (vminst.ml:2123
/// `PrimitiveStringSubBytes`) — byte-indexed substring (OCaml's
/// `String.sub`), unlike `string-sub`'s Unicode-scalar-value indexing.
/// Guards an out-of-range span exactly like `prim_string_sub`'s "illegal
/// index" dynamic error, AND a split landing inside a multi-byte UTF-8
/// sequence — impossible for OCaml's byte-oriented strings, but a
/// `Value::Str` here is a Rust `String`, which must stay valid UTF-8.
fn prim_string_sub_bytes(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let wid = as_int(args.pop().unwrap())?;
    let pos = as_int(args.pop().unwrap())?;
    let s = as_str(args.pop().unwrap())?;
    if wid < 0 || pos < 0 {
        return eval_error("illegal index for string-sub-bytes");
    }
    let (pos, wid) = (pos as usize, wid as usize);
    match pos.checked_add(wid) {
        Some(end) if end <= s.len() && s.is_char_boundary(pos) && s.is_char_boundary(end) => {
            Ok(Value::Str(s[pos..end].to_string()))
        }
        _ => eval_error("illegal index for string-sub-bytes"),
    }
}

/// `string-unexplode : int list -> string` (vminst.ml:2196
/// `PrimitiveStringUnexplode`) — the inverse of `string-explode` (above):
/// each int is a Unicode scalar value (code point), concatenated into one
/// UTF-8 string. Upstream's `Uchar.of_int` raises on an int that isn't a
/// valid Unicode scalar value (a surrogate, or out of range); reported here
/// as the same kind of dynamic error rather than panicking.
fn prim_string_unexplode(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let items = as_list(args.pop().unwrap())?;
    let mut s = String::new();
    for v in items {
        let n = as_int(v)?;
        match u32::try_from(n).ok().and_then(char::from_u32) {
            Some(c) => s.push(c),
            None => {
                return eval_error(format!(
                    "string-unexplode: {n} is not a valid Unicode scalar value"
                ))
            }
        }
    }
    Ok(Value::Str(s))
}

/// `normalize-string-to-nfc : string -> string` (dev-0-1-0 vminst.ml:2050
/// `NormalizeStringToNFC`) — REAL: UAX #15 Normalization Form C, via the
/// `unicode-normalization` crate (`UnicodeNormalization::nfc`), a pure-Rust
/// stand-in for upstream's uunf-backed `NormalizeString.of_utf8_nfc`.
/// DOCUMENTED NON-RISK: this crate's embedded Unicode table version may lag
/// or lead upstream's uunf pin — both track recent Unicode, and no bundled
/// package/test relies on a normalization pair that changed between
/// versions.
fn prim_normalize_string_to_nfc(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    Ok(Value::Str(s.nfc().collect()))
}

/// `normalize-string-to-nfd : string -> string` (dev-0-1-0 vminst.ml:2066
/// `NormalizeStringToNFD`) — REAL: UAX #15 Normalization Form D, same
/// crate/caveats as [`prim_normalize_string_to_nfc`] above.
fn prim_normalize_string_to_nfd(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    Ok(Value::Str(s.nfd().collect()))
}

/// `split-grapheme-cluster : string -> list string` (dev-0-1-0 vminst.ml:
/// 2082 `SplitOnGraphemeCluster` / `GraphemeCluster.split_utf8`) — REAL: UAX
/// #29 EXTENDED grapheme clusters, via the `unicode-segmentation` crate's
/// `graphemes(s, true)` (`true` selects the extended, not legacy, cluster
/// rules — what upstream's uuseg default segmenter produces).
fn prim_split_grapheme_cluster(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let clusters: Vec<Value> = s
        .graphemes(true)
        .map(|g| Value::Str(g.to_string()))
        .collect();
    Ok(Value::List(clusters))
}

/// `display-message : string -> unit` (vminst.ml:2056
/// `PrimitiveDisplayMessage`) — upstream prints via `print_endline`
/// (STDOUT); this port deliberately prints to STDERR instead (`eprintln!`),
/// keeping stdout reserved for actual document output. This matches the
/// existing house convention: the CLI's own "output written" status line
/// (`rustyfi`'s `main.rs`) is likewise stderr-only, never stdout — a
/// documented deviation, not an oversight.
fn prim_display_message(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let msg = as_str(args.pop().unwrap())?;
    eprintln!("{msg}");
    Ok(Value::Unit)
}

/// `abort-with-message : string -> 'a` (vminst.ml:3133 `AbortWithMessage`)
/// — raises a dynamic error carrying `msg` verbatim. The polymorphic result
/// type (`prim_types.rs`'s `poly1`) is vacuously satisfiable: this always
/// evaluates to `Err`, never actually producing a value of whatever type
/// the call site expected.
fn prim_abort_with_message(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let msg = as_str(args.pop().unwrap())?;
    eval_error(msg)
}

// ---- images (raster images) -----------

/// `load-image : string -> image` (v0.0.6 vminstdef.yaml:540). Resolves
/// `path` against the process's current working directory — this port
/// has no "job directory" threaded through `Interp` yet, so this is a
/// deliberately simple stand-in for v0.0.6's real job-directory-relative
/// resolution, good enough for a CLI invoked from the document's own
/// directory and for this crate's fixture-driven tests (which pass an
/// absolute path).
///
/// Decoding is eager (via the `image` crate, to 8-bit `DeviceRGB` — see
/// `ImageResource`'s doc comment for the alpha-dropping/format caveats),
/// matching v0.0.6's `ImageInfo.add_image` (imageInfo.ml): a missing or
/// undecodable file is a clean `EvalError` here, not deferred to the PDF
/// writer.
///
/// JPEG DCTDecode passthrough: in addition to the eager RGB8 decode above
/// (still needed for `use-image-by-width`'s aspect ratio and the HTML
/// backend's `<img>` data URI), this re-reads the same path's raw bytes and
/// sniffs them for a baseline JPEG (`ImageResource::sniff_baseline_jpeg_dct`)
/// so the PDF writer can embed the ORIGINAL DCT-encoded bytes instead of
/// re-encoding the flattened samples. The second read is best-effort: a
/// failure just leaves `jpeg_dct` as `None` and falls back to flat-RGB8
/// embedding, since the file already decoded fine above.
fn prim_load_image(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path = as_str(args.pop().unwrap())?;
    let decoded = image::open(&path).map_err(|e| EvalError {
        span: None,
        msg: format!("load-image: cannot decode '{path}': {e}"),
    })?;
    let rgb = decoded.to_rgb8();
    let (px_w, px_h) = rgb.dimensions();
    let jpeg_dct = std::fs::read(&path)
        .ok()
        .and_then(ImageResource::sniff_baseline_jpeg_dct);
    let id = ImageId(interp.images.len());
    interp.images.push(ImageResource {
        samples: rgb.into_raw(),
        px_w,
        px_h,
        jpeg_dct,
        pdf: None,
    });
    Ok(Value::Image(id))
}

/// `use-image-by-width : image -> length -> inline-boxes` (v0.0.6
/// vminstdef.yaml:554). Computes the on-page height from the source
/// image's own pixel aspect ratio (v0.0.6
/// `ImageInfo.get_height_from_width`, imageInfo.ml:44): `height = width *
/// px_h / px_w`.
fn prim_use_image_by_width(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let width = as_length(args.pop().unwrap())?;
    let image = as_image(args.pop().unwrap())?;
    let resource = interp.images.get(image.0).ok_or_else(|| EvalError {
        span: None,
        msg: format!("internal error: image id {} out of range", image.0),
    })?;
    let (iw, ih) = resource.intrinsic_dims_pt();
    if iw == 0.0 {
        return eval_error("use-image-by-width: image has zero width, cannot scale");
    }
    let height = width * (ih / iw);
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::Image {
            width,
            height,
            image,
        },
    )]))
}

/// `load-pdf-image : string -> int -> image` (v0.0.6 vminstdef.yaml:525-538
/// `BackendRegisterPdfImage`; dev-0-1-0 renames it `PrimitiveLoadPdfImage`
/// with the identical type/body). Loads page `pageno` (1-based) of the PDF
/// at `path`, parsed eagerly with `lopdf`, and stores a `PdfPageResource` —
/// the page's `/MediaBox` (for `use-image-by-width`'s aspect ratio), its
/// content stream(s) (already inflated/concatenated by
/// `lopdf::Document::get_page_content`), and its imported `/Resources`
/// object subtree (for the PDF writer's Form XObject).
///
/// Path resolution is cwd-relative, the same documented deviation as
/// `prim_load_image`/`prim_read_file` (no job-directory threaded through
/// `Interp` yet).
///
/// Errors (all clean `EvalError`, no panics):
/// - file missing/unreadable → "cannot open '<path>': <e>";
/// - malformed/unparseable PDF → "cannot parse PDF '<path>': <e>";
/// - `pageno < 1` → "page number must be >= 1 (got <n>)";
/// - `pageno` beyond the page count → "'<path>' has no page <n>";
/// - `/Encrypt` present in the trailer → "'<path>' is encrypted; not
///   supported" (decryption is never attempted);
/// - no usable `/MediaBox` (missing at every level of the inherited page
///   tree, wrong array length, or non-numeric entries) → "page <n> of
///   '<path>' has no usable MediaBox".
#[cfg(feature = "pdf-image")]
fn prim_load_pdf_image(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let pageno = as_int(args.pop().unwrap())?;
    let path = as_str(args.pop().unwrap())?;
    if pageno < 1 {
        return eval_error(format!(
            "load-pdf-image: page number must be >= 1 (got {pageno})"
        ));
    }
    let doc = lopdf::Document::load(&path).map_err(|e| {
        let msg = match &e {
            lopdf::Error::IO(io_e) => format!("load-pdf-image: cannot open '{path}': {io_e}"),
            other => format!("load-pdf-image: cannot parse PDF '{path}': {other}"),
        };
        EvalError { span: None, msg }
    })?;
    if doc.is_encrypted() {
        return eval_error(format!(
            "load-pdf-image: '{path}' is encrypted; not supported"
        ));
    }
    let pages = doc.get_pages();
    let page_id = *pages.get(&(pageno as u32)).ok_or_else(|| EvalError {
        span: None,
        msg: format!("load-pdf-image: '{path}' has no page {pageno}"),
    })?;
    let page_dict = doc.get_dictionary(page_id).map_err(|e| EvalError {
        span: None,
        msg: format!("load-pdf-image: cannot parse PDF '{path}': {e}"),
    })?;
    let media_box = resolve_pdf_media_box(&doc, page_dict).ok_or_else(|| EvalError {
        span: None,
        msg: format!("load-pdf-image: page {pageno} of '{path}' has no usable MediaBox"),
    })?;
    let content = doc.get_page_content(page_id).map_err(|e| EvalError {
        span: None,
        msg: format!("load-pdf-image: cannot parse PDF '{path}': {e}"),
    })?;
    let resources = import_pdf_resources(&doc, page_dict);
    let id = ImageId(interp.images.len());
    interp.images.push(ImageResource {
        samples: Vec::new(),
        px_w: 0,
        px_h: 0,
        jpeg_dct: None,
        pdf: Some(PdfPageResource {
            media_box,
            content,
            resources,
        }),
    });
    Ok(Value::Image(id))
}

/// Without the `pdf-image` feature no PDF reader is linked in, so the
/// primitive can only fail — which it does at the call site, naming why.
///
/// The name stays REGISTERED rather than being gated out of the primitive
/// tables: `typecheck::PRIMITIVE_NAMES`, `prim_types::primitive_type` and this
/// table are cross-checked against each other (`tests/typecheck.rs`), and a
/// document that reaches for `load-pdf-image` is better told that this build
/// cannot read PDFs than that the name does not exist.
#[cfg(not(feature = "pdf-image"))]
fn prim_load_pdf_image(_interp: &mut Interp, _args: Vec<Value>) -> Result<Value, EvalError> {
    eval_error(
        "load-pdf-image: this build has no PDF reader (the `pdf-image` feature \
         is off). It is off for WebAssembly, where the primitive could not work \
         regardless: it takes a filesystem path."
            .to_string(),
    )
}

/// `/MediaBox` lookup with page-tree inheritance (`lopdf` does not resolve
/// this automatically, unlike upstream camlpdf's `Pdfpage` helpers): walk
/// `page_dict`, then its `/Parent` chain, returning the first `/MediaBox`
/// found as `(x0, y0, x1, y1)` in raw PDF points. `None`
/// if no ancestor carries a well-formed 4-element numeric array, or if a
/// `/Parent` cycle is detected.
#[cfg(feature = "pdf-image")]
fn resolve_pdf_media_box(
    doc: &lopdf::Document,
    page_dict: &lopdf::Dictionary,
) -> Option<(f64, f64, f64, f64)> {
    let mut cur = page_dict;
    let mut seen: BTreeSet<(u32, u16)> = BTreeSet::new();
    loop {
        if let Ok(obj) = cur.get(b"MediaBox") {
            if let Ok(arr) = obj.as_array() {
                if arr.len() == 4 {
                    let mut v = [0f64; 4];
                    let mut ok = true;
                    for (slot, item) in v.iter_mut().zip(arr.iter()) {
                        match item.as_float() {
                            Ok(f) => *slot = f as f64,
                            Err(_) => {
                                ok = false;
                                break;
                            }
                        }
                    }
                    if ok {
                        return Some((v[0], v[1], v[2], v[3]));
                    }
                }
            }
        }
        match cur.get(b"Parent").and_then(|o| o.as_reference()) {
            Ok(parent_id) => {
                if !seen.insert(parent_id) {
                    return None; // cycle
                }
                cur = doc.get_dictionary(parent_id).ok()?;
            }
            Err(_) => return None,
        }
    }
}

/// Import the page's `/Resources` subtree (walking page-tree inheritance
/// like `resolve_pdf_media_box`) into a neutral `ImportedObjects` table for
/// the PDF writer. Local id `0` always holds the
/// (possibly inline) `/Resources` dictionary itself; every other entry is a
/// real source PDF object number, keyed by `convert_pdf_object`'s
/// transitive walk of every `Reference` reachable from it.
#[cfg(feature = "pdf-image")]
fn import_pdf_resources(doc: &lopdf::Document, page_dict: &lopdf::Dictionary) -> ImportedObjects {
    let mut out: Vec<(u32, ObjRepr)> = Vec::new();
    let mut seen: BTreeSet<u32> = BTreeSet::new();
    let root_repr = match resolve_pdf_resources_object(doc, page_dict) {
        Some(obj) => convert_pdf_object(doc, obj, &mut out, &mut seen),
        None => ObjRepr::Dict(Vec::new()),
    };
    out.insert(0, (0, root_repr));
    ImportedObjects(out)
}

/// `/Resources` lookup with page-tree inheritance, mirroring
/// `resolve_pdf_media_box` but returning the raw (possibly-inline)
/// `&lopdf::Object` rather than a decoded value, since `/Resources` may
/// legally be either a direct dictionary or an indirect reference.
#[cfg(feature = "pdf-image")]
fn resolve_pdf_resources_object<'a>(
    doc: &'a lopdf::Document,
    page_dict: &'a lopdf::Dictionary,
) -> Option<&'a lopdf::Object> {
    let mut cur = page_dict;
    let mut seen: BTreeSet<(u32, u16)> = BTreeSet::new();
    loop {
        if let Ok(obj) = cur.get(b"Resources") {
            return Some(obj);
        }
        match cur.get(b"Parent").and_then(|o| o.as_reference()) {
            Ok(parent_id) => {
                if !seen.insert(parent_id) {
                    return None;
                }
                cur = doc.get_dictionary(parent_id).ok()?;
            }
            Err(_) => return None,
        }
    }
}

/// Recursively convert one `lopdf::Object` into the neutral `ObjRepr`
/// grammar, following every `Reference` transitively and
/// appending newly-visited indirect objects to `out` keyed by their source
/// object number (`seen` guards against re-visiting/cycles — a shared
/// object referenced from multiple places is emitted once and pointed at by
/// `ObjRepr::Ref` from every occurrence). Stream objects are copied
/// **verbatim** (still-filtered bytes, `/Filter`/`/DecodeParms` kept as-is;
/// only `/Length` is dropped since the writer derives it) — unlike the
/// page's own content stream (`Document::get_page_content`, inflated
/// separately in `prim_load_pdf_image`), a resource stream (font program,
/// embedded image XObject, ICC profile, ...) is re-emitted byte-for-byte,
/// so no decode/re-encode risk is taken on data this importer doesn't need
/// to understand.
#[cfg(feature = "pdf-image")]
fn convert_pdf_object(
    doc: &lopdf::Document,
    obj: &lopdf::Object,
    out: &mut Vec<(u32, ObjRepr)>,
    seen: &mut BTreeSet<u32>,
) -> ObjRepr {
    use lopdf::Object as LObj;
    match obj {
        LObj::Null => ObjRepr::Null,
        LObj::Boolean(b) => ObjRepr::Bool(*b),
        LObj::Integer(n) => ObjRepr::Int(*n),
        LObj::Real(r) => ObjRepr::Real(*r as f64),
        LObj::Name(n) => ObjRepr::Name(n.clone()),
        LObj::String(s, _) => ObjRepr::String(s.clone()),
        LObj::Array(items) => ObjRepr::Array(
            items
                .iter()
                .map(|it| convert_pdf_object(doc, it, out, seen))
                .collect(),
        ),
        LObj::Dictionary(d) => ObjRepr::Dict(convert_pdf_dict(doc, d, out, seen)),
        LObj::Stream(s) => {
            let dict_entries = convert_pdf_dict(doc, &s.dict, out, seen)
                .into_iter()
                .filter(|(k, _)| k.as_slice() != b"Length")
                .collect();
            ObjRepr::Stream(dict_entries, s.content.clone())
        }
        LObj::Reference((obj_num, gen)) => {
            let (obj_num, gen) = (*obj_num, *gen);
            if obj_num != 0 && seen.insert(obj_num) {
                if let Ok(target) = doc.get_object((obj_num, gen)) {
                    let repr = convert_pdf_object(doc, target, out, seen);
                    out.push((obj_num, repr));
                }
            }
            ObjRepr::Ref(obj_num)
        }
    }
}

#[cfg(feature = "pdf-image")]
fn convert_pdf_dict(
    doc: &lopdf::Document,
    dict: &lopdf::Dictionary,
    out: &mut Vec<(u32, ObjRepr)>,
    seen: &mut BTreeSet<u32>,
) -> Vec<(Vec<u8>, ObjRepr)> {
    dict.iter()
        .map(|(k, v)| (k.clone(), convert_pdf_object(doc, v, out, seen)))
        .collect()
}

/// `read-file : string -> list string` (dev-0-1-0 vminst.ml:3073
/// `PrimitiveReadFile`) — REAL, with two documented
/// deviations:
///
/// 1. **Path resolution**: resolves `path` against the process's current
///    working directory, the same `load-image` precedent
///    (`prim_load_image`'s doc comment) — this port has no job-directory
///    notion threaded through `Interp` yet. Upstream resolves against
///    `OptionState.job_directory ()` (the input document's own directory).
/// 2. **Containment tightening**: upstream rejects any `..` path component
///    (`"cannot access files by using '..'"`, vminst.ml:3084-3090) but
///    otherwise resolves `Filename.concat jobdir path` literally — an
///    absolute `path` silently escapes the job directory upstream. This
///    port ALSO rejects absolute paths (same error class), making the
///    containment upstream's own message implies actually real.
///
/// Line splitting is faithful to OCaml's `input_line` loop: split on `'\n'`,
/// drop a trailing empty piece (file ends with `\n`), keep `'\r'` (do NOT
/// use `BufRead::lines`, which strips `\r\n`) — an empty file yields `[]`.
/// Non-UTF-8 content is a clean `EvalError` (upstream's OCaml strings are
/// byte-transparent; this port's `Value::Str` must stay valid UTF-8 —
/// documented deviation).
fn prim_read_file(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path_str = as_str(args.pop().unwrap())?;
    let path = std::path::Path::new(&path_str);
    if path.is_absolute() {
        return eval_error(
            "read-file: cannot access files by using an absolute path (job-directory containment)",
        );
    }
    if path
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        return eval_error("cannot access files by using '..'");
    }
    let bytes = std::fs::read(path).map_err(|e| EvalError {
        span: None,
        msg: format!("read-file: cannot open '{path_str}': {e}"),
    })?;
    let text = String::from_utf8(bytes).map_err(|_| EvalError {
        span: None,
        msg: format!("read-file '{path_str}': not valid UTF-8"),
    })?;
    let mut lines: Vec<Value> = text
        .split('\n')
        .map(|s| Value::Str(s.to_string()))
        .collect();
    if matches!(lines.last(), Some(Value::Str(s)) if s.is_empty()) {
        lines.pop();
    }
    Ok(Value::List(lines))
}

/// `(string) option` — `register-document-information`'s `title`/`subject`/
/// `author` fields, parsed the same way [`as_border_option`] reads a
/// `Value::Ctor`.
fn as_option_string(v: Value) -> Result<Option<String>, EvalError> {
    match v {
        Value::Ctor(name, payload) => match (name.as_str(), payload.map(|b| *b)) {
            ("None", None) => Ok(None),
            ("Some", Some(Value::Str(s))) => Ok(Some(s)),
            (other, _) => eval_error(format!(
                "expected a string option (None / Some(string)), got variant '{other}'"
            )),
        },
        other => eval_error(format!("expected an option, got {}", other.type_name())),
    }
}

/// `register-document-information : document-information-dictionary ->
/// unit` (dev-0-1-0 vminst.ml:2978 `PrimitiveRegisterDocumentInformation`)
/// — REAL: extracts `title`/`subject`/`author`
/// (`option string`) and `keywords` (`list string`) from the record
/// argument (`t_doc_info_dictionary()`'s shape, `prim_types.rs`) and stores
/// them onto `Interp::doc_info` — LAST WRITE WINS (upstream's `register`,
/// `documentInformationDictionary.ml`), matching the `outline`/
/// `annotations`/`destinations` accumulator policy (`eval.rs`): reset per
/// trial (fresh `Interp`), the final trial's value drained into
/// `DocExtras::doc_info` (`lib.rs`) and emitted as the PDF `/Info`
/// dictionary by both writers (`rustyfi-pdf`'s `lib.rs`/`cid.rs`).
fn prim_register_document_information(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let fields = match args.pop().unwrap() {
        Value::Record(m) => m,
        other => {
            return eval_error(format!(
                "register-document-information: expected a document-information-dictionary \
                 record, got {}",
                other.type_name()
            ))
        }
    };
    let record_name = "document-information-dictionary";
    let title = as_option_string(record_field(&fields, record_name, "title")?)?;
    let subject = as_option_string(record_field(&fields, record_name, "subject")?)?;
    let author = as_option_string(record_field(&fields, record_name, "author")?)?;
    let keywords = as_list(record_field(&fields, record_name, "keywords")?)?
        .into_iter()
        .map(as_str)
        .collect::<Result<Vec<_>, _>>()?;
    interp.doc_info = Some(DocInfo {
        title,
        subject,
        author,
        keywords,
    });
    Ok(Value::Unit)
}

// ============================================================================
// ---- graphics primitives ------
// `start-path`/`line-to`/`terminate-path`/`close-with-line`/`fill`/`stroke`/
// `inline-graphics`. Argument order matches `tools/gencode/vminst.ml`
// (point-first for `line-to`, width-first for `stroke`).
// ============================================================================

/// `start-path : point -> pre-path` (vminst.ml:713).
fn prim_start_path(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let start = as_point(args.pop().unwrap())?;
    Ok(Value::PrePath(PrePath {
        start,
        segs: Vec::new(),
    }))
}

/// `line-to : point -> pre-path -> pre-path` (vminst.ml:727) — appends a
/// straight segment to the pre-path's forward-accumulated `segs`.
fn prim_line_to(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut pp = as_prepath(args.pop().unwrap())?;
    let pt = as_point(args.pop().unwrap())?;
    pp.segs.push(PathSeg::Line(pt));
    Ok(Value::PrePath(pp))
}

/// `terminate-path : pre-path -> path` (vminst.ml:759) — finishes an OPEN
/// subpath (no closing segment).
fn prim_terminate_path(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let pp = as_prepath(args.pop().unwrap())?;
    Ok(Value::Path(Path {
        subpaths: vec![Subpath {
            start: pp.start,
            segs: pp.segs,
            closing: Closing::Open,
        }],
    }))
}

/// `close-with-line : pre-path -> path` (vminst.ml:773) — closes the subpath
/// with a straight segment back to its start (PDF `h`).
fn prim_close_with_line(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let pp = as_prepath(args.pop().unwrap())?;
    Ok(Value::Path(Path {
        subpaths: vec![Subpath {
            start: pp.start,
            segs: pp.segs,
            closing: Closing::Line,
        }],
    }))
}

/// `fill : color -> path -> graphics` (vminst.ml:2398) — a filled region;
/// the PDF writer (`place_graphics`, rustyfi-pdf) paints it with the
/// even-odd rule, matching upstream's `op_f'`.
fn prim_fill(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path = as_path(args.pop().unwrap())?;
    let color = as_color(args.pop().unwrap())?;
    Ok(Value::Graphics(GraphicsElem::Fill(color, path)))
}

/// `stroke : length -> color -> path -> graphics` (vminst.ml:2381) — width
/// first, then color, then path.
fn prim_stroke(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path = as_path(args.pop().unwrap())?;
    let color = as_color(args.pop().unwrap())?;
    let wid = as_length(args.pop().unwrap())?;
    Ok(Value::Graphics(GraphicsElem::Stroke(wid, color, path)))
}

/// Apply a graphics callback under the eager-call window, returning its
/// resolved elements with every `register-destination` it made appended as a
/// [`GraphicsElem::Destination`] marker. Markers go AFTER the real elements, so
/// ink z-order is untouched and a callback that registers nothing yields the
/// same `elems` as before.
///
/// The window is deliberately NOT opened inside a page-break walk
/// (`current_page` is `Some` — a deco can build an `inline-graphics` of its
/// own): a box built there is drawn straight into `page_graphics`, which
/// `fire_hooks` never re-walks, so a marker minted for it would be silently
/// dropped. There the direct registration is available and correct.
fn apply_graphics_callback(
    interp: &mut Interp,
    version: RustyfiVersion,
    apply: impl FnOnce(&mut Interp) -> Result<Value, EvalError>,
) -> Result<Vec<GraphicsElem>, EvalError> {
    let defer = interp.current_page.is_none();
    let saved = if defer {
        interp.pending_dests.replace(Vec::new())
    } else {
        None
    };
    let result = apply(interp).and_then(|v| coerce_graphics_result_for(version, v));
    let pending = if defer {
        interp.pending_dests.take().unwrap_or_default()
    } else {
        Vec::new()
    };
    if defer {
        interp.pending_dests = saved;
    }
    let mut elems = result?;
    elems.extend(
        pending
            .into_iter()
            .map(|(key, pt)| GraphicsElem::Destination { key, pt }),
    );
    Ok(elems)
}

/// `inline-graphics : length -> length -> length -> (point -> graphics
/// list) -> inline-boxes` (vminst.ml:1872 `BackendInlineGraphics`) — a box
/// of size `(w, h, d)` carrying the callback's resolved graphics elements,
/// the minimal on-page sink for a `graphics` value.
///
/// **Eager-callback shortcut.** Upstream defers the callback until
/// the box's *placed* point is known on the page, then calls
/// `gfun(placed_point)`. A lang closure cannot live inside a backend box
/// (`PureHorzBox::Graphics` only holds resolved `GraphicsElem`s), and the
/// placed point isn't known until page-break/render time — so instead this
/// calls `gfun` immediately at `(0pt, 0pt)`, and the PDF writer
/// (`place_graphics`, rustyfi-pdf) translates the *whole* box to its placed
/// position via a single `cm` at render time. This equals upstream's
/// behavior if and only if `gfun` uses its point argument purely additively
/// (shift-covariant) — true of every real `Gr`/`deco` generator, but not
/// enforced by this signature.
///
/// **The one SIDE EFFECT that survives the shortcut** is
/// `register-destination`: at construction time there is no page, so
/// `annotation.ml:15`'s gate would refuse it and fail the document (azmath's
/// `equation.satyh` anchors every `\label`ed equation this way).
/// [`apply_graphics_callback`] turns each call into a
/// `GraphicsElem::Destination` marker riding in `elems` — rather than a field
/// of its own, so it inherits the `origin_independent` probe below and the
/// existing `fire_hooks`/`shift_graphics` pipeline.
fn prim_inline_graphics(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let gfun = args.pop().unwrap();
    let d = as_length(args.pop().unwrap())?;
    let h = as_length(args.pop().unwrap())?;
    let w = as_length(args.pop().unwrap())?;
    // The callback's result type is `list graphics` under v0.0.6, one
    // `graphics` collection under v0.1 — see `coerce_graphics_result`'s doc
    // comment.
    let gf = gfun.clone();
    let elems = apply_graphics_callback(interp, version, move |it| {
        let origin = make_point_value((Length::ZERO, Length::ZERO));
        it.apply(gf, origin)
    })?;
    // Detect a PAGE-ABSOLUTE callback: run it again at a far-off probe point
    // and compare. If the output is byte-identical the callback ignored its
    // placed-point argument (`fun _ -> …`, e.g. slydifi's frame background /
    // figbox's `draw-text pt`), so its coordinates are already page-absolute
    // and the PDF writer must NOT translate them by the box's placed position
    // (which is often a negative text-origin, shifting the decoration off the
    // page). A position-relative callback yields different output here, so
    // `origin_independent` stays false and the per-box `cm` applies as before.
    // Upstream (`handlePdf.ml`) always calls the callback with the true placed
    // point and never post-translates; this recovers that for the constant
    // case without a post-layout deferral. (The extra evaluation must be free
    // of observable side effects — true of every `Gr`/`draw-text` generator;
    // `register-destination` is captured per call rather than committed, so
    // the probe's copy is dropped.)
    //
    // The comparison includes the markers on purpose: an ANCHOR-ONLY callback
    // draws no ink at either point, so comparing ink alone would classify it
    // page-absolute and pin every anchor at the raw callback argument.
    let origin_independent = {
        let probe = make_point_value((Length::pt(4096.0), Length::pt(2731.0)));
        match apply_graphics_callback(interp, version, move |it| it.apply(gfun, probe)) {
            Ok(e2) => e2 == elems,
            Err(_) => false,
        }
    };
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::Graphics {
            width: w,
            height: h,
            depth: d,
            elems,
            origin_independent,
        },
    )]))
}

/// `inline-graphics-outer : length -> length -> (length -> point -> graphics
/// list) -> inline-boxes` (vminst.ml:1891 `BackendInlineGraphicsOuter`) — a
/// graphics box whose width stretches like `inline-fil` (upstream widinfo
/// `Fils(1)`). The callback needs the RESOLVED width, unknown until line
/// layout, so it is deferred through `Interp::outer_graphics` (the `HookId`
/// pattern) and fired by `resolve_outer_graphics_in_contents` (called from
/// `line-break`/`tabular`/`draw-text`) with the width `justify_line` wrote
/// into the box and the point `(0pt, 0pt)` — the same shift-covariance
/// shortcut as `inline-graphics` above (the writer's `cm` supplies the
/// placed point); the width argument is faithful.
fn prim_inline_graphics_outer(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let gfun = args.pop().unwrap();
    let d = as_length(args.pop().unwrap())?;
    let h = as_length(args.pop().unwrap())?;
    interp.outer_graphics.push((gfun, version));
    let fn_id = GraphicsFnId(interp.outer_graphics.len() - 1);
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::GraphicsOuter {
            height: h,
            depth: d,
            width: Length::ZERO,
            fn_id,
        },
    )]))
}

/// Fire every deferred `inline-graphics-outer` callback in an already-
/// justified run, replacing its `GraphicsOuter` marker with a resolved
/// `Graphics` box (see `prim_inline_graphics_outer`). Idempotent (a resolved
/// box no longer matches) and cheap when nothing matches (one pass, no
/// allocation).
fn resolve_outer_graphics_in_contents(
    interp: &mut Interp,
    contents: &mut [(Length, PureHorzBox)],
) -> Result<(), EvalError> {
    for (_, bx) in contents.iter_mut() {
        if let PureHorzBox::GraphicsOuter {
            height,
            depth,
            width,
            fn_id,
        } = bx
        {
            let (w, h, d) = (*width, *height, *depth);
            let (gfun, gver) = match interp.outer_graphics.get(fn_id.0) {
                Some((f, v)) => (f.clone(), *v),
                None => {
                    return eval_error(format!(
                        "inline-graphics-outer: dangling callback index {}",
                        fn_id.0
                    ))
                }
            };
            // Same per-version coercion as `prim_inline_graphics`
            // above, shared with `tabular`'s per-cell use. The generation is
            // the one the callback was REGISTERED under, carried alongside it in
            // `Interp::outer_graphics`: this pass is a DEFERRED one
            // (`line-break`/`tabular`/`draw-text`), so `interp.version` here
            // is the entry document's, not the callback author's.
            //
            // Deferred to LINE-BREAK time, not page break, so a
            // `register-destination` here still has no page: same capture as
            // `prim_inline_graphics`.
            let elems = apply_graphics_callback(interp, gver, move |it| {
                let partial = it.apply(gfun, Value::Length(w))?;
                it.apply(partial, make_point_value((Length::ZERO, Length::ZERO)))
            })?;
            *bx = PureHorzBox::Graphics {
                width: w,
                height: h,
                depth: d,
                elems,
                origin_independent: false,
            };
        }
    }
    Ok(())
}

/// `tabular : (cell list) list -> (length list -> length list -> graphics
/// list) -> inline-boxes` (vminst.ml:539) — solve the grid (backend
/// `rustyfi_backend::tabular::main`) and eagerly drive the rule callback
/// with the solved box-local grid-line coordinates.
///
/// **Why eager is faithful here, unlike `inline-graphics`.** The callback's
/// arguments are the grid-line coordinates, fully determined by cell
/// content alone (`main` computes them before any placement) — so calling
/// it once at construction time with the true box-local `xs`/`ys` is exactly
/// what upstream's later, placement-time call produces once the PDF
/// writer's per-box `cm` translate (shared with `place_graphics`, see
/// `rustyfi-pdf`) shifts the resulting rule paths into position. No
/// shift-covariance caveat (contrast `prim_inline_graphics` above).
fn prim_tabular(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let rulesf = args.pop().unwrap();
    let rows = as_cell_grid(args.pop().unwrap())?;
    let mut solved = rustyfi_backend::tabular::main(rows);
    for cell in &mut solved.cells {
        resolve_outer_graphics_in_contents(interp, &mut cell.contents)?;
    }

    let xs = make_length_list(&solved.xs);
    let ys = make_length_list(&solved.ys);
    let partial = interp.apply(rulesf, xs)?;
    let gval = interp.apply(partial, ys)?;
    // The rules callback returns `list graphics` under v0.0.6, one
    // `graphics` collection under v0.1 — per the CALLER's generation
    // (`version`), which is the one whose `tabular` type this call was
    // checked against.
    let rules = coerce_graphics_result_for(version, gval)?;

    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::Tabular(TabularBox {
            width: solved.width,
            height: solved.height,
            depth: Length::ZERO,
            cells: solved.cells,
            rules,
        }),
    )]))
}

// ============================================================================
// ---- gr.satyh graphics primitives -------------------------------------------
// ============================================================================

/// `bezier-to : point -> point -> point -> pre-path -> pre-path`
/// (vminst.ml:742) — appends a cubic Bézier segment (`ptS`/`ptT` control
/// points, `pt1` destination) to the pre-path's forward-accumulated `segs`.
fn prim_bezier_to(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut pp = as_prepath(args.pop().unwrap())?;
    let pt1 = as_point(args.pop().unwrap())?;
    let pt_t = as_point(args.pop().unwrap())?;
    let pt_s = as_point(args.pop().unwrap())?;
    pp.segs.push(PathSeg::Bezier(pt_s, pt_t, pt1));
    Ok(Value::PrePath(pp))
}

/// `close-with-bezier : point -> point -> pre-path -> path` (vminst.ml:787)
/// — closes the subpath with a cubic Bézier back to its start (`ptS`/`ptT`
/// control points; the destination is always the subpath's own `start`, per
/// `Closing::Bezier`'s doc comment).
fn prim_close_with_bezier(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let pp = as_prepath(args.pop().unwrap())?;
    let pt_t = as_point(args.pop().unwrap())?;
    let pt_s = as_point(args.pop().unwrap())?;
    Ok(Value::Path(Path {
        subpaths: vec![Subpath {
            start: pp.start,
            segs: pp.segs,
            closing: Closing::Bezier(pt_s, pt_t),
        }],
    }))
}

/// `shift-path : point -> path -> path` (vminst.ml:663) — translate every
/// point of the path by the given vector (`rustyfi_backend::shift_path`).
fn prim_shift_path(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path = as_path(args.pop().unwrap())?;
    let v = as_point(args.pop().unwrap())?;
    Ok(Value::Path(shift_path(v, &path)))
}

/// `linear-transform-path : float -> float -> float -> float -> path ->
/// path` (vminst.ml:678) — apply the 2x2 matrix `(a, b, c, d)` to every
/// point of the path (`rustyfi_backend::linear_transform_path`).
fn prim_linear_transform_path(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let path = as_path(args.pop().unwrap())?;
    let d = as_float(args.pop().unwrap())?;
    let c = as_float(args.pop().unwrap())?;
    let b = as_float(args.pop().unwrap())?;
    let a = as_float(args.pop().unwrap())?;
    Ok(Value::Path(linear_transform_path((a, b, c, d), &path)))
}

/// `shift-graphics : point -> graphics -> graphics` (vminst.ml:2451) —
/// translate every point of the graphics element by the given vector.
fn prim_shift_graphics(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let g = as_graphics(args.pop().unwrap())?;
    let v = as_point(args.pop().unwrap())?;
    Ok(Value::Graphics(shift_graphics(v, &g)))
}

/// `linear-transform-graphics : float -> float -> float -> float -> graphics
/// -> graphics` (vminst.ml:2432). **Eager, unlike upstream**:
/// `graphicD.ml`'s `make_linear_trans` lazily wraps the element in a
/// `LinearTrans` node, deferring the matrix to a PDF `cm` operator at render
/// time — which also scales any wrapped `Stroke`/`DashedStroke`'s effective
/// line width (width is specified in the pre-transform coordinate space).
/// This port instead rewrites every point up front (a pure coordinate map,
/// no PDF change needed) and leaves `width` untouched, so
/// a non-uniform `scale-graphics` (`gr.satyh`) will NOT scale a stroke's
/// line width the way upstream does — invisible for pure rotation
/// (`rotate-graphics`, orthonormal, preserves lengths) and for `Fill`, which
/// is the only `GraphicsElem` shape any bundled package actually
/// strokes-then-scales.
fn prim_linear_transform_graphics(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let g = as_graphics(args.pop().unwrap())?;
    let d = as_float(args.pop().unwrap())?;
    let c = as_float(args.pop().unwrap())?;
    let b = as_float(args.pop().unwrap())?;
    let a = as_float(args.pop().unwrap())?;
    Ok(Value::Graphics(linear_transform_graphics((a, b, c, d), &g)))
}

/// `get-graphics-bbox : graphics -> point * point` (v0.0.6 vminst.ml:2466)
/// — the v006 fork side. `.unwrap_or(…)` is UNREACHABLE under 0.0.6 (no
/// 0.0.6-visible constructor produces `Group`/`Clip`, so `graphics_bbox`
/// never returns `None` here); documented rather than `.expect`ed so a
/// future faithful `Group`/`Clip` leak (a bug) fails soft instead of
/// panicking.
fn prim_get_graphics_bbox_v006(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let g = as_graphics(args.pop().unwrap())?;
    let (pmin, pmax) =
        graphics_bbox(&g).unwrap_or(((Length::ZERO, Length::ZERO), (Length::ZERO, Length::ZERO)));
    Ok(Value::Tuple(vec![
        make_point_value(pmin),
        make_point_value(pmax),
    ]))
}

/// `get-graphics-bbox : graphics -> option (point * point)` (dev-0-1-0
/// vminst.ml:2301) — the v01 fork side: `graphics` is a collection,
/// so an empty `unite-graphics []` (or an empty `Clip`'s contents-blind
/// bbox is still `Some`, but an empty `Group` folds to nothing)
/// legitimately has no bbox — surfaced as the SATySFi `option` variant,
/// the `probe-cross-reference` building pattern.
fn prim_get_graphics_bbox_v01(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let g = as_graphics(args.pop().unwrap())?;
    Ok(match graphics_bbox(&g) {
        Some((pmin, pmax)) => Value::Ctor(
            "Some".to_string(),
            Some(Box::new(Value::Tuple(vec![
                make_point_value(pmin),
                make_point_value(pmax),
            ]))),
        ),
        None => Value::Ctor("None".to_string(), None),
    })
}

/// `unite-graphics : list graphics -> graphics` (dev-0-1-0 vminst.ml:3119)
/// — `GraphicD.concat` = `List.concat`, ported as the `Group` container.
/// `unite-graphics []` is legal and yields the
/// empty collection (the `None`-bbox witness `get-graphics-bbox` exercises
/// above).
fn prim_unite_graphics(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let items = as_list(args.pop().unwrap())?;
    let mut elems = Vec::with_capacity(items.len());
    for it in items {
        elems.push(as_graphics(it)?);
    }
    Ok(Value::Graphics(GraphicsElem::Group(elems)))
}

/// `clip-graphics-by-path : path -> graphics -> graphics` (dev-0-1-0
/// vminst.ml:3105) — `GraphicD.make_clip gr pathlst` = `Clip(paths, gr)`;
/// the port's single-element `g` (possibly itself a `Group`) IS the
/// collection upstream's `gr` argument names.
fn prim_clip_graphics_by_path(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let g = as_graphics(args.pop().unwrap())?;
    let path = as_path(args.pop().unwrap())?;
    Ok(Value::Graphics(GraphicsElem::Clip(path, vec![g])))
}

/// `get-path-bbox : path -> point * point` (vminst.ml:696
/// `PathGetBoundingBox`) — `rustyfi_backend::path_bbox` (see that function's
/// doc comment for the exact cubic-extrema policy shared with
/// `get-graphics-bbox`).
fn prim_get_path_bbox(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path = as_path(args.pop().unwrap())?;
    let (pmin, pmax) = path_bbox(&path);
    Ok(Value::Tuple(vec![
        make_point_value(pmin),
        make_point_value(pmax),
    ]))
}

/// `dashed-stroke : length -> (length*length*length) -> color -> path ->
/// graphics` (vminst.ml:2414) — width first, then the dash pattern, then
/// color, then path (mirrors `stroke`'s argument order with one extra
/// dash-pattern argument inserted).
fn prim_dashed_stroke(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let path = as_path(args.pop().unwrap())?;
    let color = as_color(args.pop().unwrap())?;
    let dash = as_dash(args.pop().unwrap())?;
    let wid = as_length(args.pop().unwrap())?;
    Ok(Value::Graphics(GraphicsElem::DashedStroke(
        wid, dash, color, path,
    )))
}

/// `draw-text : point -> inline-boxes -> graphics` (vminst.ml:2363
/// `PrimitiveDrawText`) — FAITHFUL: lays the run out at natural width
/// (upstream `LineBreak.natural`; here `natural_metrics` + `fit_cell` at that
/// width, so slack is 0 and every box keeps its natural advance) and stores
/// the placed run in `GraphicsElem::Text`. Also resolves any
/// `inline-graphics-outer` marker the run carries (`resolve_outer_graphics_
/// in_contents` — width 0 there, since slack is 0 at natural width, upstream
/// identical: `widperfil = 0`).
fn prim_draw_text(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ib = as_inline_boxes(args.pop().unwrap())?;
    let pt = as_point(args.pop().unwrap())?;
    let (width, height, depth) = natural_metrics(&ib);
    let (mut contents, _, _) = fit_cell(ib, width);
    resolve_outer_graphics_in_contents(interp, &mut contents)?;
    Ok(Value::Graphics(GraphicsElem::Text {
        pt,
        contents,
        width,
        height,
        depth,
        transform: None,
    }))
}

// ============================================================================
// ---- pervasives.satyh prims -------------------
// ============================================================================

/// `get-natural-metrics : inline-boxes -> length * length * length`
/// (vminst.ml:2020 `PrimitiveGetNaturalMetrics`) — FAITHFUL: delegates to
/// `rustyfi_backend::natural_metrics` (see that function's doc comment for
/// why no depth sign-flip is needed here, unlike upstream).
fn prim_get_natural_metrics(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ib = as_inline_boxes(args.pop().unwrap())?;
    let (width, height, depth) = natural_metrics(&ib);
    Ok(Value::Tuple(vec![
        Value::Length(width),
        Value::Length(height),
        Value::Length(depth),
    ]))
}

/// Build the atomic `PureHorzBox::Frame` for `inline-frame-outer`/`-inner`
/// (upstream keeps both atomic too; `-breakable` is transparent instead, see
/// [`prim_inline_frame_breakable`]): fit `inner` at its natural width
/// (`fit_cell` — the same
/// no-Context fit tabular cells use), pad the fitted run by `pads`, intern
/// `deco` into `interp.decos`. `deco` is fired lang-side, after
/// placement, by `fire_hooks`/`fire_inline_frame` — this constructor never
/// calls it.
fn make_inline_frame(
    interp: &mut Interp,
    version: RustyfiVersion,
    (pad_l, pad_r, pad_t, pad_b): (Length, Length, Length, Length),
    deco: Value,
    inner: Vec<HorzBox>,
) -> Value {
    let (w, _, _) = natural_metrics(&inner);
    let (contents, height, depth) = fit_cell(inner, w);
    let contents = contents.into_iter().map(|(x, b)| (x + pad_l, b)).collect();
    let id = DecoId(interp.decos.len());
    // `version` is the CALLING code's generation, threaded in by the
    // per-version prim rows below — fire time is a post-page-break pass with
    // no version context of its own, so this is the only moment the answer
    // is available. See `DecoEntry`'s doc comment.
    interp.decos.push(DecoEntry::Inline { deco, version });
    Value::InlineBoxes(vec![HorzBox::Pure(PureHorzBox::Frame {
        width: pad_l + w + pad_r,
        height: height + pad_t,
        depth: depth + pad_b,
        deco: id,
        contents,
    })])
}

/// `inline-frame-outer : paddings -> deco -> inline-boxes -> inline-boxes`
/// (vminst.ml:1787 `BackendOuterFrame`) — FAITHFUL: builds the atomic
/// `PureHorzBox::Frame`; see [`make_inline_frame`]. Upstream's
/// outer/inner distinction is glue participation in the enclosing line
/// (`PHGOuterFrame` vs `PHGInnerFrame`), which this atomic box model
/// collapses — both this and [`prim_inline_frame_inner`] build the exact
/// same box.
fn prim_inline_frame_outer(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let inner = as_inline_boxes(args.pop().unwrap())?;
    let deco = args.pop().unwrap();
    let pads = as_paddings(args.pop().unwrap())?;
    Ok(make_inline_frame(interp, version, pads, deco, inner))
}

/// `inline-frame-inner : paddings -> deco -> inline-boxes -> inline-boxes`
/// (vminst.ml:1807 `BackendInnerFrame`) — same construction as
/// [`prim_inline_frame_outer`]; see that function's doc comment for the
/// outer/inner distinction this atomic model collapses.
fn prim_inline_frame_inner(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let inner = as_inline_boxes(args.pop().unwrap())?;
    let deco = args.pop().unwrap();
    let pads = as_paddings(args.pop().unwrap())?;
    Ok(make_inline_frame(interp, version, pads, deco, inner))
}

/// `set-manual-rising : length -> context -> context` (vminst.ml:1661
/// `PrimitiveSetManualRising`) — FAITHFUL store into
/// `Context::manual_rising`, the same shape as `set-font-size`/
/// `set-leading` above. Read by `text_to_boxes`'s `flush_word`, which adds
/// it to the script font's own baseline raise; the default is
/// `Length::ZERO`, so a document that never calls this is unaffected.
fn prim_set_manual_rising(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let rising = as_length(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        manual_rising: rising,
        ..ctx
    })))
}

/// `script-guard : script -> inline-boxes -> inline-boxes` (vminst.ml:1908
/// `BackendScriptGuard`).
///
/// STAND-IN: upstream wraps `hblst` in a `HorzScriptGuard` that tells the
/// line breaker which script to assume at each edge, for inter-script
/// spacing rules (`lineBreak.ml`'s script-boundary handling). This port's
/// line breaker has no script-aware spacing at all yet, so this is the
/// identity function: the `script` argument is accepted (so callers like
/// pervasives.satyh's `\SATySFi`/`\LaTeX`/`\TeX` type-check and run) and
/// discarded.
fn prim_script_guard(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ib = as_inline_boxes(args.pop().unwrap())?;
    let _script = args.pop().unwrap();
    Ok(Value::InlineBoxes(ib))
}

/// Unwrap `inline-boxes`' `Vec<HorzBox>` down to the bare `Vec<PureHorzBox>`
/// a `PureHorzBox::Discretionary` slot stores (mirrors `prim_line_break`'s
/// identical unwrap, linebreak.rs's only other consumer of this shape).
fn into_pure(boxes: Vec<HorzBox>) -> Vec<PureHorzBox> {
    boxes.into_iter().map(|HorzBox::Pure(p)| p).collect()
}

/// `discretionary : int -> inline-boxes -> inline-boxes -> inline-boxes ->
/// inline-boxes` (vminst.ml:1969 `BackendDiscretionary`), params `(pb,
/// hblst0, hblst1, hblst2)` — FAITHFUL: builds the same
/// `PureHorzBox::Discretionary` the UAX#14 line breaker already produces
/// internally. `hblst0` (`no_break`) renders when this point is NOT chosen
/// as a line break; `hblst1`/`hblst2` (`pre_break`/`post_break`) render at
/// the end/start of the two lines a break here would produce.
fn prim_discretionary(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let post_break = as_inline_boxes(args.pop().unwrap())?;
    let pre_break = as_inline_boxes(args.pop().unwrap())?;
    let no_break = as_inline_boxes(args.pop().unwrap())?;
    let penalty = as_int(args.pop().unwrap())?;
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::Discretionary {
            penalty: penalty.clamp(i32::MIN as i64, i32::MAX as i64) as i32,
            pre_break: into_pure(pre_break),
            post_break: into_pure(post_break),
            no_break: into_pure(no_break),
        },
    )]))
}

/// `get-axis-height : context -> length` (vminst.ml:1739
/// `PrimitiveGetAxisHeight`), needed by `picture.satyh`'s `Picture.node`
/// (Tier-2 decoration/graphics wave) — centers text vertically around the
/// math axis.
///
/// FAITHFUL: reads `axis_height` from `ctx.math_font`'s OpenType MATH
/// table via `MathC` (`FontInfo.get_axis_height mfabbrev fontsize`), falling
/// back to a fixed `0.25` ratio of `ctx.font_size` (`pervasives.satyh`'s
/// `\SATySFi`/`\LaTeX` manual-rising ratio) whenever the font has no MATH
/// table — so base-14/non-math output is unchanged.
fn prim_get_axis_height(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let mc = MathC::of(interp, &ctx);
    Ok(Value::Length(mc.axis(ctx.font_size)))
}

// ============================================================================
// ---- page-break hooks + cross-references -----------------------------------
// ============================================================================

/// `hook-page-break : (page-break-info -> point -> unit) -> inline-boxes`
/// (vminstdef.yaml:576). Pushes the closure argument onto `interp.hooks`
/// (the lang-side table `fire_hooks` reads back after placement) and
/// returns an inline box carrying only the opaque `HookId` — exactly
/// `prim_load_image`'s shape (`ImageId`/`interp.images`), applied to a
/// deferred *computation* instead of a resource. The backend places this
/// box like any other zero-width content and never sees the closure.
fn prim_hook_page_break(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let closure = args.pop().unwrap();
    let id = HookId(interp.hooks.len());
    interp.hooks.push(closure);
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::HookPageBreak { id },
    )]))
}

/// `hook-page-break-block : (page-break-info -> point -> unit) ->
/// block-boxes` (vminst.ml:632 `BackendHookPageBreakBlock`) — the
/// block-level analog of `prim_hook_page_break` above, FAITHFUL: same
/// `interp.hooks` push, same opaque `HookId`, but wrapped in a
/// `VertBox::HookPageBreak` marker instead of an inline box. `chop_page`/
/// `place_block_at` (rustyfi-backend) place it as a zero-height
/// `PlacedLine` carrying the SAME `PureHorzBox::HookPageBreak` wrapper the
/// inline primitive uses, so `fire_hooks` (lib.rs) fires it through the
/// exact same scan with no changes of its own.
fn prim_hook_page_break_block(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let closure = args.pop().unwrap();
    let id = HookId(interp.hooks.len());
    interp.hooks.push(closure);
    Ok(Value::BlockBoxes(vec![VertBox::HookPageBreak(id)]))
}

/// `register-cross-reference : string -> string -> unit` (vminstdef.yaml:1793).
/// Callable anywhere (not just from a hook) — ordinary strict primitive
/// over the shared `crossrefs` table.
fn prim_register_cross_reference(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let value = as_str(args.pop().unwrap())?;
    let key = as_str(args.pop().unwrap())?;
    interp.crossrefs.borrow_mut().register(key, value);
    Ok(Value::Unit)
}

/// `get-cross-reference : string -> string option` (vminstdef.yaml:1808).
/// A miss is recorded (`CrossRefs::get`) so an unresolved forward reference
/// forces another fixpoint trial; the result surfaces as the SATySFi
/// `option` variant (`None` / `Some(string)`).
fn prim_get_cross_reference(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let key = as_str(args.pop().unwrap())?;
    Ok(match interp.crossrefs.borrow_mut().get(&key) {
        Some(v) => Value::Ctor("Some".to_string(), Some(Box::new(Value::Str(v)))),
        None => Value::Ctor("None".to_string(), None),
    })
}

/// `probe-cross-reference : string -> string option` (vminst.ml:3043
/// `BackendProbeCrossReference`) — FAITHFUL: `get-cross-reference` minus the
/// miss bookkeeping (`CrossRefs::probe`, crossRef.ml:112), so a `None` here
/// never forces another fixpoint trial.
fn prim_probe_cross_reference(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let key = as_str(args.pop().unwrap())?;
    Ok(match interp.crossrefs.borrow().probe(&key) {
        Some(v) => Value::Ctor("Some".to_string(), Some(Box::new(Value::Str(v)))),
        None => Value::Ctor("None".to_string(), None),
    })
}

// ============================================================================
// ---- annot.satyh's prim surface (link annotations + the frame/script
// stand-ins it needs) --------------------------------------------------------
// ============================================================================

/// `get-leftmost-script`/`get-rightmost-script : inline-boxes -> script
/// option` (vminstdef.yaml:1754/1767 `BackendGetLeftmostScript`/
/// `BackendGetRightmostScript`) — STAND-IN: upstream inspects the actual
/// Unicode script of the first/last character in `hblst`
/// (`LineBreak.get_leftmost_script`/`get_rightmost_script`), which
/// `annot.satyh`'s `\href` uses to `script-guard` the link's edges so
/// inter-script spacing isn't inserted right at the boundary. This port's
/// `PureHorzBox::InnerString` carries no per-character script tag (no
/// script-aware line breaking at all yet — `script-guard` above is already
/// an identity stand-in for the same reason), so both primitives
/// unconditionally return `None`: `\href` then takes its `None` arm
/// (`inline-nil`, no guard inserted) — a safe, honest default rather than
/// fabricating a script this port cannot actually see.
fn prim_get_leftmost_script(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let _ib = as_inline_boxes(args.pop().unwrap())?;
    Ok(Value::Ctor("None".to_string(), None))
}

/// See [`prim_get_leftmost_script`] — the rightmost-edge twin, identical
/// stand-in reasoning.
fn prim_get_rightmost_script(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let _ib = as_inline_boxes(args.pop().unwrap())?;
    Ok(Value::Ctor("None".to_string(), None))
}

/// `inline-frame-breakable : paddings -> deco-set -> inline-boxes ->
/// inline-boxes` (vminstdef.yaml:1672 `BackendOuterFrameBreakable`) —
/// FAITHFUL: upstream's `HorzFrameBreakable` is *transparent* to the
/// paragraph breaker (`lineBreak.ml:1094` threads the enclosing width map
/// straight through the frame's contents), so the frame's own glue and
/// discretionaries are break candidates of the enclosing paragraph, and
/// `cut` (`:824`) re-frames the chosen fragments one line at a time —
/// `decoS` for a frame that came out unbroken, `decoH`/`decoM`/`decoT` per
/// fragment for one that split.
///
/// This port's breaker is a flat index DP rather than upstream's recursive
/// one, so transparency is spelled by SPLICING: the contents go straight into
/// the returned box list, bracketed by a zero-width
/// [`PureHorzBox::InlineFrameMarker`] pair that `fire_hooks` walks to
/// reassemble the fragments and fire the right closure for each. The
/// horizontal paddings become `FixedEmpty` boxes inside the bracket, exactly
/// upstream's `append_horz_padding` (`lineBreak.ml:79`); the vertical ones
/// ride on the markers (which is how they still reach the line's height and
/// depth) and are re-applied per fragment at fire time.
///
/// The atomic `PureHorzBox::Frame` is NOT usable here — it fires only
/// `decoS` and, being width-rigid, can neither break nor let an interior
/// `inline-fil` stretch. It is reserved for `inline-frame-outer`/`-inner`,
/// which upstream really does keep atomic.
fn prim_inline_frame_breakable(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let inner = as_inline_boxes(args.pop().unwrap())?;
    let decoset = as_decoset(args.pop().unwrap())?;
    let (pad_l, pad_r, pad_t, pad_b) = as_paddings(args.pop().unwrap())?;
    let (_, height, depth) = natural_metrics(&inner);
    let id = DecoId(interp.decos.len());
    // `version` is the CALLING code's generation — see `make_inline_frame`'s
    // identical comment and `DecoEntry`'s doc comment.
    interp.decos.push(DecoEntry::InlineBreakable {
        pads: Paddings {
            l: pad_l,
            r: pad_r,
            t: pad_t,
            b: pad_b,
        },
        decoset,
        version,
    });
    let marker = |end| {
        HorzBox::Pure(PureHorzBox::InlineFrameMarker {
            id,
            end,
            height: height + pad_t,
            depth: depth + pad_b,
        })
    };
    let mut out = Vec::with_capacity(inner.len() + 4);
    out.push(marker(false));
    // Upstream emits both padding boxes unconditionally; a zero-width
    // `FixedEmpty` is inert everywhere in this port too, but skipping it keeps
    // the box stream (and every placed-line snapshot) unchanged for the
    // zero-padding callers, which is every bundled one.
    if pad_l != Length::ZERO {
        out.push(HorzBox::Pure(PureHorzBox::FixedEmpty { width: pad_l }));
    }
    out.extend(inner);
    if pad_r != Length::ZERO {
        out.push(HorzBox::Pure(PureHorzBox::FixedEmpty { width: pad_r }));
    }
    out.push(marker(true));
    Ok(Value::InlineBoxes(out))
}

/// `deco-set` = `Value::Tuple` of 4 closures (`(decoS, decoH, decoM,
/// decoT)`, evalUtil.ml:169 `get_decoset`) — no type check on the elements
/// themselves (they're closures, applied later by `apply_deco`).
fn as_decoset(v: Value) -> Result<[Value; 4], EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 4 => {
            let mut it = vs.into_iter();
            let a = it.next().unwrap();
            let b = it.next().unwrap();
            let c = it.next().unwrap();
            let d = it.next().unwrap();
            Ok([a, b, c, d])
        }
        other => eval_error(format!(
            "expected a deco-set (4-tuple of decorations), got {}",
            other.type_name()
        )),
    }
}

/// 0.0.6 graphics-producing callbacks return `list graphics` (`tL tGR`);
/// 0.1's return one `graphics` collection (`tGR` — dev-0-1-0
/// `primitives.cppo.ml:75-85`). STRICT per
/// version: a 0.1 program returning a list here is a bug the type checker
/// already rejected; don't mask it with tolerant decoding. Shared by every
/// coercion site (`prim_inline_graphics`, `inline-graphics-outer`/
/// `tabular`'s `resolve_outer_graphics_in_contents`, `tabular`'s own rules
/// callback, and `apply_deco` below).
///
/// `version` is EXPLICIT rather than read off `interp.version`, and that is
/// the whole point. `interp.version` is one whole-program field, set once by
/// `lib.rs`'s `eval_document_trials`; in a cross-version program it names
/// the ENTRY document's generation, while the callback being decoded here
/// may have been written by a spliced 0.0.6 dependency. Every caller gets
/// the right answer from a place that genuinely knows it: the six carrier
/// prim bodies are registered per version
/// (`version_forked_prims!`, folded at compile time by
/// `compile.rs`'s `Ast::VersionScope` arm), and the two DEFERRED consumers
/// read the generation captured when the closure was interned
/// (`DecoEntry::version`, `Interp::outer_graphics`'s second component).
fn coerce_graphics_result_for(
    version: RustyfiVersion,
    v: Value,
) -> Result<Vec<GraphicsElem>, EvalError> {
    if version.graphics_is_collection() {
        Ok(vec![as_graphics(v)?])
    } else {
        as_list(v)?.into_iter().map(as_graphics).collect()
    }
}

/// `make_frame_deco` (evalUtil.ml:604): apply a curried
/// `point -> length -> length -> length -> graphics list` deco and coerce
/// the result. Depths here are already user-sign (nonnegative), so no
/// negate (upstream negates because ITS internal depths are nonpositive).
/// The deco closure's result is `list graphics` under v0.0.6, one `graphics`
/// collection under v0.1 — see `coerce_graphics_result`'s doc comment.
///
/// `version` is the generation the closure was CAPTURED under
/// (`DecoEntry::version`), not `interp.version`: this runs from `lib.rs`'s
/// post-page-break firing pass, which is outside every `VersionScope`
/// window, so `interp.version` there is the entry document's generation. In
/// a single-version program the two are the same value.
pub(crate) fn apply_deco(
    interp: &mut Interp,
    version: RustyfiVersion,
    deco: Value,
    pt: Point,
    w: Length,
    h: Length,
    d: Length,
) -> Result<Vec<GraphicsElem>, EvalError> {
    let v = interp.apply(deco, make_point_value(pt))?;
    let v = interp.apply(v, Value::Length(w))?;
    let v = interp.apply(v, Value::Length(h))?;
    let v = interp.apply(v, Value::Length(d))?;
    coerce_graphics_result_for(version, v)
}

/// `(length * color) option` — `register-link-to-uri`/`-to-location`'s
/// trailing border argument (vminstdef.yaml:2755/2775's `vborderopt`),
/// parsed the same way [`as_color`]/[`as_page`] read a `Value::Ctor`.
fn as_border_option(v: Value) -> Result<Option<(Length, Color)>, EvalError> {
    match v {
        Value::Ctor(name, payload) => match (name.as_str(), payload.map(|b| *b)) {
            ("None", None) => Ok(None),
            ("Some", Some(Value::Tuple(vs))) if vs.len() == 2 => {
                let mut it = vs.into_iter();
                let w = as_length(it.next().unwrap())?;
                let c = as_color(it.next().unwrap())?;
                Ok(Some((w, c)))
            }
            (other, _) => eval_error(format!(
                "expected a border option (None / Some(length * color)), got variant '{other}'"
            )),
        },
        other => eval_error(format!("expected an option, got {}", other.type_name())),
    }
}

/// `register-destination : string -> point -> unit` (vminstdef.yaml:2738) —
/// FAITHFUL: upstream `NamedDest.register` + `notify_pagebreak` collapsed
/// into one step, since our firing window (`fire_hooks`) already knows the
/// page. Errors outside that window (`annotation.ml:15`'s
/// `State.during_page_break` gate).
///
/// **ONE exception, a re-timing rather than a relaxation of the gate.** Inside
/// an eagerly-applied `inline-graphics` callback this port is running code
/// upstream would only run DURING page breaking (see `prim_inline_graphics`),
/// so refusing here would refuse a call upstream accepts. Such a call is
/// recorded in `Interp::pending_dests` instead, and the caller mints a
/// `GraphicsElem::Destination` marker from it. Outside that one window the gate
/// is unchanged: no page, no destination.
fn prim_register_destination(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let (x, y) = as_point(args.pop().unwrap())?;
    let key = as_str(args.pop().unwrap())?;
    if interp.current_page.is_none() {
        if let Some(pending) = interp.pending_dests.as_mut() {
            pending.push((key, (x, y)));
            return Ok(Value::Unit);
        }
    }
    let Some(page) = interp.current_page else {
        return eval_error(
            "register-destination can only be called during page breaking \
             (from a page-break hook or a decoration)",
        );
    };
    let name = interp.dest_name(&key);
    // See `prim_register_link_to_uri`'s identical comment —
    // `register-location-frame`'s `decoR` fires this from inside a firing
    // block-frame deco.
    if let Some(deco_id) = interp.current_deco_id {
        interp.dest_decos.push((deco_id, name.clone()));
    }
    interp.destinations.push(NamedDest { page, name, x, y });
    Ok(Value::Unit)
}

/// Shared body of `register-link-to-uri` / `register-link-to-location`
/// (vminstdef.yaml:2753/2773): pops the common `point/w/h/d/border` suffix,
/// builds `annotation.ml:22`'s rect `(x, y - d, x + w, y + h)` (PDF y-up
/// points; our depths are already nonnegative), and pushes the `Annot`.
fn register_link(
    interp: &mut Interp,
    mut args: Vec<Value>,
    prim_name: &str,
    make_action: impl FnOnce(&mut Interp, String) -> AnnotAction,
) -> Result<Value, EvalError> {
    let border = as_border_option(args.pop().unwrap())?;
    let dpt = as_length(args.pop().unwrap())?;
    let hgt = as_length(args.pop().unwrap())?;
    let wid = as_length(args.pop().unwrap())?;
    let (x, y) = as_point(args.pop().unwrap())?;
    let target = as_str(args.pop().unwrap())?;
    let Some(page) = interp.current_page else {
        return eval_error(format!(
            "{prim_name} can only be called during page breaking \
             (from a page-break hook or a decoration)"
        ));
    };
    let action = make_action(interp, target);
    // Tag this link with the DecoId of whatever deco closure is currently
    // firing (set by `fire_hooks`'s two `apply_deco` call sites, `lib.rs`) —
    // `annot.satyh`'s `\href` always calls this from inside one, so
    // `current_deco_id` is `Some` for every real `\href`; a hand-built test
    // calling this prim directly (not through a firing deco) legitimately
    // leaves it `None`, and the reflow backend just won't find a Frame to
    // wrap for that link.
    if let Some(deco_id) = interp.current_deco_id {
        interp.link_decos.push((deco_id, action.clone()));
    }
    interp.annotations.push(Annot {
        page,
        rect: (x, y - dpt, x + wid, y + hgt),
        action,
        border,
    });
    Ok(Value::Unit)
}

/// `register-link-to-uri : string -> point -> length -> length -> length ->
/// (length * color) option -> unit` (vminstdef.yaml:2753
/// `BackendRegisterLinkToUri`) — FAITHFUL: see [`register_link`].
fn prim_register_link_to_uri(interp: &mut Interp, args: Vec<Value>) -> Result<Value, EvalError> {
    register_link(interp, args, "register-link-to-uri", |_, uri| {
        AnnotAction::Uri(uri)
    })
}

/// `register-link-to-location : string -> point -> length -> length ->
/// length -> (length * color) option -> unit` (vminstdef.yaml:2773
/// `BackendRegisterLinkToLocation`) — FAITHFUL: same shape as
/// [`prim_register_link_to_uri`], but upstream's action is
/// `GotoName(NamedDest.get name)` — the key goes through the SAME name table
/// as [`prim_register_destination`], so a link to a not-(yet-)registered
/// destination still mints a stable name (a viewer no-ops on it), exactly
/// like upstream.
fn prim_register_link_to_location(
    interp: &mut Interp,
    args: Vec<Value>,
) -> Result<Value, EvalError> {
    register_link(interp, args, "register-link-to-location", |interp, key| {
        AnnotAction::GotoName(interp.dest_name(&key))
    })
}

// ============================================================================
// The faithful `Value::Math` primitive layer `math.satyh` is built
// out of. Every `math-*` primitive here builds or consumes a
// `Value::Math(Rc<Vec<Math>>)` (`value.rs`'s `Math`); a `math`-typed
// argument may equally arrive as a `Value::MathText` (a `${…}` literal —
// `as_math` accepts either, reflecting a `MathText`'s `MathElem` tree into
// `Math` nodes on the fly, see below).
// ============================================================================

use crate::value::{Math, MathElement, MathVariantStyle};

/// `math-class` = `Value::Ctor("MathOrd"|"MathBin"|…, None)` — mirrors
/// `as_color`/`as_page`'s shape exactly.
fn as_math_kind(v: Value) -> Result<MathKind, EvalError> {
    match v {
        Value::Ctor(name, None) => match name.as_str() {
            "MathOrd" => Ok(MathKind::Ord),
            "MathBin" => Ok(MathKind::Bin),
            "MathRel" => Ok(MathKind::Rel),
            "MathOp" => Ok(MathKind::Op),
            "MathPunct" => Ok(MathKind::Punct),
            "MathOpen" => Ok(MathKind::Open),
            "MathClose" => Ok(MathKind::Close),
            "MathPrefix" => Ok(MathKind::Prefix),
            "MathInner" => Ok(MathKind::Inner),
            other => eval_error(format!("expected a math-class constructor, got '{other}'")),
        },
        other => eval_error(format!("expected a math-class, got {}", other.type_name())),
    }
}

/// `math-char-class` = `Value::Ctor("MathItalic"|…, None)`, resolved to the
/// backend's [`MathCharClass`] (see `value.rs`'s
/// `Math::ChangeCharClass` doc comment).
fn as_math_char_class(v: Value) -> Result<MathCharClass, EvalError> {
    match v {
        Value::Ctor(name, None) => match name.as_str() {
            "MathItalic" => Ok(MathCharClass::Italic),
            "MathBoldItalic" => Ok(MathCharClass::BoldItalic),
            "MathRoman" => Ok(MathCharClass::Roman),
            "MathBoldRoman" => Ok(MathCharClass::BoldRoman),
            "MathScript" => Ok(MathCharClass::Script),
            "MathBoldScript" => Ok(MathCharClass::BoldScript),
            "MathFraktur" => Ok(MathCharClass::Fraktur),
            "MathBoldFraktur" => Ok(MathCharClass::BoldFraktur),
            "MathDoubleStruck" => Ok(MathCharClass::DoubleStruck),
            // V0_1-only registration — these 5
            // ctor names are only ever declared by `builtin_variants` under
            // V0_1, so under V0_0 this arm is simply never reached: the
            // ctor name itself is rejected earlier, at typecheck, as
            // unknown.
            "MathSansSerif" => Ok(MathCharClass::SansSerif),
            "MathBoldSansSerif" => Ok(MathCharClass::BoldSansSerif),
            "MathItalicSansSerif" => Ok(MathCharClass::ItalicSansSerif),
            "MathBoldItalicSansSerif" => Ok(MathCharClass::BoldItalicSansSerif),
            "MathTypewriter" => Ok(MathCharClass::Typewriter),
            other => eval_error(format!(
                "expected a math-char-class constructor, got '{other}'"
            )),
        },
        other => eval_error(format!(
            "expected a math-char-class, got {}",
            other.type_name()
        )),
    }
}

/// `math-variant-char`'s 9-field style record (`value.rs`'s
/// `MathVariantStyle`; `prim_types::t_math_variant_style`'s runtime
/// counterpart).
fn as_math_variant_style(v: Value) -> Result<MathVariantStyle, EvalError> {
    match v {
        Value::Record(mut fields) => {
            let mut take = |label: &str| -> Result<String, EvalError> {
                match fields.remove(label) {
                    Some(v) => as_str(v),
                    None => eval_error(format!(
                        "math-variant-char style record missing field '{label}'"
                    )),
                }
            };
            Ok(MathVariantStyle {
                italic: take("italic")?,
                bold_italic: take("bold-italic")?,
                roman: take("roman")?,
                bold_roman: take("bold-roman")?,
                script: take("script")?,
                bold_script: take("bold-script")?,
                fraktur: take("fraktur")?,
                bold_fraktur: take("bold-fraktur")?,
                double_struck: take("double-struck")?,
            })
        }
        other => eval_error(format!(
            "expected a math-variant-char style record, got {}",
            other.type_name()
        )),
    }
}

/// A `math` argument: either an already-faithful `Value::Math` (built by
/// another `math-*` primitive), or a `${…}` literal `Value::MathText`,
/// reflected into `Math` nodes on the fly via [`reflect_math_elem`] — see
/// `value.rs`'s `Value::Math` doc comment for why both are interchangeable.
fn as_math(interp: &mut Interp, v: Value) -> Result<Rc<Vec<Math>>, EvalError> {
    match v {
        Value::Math(m) => Ok(m),
        Value::MathText { elems, env } => {
            let mut out = Vec::new();
            for e in elems.iter() {
                reflect_math_elem(interp, e, &env, &mut out)?;
            }
            Ok(Rc::new(out))
        }
        other => eval_error(format!("expected math, got {}", other.type_name())),
    }
}

/// Reflect one elaborated `${…}` literal `MathElem` (a fused,
/// math-class-free form) into zero-or-more faithful `Math` atoms, pushed
/// onto `out` — the "less churn" resolution:
/// `MathElem` stays the fast path for a bare `${x^2}` in prose
/// (`read_inline`'s `EmbedMath` arm, untouched), and only gets reflected
/// into `Value::Math` at a command/primitive boundary (here — whenever a
/// `${…}` literal is passed where a faithful `math` value is expected).
/// `Cmd`/`Embed` are resolved by actually evaluating them against `env` (the
/// literal's own captured environment) and recursively reflecting/flattening
/// the result — the "Embed of a `#…` program value that itself
/// evaluates to math" case.
fn reflect_math_elem(
    interp: &mut Interp,
    elem: &MathElem,
    env: &Env,
    out: &mut Vec<Math>,
) -> Result<(), EvalError> {
    match elem {
        MathElem::Chars(s) => {
            // One atom per MATHCHAR token ("one atom per run" —
            // the lexer already grouped a symbol run or a single latin
            // digit/letter into `s`); class + codepoint remap are both
            // deferred to `layout_math_atom`'s `VariantCharPending` arm,
            // where `Context::math_class_map`/`math_variant_char_map` and
            // the current font are available.
            out.push(Math::Pure(MathElement::VariantCharPending(s.clone())));
            Ok(())
        }
        MathElem::Group(elems) => {
            for e in elems {
                reflect_math_elem(interp, e, env, out)?;
            }
            Ok(())
        }
        MathElem::Sub(base, script) => {
            let mut base_v = Vec::new();
            reflect_math_elem(interp, base, env, &mut base_v)?;
            let mut script_v = Vec::new();
            for e in script {
                reflect_math_elem(interp, e, env, &mut script_v)?;
            }
            out.push(Math::Sub(base_v, script_v));
            Ok(())
        }
        MathElem::Sup(base, script) => {
            let mut base_v = Vec::new();
            reflect_math_elem(interp, base, env, &mut base_v)?;
            let mut script_v = Vec::new();
            for e in script {
                reflect_math_elem(interp, e, env, &mut script_v)?;
            }
            out.push(Math::Sup(base_v, script_v));
            Ok(())
        }
        MathElem::Primes(base, n) => {
            let mut base_v = Vec::new();
            reflect_math_elem(interp, base, env, &mut base_v)?;
            let primes: String = std::iter::repeat('\u{2032}').take(*n).collect();
            out.push(Math::Sup(
                base_v,
                vec![Math::Pure(MathElement::Char {
                    class: MathKind::Ord,
                    big: false,
                    chars: primes,
                })],
            ));
            Ok(())
        }
        MathElem::Cmd { cmd, args, .. } => {
            let mut v = cmd.run(env, interp)?;
            for arg in args {
                // `arg.opts` is always empty here — the math-mode application
                // grammar has no `?(l=e)` bundle form (see `MathElem::Cmd`'s
                // doc comment, `ast.rs`) — but fold through `apply_with_opts`
                // uniformly with `read_inline`/`read_block` regardless.
                let mut opt_vals = Vec::with_capacity(arg.opts.len());
                for (label, e) in &arg.opts {
                    opt_vals.push((label.clone(), e.run(env, interp)?));
                }
                let arg_v = arg.arg.run(env, interp)?;
                v = interp.apply_with_opts(v, opt_vals, arg_v)?;
            }
            let m = as_math(interp, v)?;
            out.extend(m.iter().cloned());
            Ok(())
        }
        MathElem::Embed { expr, span: _ } => {
            let v = expr.run(env, interp)?;
            let m = as_math(interp, v)?;
            out.extend(m.iter().cloned());
            Ok(())
        }
    }
}

fn single_math(m: Math) -> Value {
    Value::Math(Rc::new(vec![m]))
}

// ============================================================================
// V0_1's `math-text`/`math-boxes` split + `read-math`.
// Everything below is additive and V0_1-only — no 0.0.6 path calls any of
// this (`as_math`/`reflect_math_elem`/`single_math` above stay byte-
// identical and untouched).
// ============================================================================

fn single_math_boxes(m: Math) -> Value {
    Value::MathBoxes(Rc::new(vec![m]))
}

/// V0_1 strict `math-boxes` extractor: accepts only `Value::MathBoxes` — a
/// `math-text` literal reaching a V0_1 `math-*` primitive is a genuine 0.1
/// type error (well-typed programs never hit this; it's the runtime
/// fallback for a call built by hand, e.g. from a unit test).
fn as_math_boxes(v: Value) -> Result<Rc<Vec<Math>>, EvalError> {
    match v {
        Value::MathBoxes(m) => Ok(m),
        other => eval_error(format!(
            "expected math-boxes, got {} (V0_1: math-text and math-boxes \
             are distinct types — bridge with `read-math`)",
            other.type_name()
        )),
    }
}

/// V0_1 strict `math-text` extractor: accepts only `Value::MathText`,
/// returning its elements together with the environment they were captured
/// under (needed to evaluate any `#x` embed / math-command lookup inside).
fn as_math_text(v: Value) -> Result<(Rc<Vec<MathElem>>, Env), EvalError> {
    match v {
        Value::MathText { elems, env } => Ok((elems, env)),
        other => eval_error(format!("expected math-text, got {}", other.type_name())),
    }
}

/// `option math-text` extractor (`None`/`Some math-text`) — `%math-attach-
/// scripts`' sub/sup arguments.
fn as_option_math_text(v: Value) -> Result<Option<(Rc<Vec<MathElem>>, Env)>, EvalError> {
    match v {
        Value::Ctor(name, None) if name == "None" => Ok(None),
        Value::Ctor(name, Some(payload)) if name == "Some" => {
            let (elems, env) = as_math_text(*payload)?;
            Ok(Some((elems, env)))
        }
        other => eval_error(format!(
            "expected an option (None/Some), got {}",
            other.type_name()
        )),
    }
}

/// Wrap a raw (ambient-`env`-sharing) script `MathElem` slice as an `option
/// math-text` VALUE — `Cmd`'s uniform V0_1 calling convention always
/// passes its command's sub/sup arguments this way, never pre-reflected.
fn option_math_text_value(opt: Option<&[MathElem]>, env: &Env) -> Value {
    match opt {
        None => Value::Ctor("None".to_string(), None),
        Some(elems) => Value::Ctor(
            "Some".to_string(),
            Some(Box::new(Value::MathText {
                elems: Rc::new(elems.to_vec()),
                env: env.clone(),
            })),
        ),
    }
}

/// `math-char-class` ctor-name mapper — the inverse of `as_math_char_class`
/// (above), used by `get-math-char-class` and by `set-math-variant-char`'s
/// V0_1 body (which must build a `math-char-class` VALUE to feed the
/// caller's selector closure).
fn math_char_class_ctor_name(c: MathCharClass) -> &'static str {
    match c {
        MathCharClass::Italic => "MathItalic",
        MathCharClass::BoldItalic => "MathBoldItalic",
        MathCharClass::Roman => "MathRoman",
        MathCharClass::BoldRoman => "MathBoldRoman",
        MathCharClass::Script => "MathScript",
        MathCharClass::BoldScript => "MathBoldScript",
        MathCharClass::Fraktur => "MathFraktur",
        MathCharClass::BoldFraktur => "MathBoldFraktur",
        MathCharClass::DoubleStruck => "MathDoubleStruck",
        MathCharClass::SansSerif => "MathSansSerif",
        MathCharClass::BoldSansSerif => "MathBoldSansSerif",
        MathCharClass::ItalicSansSerif => "MathItalicSansSerif",
        MathCharClass::BoldItalicSansSerif => "MathBoldItalicSansSerif",
        MathCharClass::Typewriter => "MathTypewriter",
    }
}

fn math_char_class_value(c: MathCharClass) -> Value {
    Value::Ctor(math_char_class_ctor_name(c).to_string(), None)
}

/// Port of `dev-0-1-0 src/frontend/context.ml:52-68`: bump `ctx`'s
/// `math_script_level` and scale `font_size`
/// accordingly. `Base -> Script`: scale by the font's MATH-table
/// `script_scale_down` (fallback `0.7`, consistent with the engine's other
/// fixed-fraction fallbacks). `Script -> ScriptScript`: scale by
/// `script_script_scale_down / script_scale_down` (fallback `5.0/7.0`).
/// `ScriptScript`: no-op — saturates at the deepest level, matching
/// upstream (no `ScriptScriptScript`).
fn enter_script(interp: &Interp, ctx: &Context) -> Context {
    let mc = MathC::of(interp, ctx);
    let (scale, next_level) = match ctx.math_script_level {
        MathScriptLevel::Base => (
            mc.c.map(|c| c.script_scale_down).unwrap_or(0.7),
            MathScriptLevel::Script,
        ),
        MathScriptLevel::Script => (
            mc.c.map(|c| c.script_script_scale_down / c.script_scale_down)
                .unwrap_or(5.0 / 7.0),
            MathScriptLevel::ScriptScript,
        ),
        MathScriptLevel::ScriptScript => return ctx.clone(),
    };
    Context {
        font_size: ctx.font_size * scale,
        math_script_level: next_level,
        ..ctx.clone()
    }
}

/// Flatten a `Sub`/`Sup` `MathElem`'s (at most two-deep) nesting into `(base,
/// sub_opt, sup_opt)` — `elaborate.rs::fold_math_scripts` always builds a
/// both-scripts element as `Sup(Box::new(Sub(base, sub)), sup)` regardless
/// of source order (`x_a^b` and `x^b_a` both fold this way), so a bare
/// `Sub`/`Sup` and the fused two-level shape are the only cases to handle.
/// `elem` MUST be `MathElem::Sub` or `MathElem::Sup` — every caller already
/// matched on that.
fn flatten_math_scripts(elem: &MathElem) -> (&MathElem, Option<&[MathElem]>, Option<&[MathElem]>) {
    match elem {
        MathElem::Sup(base, sup) => match base.as_ref() {
            MathElem::Sub(inner, sub) => {
                (inner.as_ref(), Some(sub.as_slice()), Some(sup.as_slice()))
            }
            _ => (base.as_ref(), None, Some(sup.as_slice())),
        },
        MathElem::Sub(base, sub) => (base.as_ref(), Some(sub.as_slice()), None),
        _ => unreachable!("flatten_math_scripts called on a non-Sub/Sup MathElem"),
    }
}

/// `attach_scripts` — mirrors upstream's
/// `append_sub_and_super_scripts` + its `enter_script` iteration
/// (`evaluator.cppo.ml:901-904`): reflects `sub_opt`/`sup_opt` (each an
/// already-extracted math-text payload — an ambient-env script slice for
/// the `reflect_scripted_v01` caller, or a genuine runtime `Value::MathText`
/// for the `%math-attach-scripts` primitive caller, both the SAME shape)
/// under `enter_script(interp, ctx)` — so commands *inside* a script observe
/// script-level context — then wraps `Math::Sub`/`Math::Sup` around `base`.
/// Both scripts present wraps as `Sup(Sub(base, sub), sup)`, matching the
/// shape `layout_math_atom`'s `check_subscript` already knows how to merge.
fn attach_scripts(
    interp: &mut Interp,
    ctx: &Context,
    base: Vec<Math>,
    sub_opt: Option<(Rc<Vec<MathElem>>, Env)>,
    sup_opt: Option<(Rc<Vec<MathElem>>, Env)>,
) -> Result<Vec<Math>, EvalError> {
    if sub_opt.is_none() && sup_opt.is_none() {
        return Ok(base);
    }
    let script_ctx = enter_script(interp, ctx);
    let mut cur = base;
    if let Some((elems, senv)) = sub_opt {
        let mut sub_v = Vec::new();
        for e in elems.iter() {
            reflect_math_elem_v01(interp, &script_ctx, e, &senv, &mut sub_v)?;
        }
        cur = vec![Math::Sub(cur, sub_v)];
    }
    if let Some((elems, senv)) = sup_opt {
        let mut sup_v = Vec::new();
        for e in elems.iter() {
            reflect_math_elem_v01(interp, &script_ctx, e, &senv, &mut sup_v)?;
        }
        cur = vec![Math::Sup(cur, sup_v)];
    }
    Ok(cur)
}

/// One base `MathElem` (already stripped of any wrapping `Sub`/`Sup`) plus
/// its (possibly absent) `sub`/`sup` script slices — the shared tail of
/// `reflect_math_elem_v01`'s `Sub`/`Sup` arm (after flattening) AND its bare
/// `Cmd` arm (`sub = sup = None`). `base` a `Cmd`: route ctx+sub+sup into
/// the application per the uniform V0_1 calling convention — a
/// SEPARATE math-command value shape does not exist in this port, so every
/// V0_1 math command, scripted or not, is applied exactly this way. `base`
/// anything else: reflect it plainly, then `attach_scripts`.
fn reflect_scripted_v01(
    interp: &mut Interp,
    ctx: &Context,
    base: &MathElem,
    sub: Option<&[MathElem]>,
    sup: Option<&[MathElem]>,
    env: &Env,
    out: &mut Vec<Math>,
) -> Result<(), EvalError> {
    if let MathElem::Cmd { cmd, args, .. } = base {
        let mut v = cmd.run(env, interp)?;
        for arg in args {
            // `arg.opts` is always empty here too (see the bare-`Cmd` arm
            // above, `reflect_math_elem`) — folded through `apply_with_opts`
            // uniformly regardless.
            let mut opt_vals = Vec::with_capacity(arg.opts.len());
            for (label, e) in &arg.opts {
                opt_vals.push((label.clone(), e.run(env, interp)?));
            }
            let arg_v = arg.arg.run(env, interp)?;
            v = interp.apply_with_opts(v, opt_vals, arg_v)?;
        }
        // A 0.0.6-authored math command reached from a 0.1 document: the two
        // generations invoke a command differently, though `math` relabels
        // to `math-text` and both type-check. 0.0.6 gets `\cmd a1..an ->
        // math` with scripts attached STRUCTURALLY afterward
        // (`reflect_math_elem`'s `Sub`/`Sup` arms); 0.1 applies three extra
        // arguments (`ctx sub sup -> math-boxes`, `sub`/`sup : math-text
        // option`) so a command can typeset its own scripts. Applying those
        // three to a 0.0.6 command used to die with `cannot apply a value of
        // type math as a function`.
        //
        // Discrimination here is DYNAMIC, and total: after its declared
        // arguments a 0.1 command is by construction still a function (ends
        // `.. -> context -> ..`), so a math VALUE at this point can only be
        // a 0.0.6 command's result — a static check can't recover the
        // authoring generation, since `Ast::VersionScope` governs which
        // `PrimDef` the body folds to and nothing on the resulting closure
        // records where it came from. `as_math` runs 0.0.6's own reflection
        // (so nested commands in a returned `${..}` literal stay 0.0.6
        // commands), and its `Rc<Vec<Math>>` payload is byte-for-byte what
        // `Value::MathBoxes` carries, so crossing needs no conversion;
        // untaken scripts then attach via `attach_scripts`, the same
        // structural `Math::Sub`/`Math::Sup` shape 0.0.6's own reflector
        // would have built. A 0.0.6 command still can't RESTYLE its own
        // scripts — it never could, in 0.0.6 either.
        if matches!(v, Value::Math(_) | Value::MathText { .. }) {
            let base_v = as_math(interp, v)?.as_ref().clone();
            let sub_opt = sub.map(|s| (Rc::new(s.to_vec()), env.clone()));
            let sup_opt = sup.map(|s| (Rc::new(s.to_vec()), env.clone()));
            let attached = attach_scripts(interp, ctx, base_v, sub_opt, sup_opt)?;
            out.extend(attached);
            return Ok(());
        }
        v = interp.apply(v, Value::Context(Box::new(ctx.clone())))?;
        v = interp.apply(v, option_math_text_value(sub, env))?;
        v = interp.apply(v, option_math_text_value(sup, env))?;
        let m = as_math_boxes(v)?;
        out.extend(m.iter().cloned());
        return Ok(());
    }
    let mut base_v = Vec::new();
    reflect_math_elem_v01(interp, ctx, base, env, &mut base_v)?;
    let sub_opt = sub.map(|s| (Rc::new(s.to_vec()), env.clone()));
    let sup_opt = sup.map(|s| (Rc::new(s.to_vec()), env.clone()));
    let attached = attach_scripts(interp, ctx, base_v, sub_opt, sup_opt)?;
    out.extend(attached);
    Ok(())
}

/// V0_1 twin of `reflect_math_elem` (differs only where upstream's
/// `read_pdf_mode_math_text` (`evaluator.cppo.ml:887-930`) differs from
/// 0.0.6 reflection): `Chars`/`Group`/`Primes` are
/// identical to the v006 arms (class/variant resolution stays deferred to
/// layout, where `ctx`'s maps live); `Sub`/`Sup` flatten and route through
/// [`reflect_scripted_v01`]; a bare `Cmd` also routes through it (with
/// `sub = sup = None`) so the uniform ctx+sub+sup calling convention
/// applies uniformly, scripted or not; `Embed` (`#x`) requires the embedded
/// value to be `math-text` (it typechecked as `math-text`) and
/// recurses — upstream `MathTextValueGroup` (`evaluator.cppo.ml:944-949`);
/// scripts on an embed attach via [`reflect_scripted_v01`]'s generic
/// (non-`Cmd`) path, same as any other non-command base.
fn reflect_math_elem_v01(
    interp: &mut Interp,
    ctx: &Context,
    elem: &MathElem,
    env: &Env,
    out: &mut Vec<Math>,
) -> Result<(), EvalError> {
    match elem {
        MathElem::Chars(s) => {
            out.push(Math::Pure(MathElement::VariantCharPending(s.clone())));
            Ok(())
        }
        MathElem::Group(elems) => {
            for e in elems {
                reflect_math_elem_v01(interp, ctx, e, env, out)?;
            }
            Ok(())
        }
        MathElem::Primes(base, n) => {
            let mut base_v = Vec::new();
            reflect_math_elem_v01(interp, ctx, base, env, &mut base_v)?;
            let primes: String = std::iter::repeat('\u{2032}').take(*n).collect();
            out.push(Math::Sup(
                base_v,
                vec![Math::Pure(MathElement::Char {
                    class: MathKind::Ord,
                    big: false,
                    chars: primes,
                })],
            ));
            Ok(())
        }
        MathElem::Sub(_, _) | MathElem::Sup(_, _) => {
            let (base, sub, sup) = flatten_math_scripts(elem);
            reflect_scripted_v01(interp, ctx, base, sub, sup, env, out)
        }
        MathElem::Cmd { .. } => reflect_scripted_v01(interp, ctx, elem, None, None, env, out),
        MathElem::Embed { expr, span: _ } => {
            let v = expr.run(env, interp)?;
            let (elems2, env2) = as_math_text(v)?;
            for e in elems2.iter() {
                reflect_math_elem_v01(interp, ctx, e, &env2, out)?;
            }
            Ok(())
        }
    }
}

/// `read-math : context -> math-text -> math-boxes` (dev-0-1-0
/// vminst.ml:790-793). Reflects every element of
/// `mt` under `ctx` via [`reflect_math_elem_v01`], then wraps the whole run
/// in a single `Math::WithContext` node so `ctx` (including any color/font/
/// size override the caller composed onto it) reaches the layout engine —
/// see [`layout_math_list`]'s `Math::WithContext` arm.
fn prim_read_math(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mt = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let (elems, env) = as_math_text(mt)?;
    let mut out = Vec::new();
    for e in elems.iter() {
        reflect_math_elem_v01(interp, &ctx, e, &env, &mut out)?;
    }
    Ok(Value::MathBoxes(Rc::new(vec![Math::WithContext(
        Box::new(ctx),
        out,
    )])))
}

/// `stringify-math : text-info -> math-text -> string` (vminst.ml:858) —
/// STAND-IN: the text-mode backend is out of scope for this PDF port (same
/// scoping note as `prim_convert_string_for_math`'s doc comment); registered
/// so 0.1 packages that reference it still typecheck.
fn prim_stringify_math(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let _mt = args.pop().unwrap();
    let _tctx = args.pop().unwrap();
    eval_error(
        "stringify-math: the text-mode backend is out of scope for this PDF port \
         (see primitives.rs's prim_convert_string_for_math doc comment)"
            .to_string(),
    )
}

/// `set-math-char : int -> int -> math-class -> context -> context`
/// (vminst.ml:59) — REAL: inserts `(char(cp_from)) -> (char(cp_to), kind)`
/// into `Context::math_class_map` (single-char string key, matching the
/// map's existing token-keying convention — see `prim_convert_string_for_
/// math`'s doc comment on how that map is consulted).
fn prim_set_math_char(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let kind = as_math_kind(args.pop().unwrap())?;
    let cpto = as_int(args.pop().unwrap())?;
    let cpfrom = as_int(args.pop().unwrap())?;
    let from = u32::try_from(cpfrom)
        .ok()
        .and_then(char::from_u32)
        .ok_or_else(|| EvalError {
            span: None,
            msg: format!("set-math-char: {cpfrom} is not a valid Unicode codepoint"),
        })?;
    let to = u32::try_from(cpto)
        .ok()
        .and_then(char::from_u32)
        .ok_or_else(|| EvalError {
            span: None,
            msg: format!("set-math-char: {cpto} is not a valid Unicode codepoint"),
        })?;
    Arc::make_mut(&mut ctx.math_class_map).insert(from.to_string(), (to.to_string(), kind));
    Ok(Value::Context(Box::new(ctx)))
}

/// `set-math-char-class : math-char-class -> context -> context`
/// (vminst.ml:445) — REAL: sets `Context::math_char_class`.
fn prim_set_math_char_class(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let cls = as_math_char_class(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        math_char_class: cls,
        ..ctx
    })))
}

/// `get-math-char-class : context -> math-char-class` (vminst.ml:459) —
/// REAL: inverse of `as_math_char_class`.
fn prim_get_math_char_class(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    Ok(math_char_class_value(ctx.math_char_class))
}

/// `embed-inline-to-math : math-class -> inline-boxes -> math-boxes`
/// (vminst.ml:432) — REAL data, stand-in render (`MathElement::
/// EmbeddedBoxes`'s doc comment).
fn prim_embed_inline_to_math(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ib = as_inline_boxes(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    Ok(single_math_boxes(Math::Pure(MathElement::EmbeddedBoxes {
        class,
        boxes: ib,
    })))
}

/// `get-math-axis-height-ratio : context -> float` (vminst.ml:1305) — REAL:
/// the axis-height ratio `MathC` already scales font sizes by
/// (`MathC::axis`).
fn prim_get_math_axis_height_ratio(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let ratio = MathC::of(interp, &ctx)
        .c
        .map(|c| c.axis_height)
        .unwrap_or(0.25);
    Ok(Value::Float(ratio))
}

/// `%math-attach-scripts : context -> math-boxes -> option math-text ->
/// option math-text -> math-boxes` — hidden:
/// the synthesized script-attacher `val math` commands WITHOUT `with sub
/// sup` lower to. Body = [`attach_scripts`] directly — the same function
/// `reflect_scripted_v01`'s non-`Cmd` path calls.
fn prim_math_attach_scripts(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let sup_v = args.pop().unwrap();
    let sub_v = args.pop().unwrap();
    let base_v = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let base = as_math_boxes(base_v)?;
    let sub_opt = as_option_math_text(sub_v)?;
    let sup_opt = as_option_math_text(sup_v)?;
    let out = attach_scripts(interp, &ctx, (*base).clone(), sub_opt, sup_opt)?;
    Ok(Value::MathBoxes(Rc::new(out)))
}

/// `load-hyphenation-dictionary : string -> hyphenation` (`vminst.ml`'s
/// `LoadHyphenationDictionary`: upstream calls `LoadHyph.main abspath` to
/// build a `BCHyphenation` constant). REAL: unlike upstream, which
/// loads a dictionary from an on-disk `.rustyfi-hyph` path, this port has no
/// filesystem-loaded pattern data — the argument is instead treated as a
/// dictionary NAME (`"english"`/`"en-US"`, matching the `hyph-english.satyh`
/// stdlib package's usage) and mapped to the compiled-in `HyphenLang` tag.
/// An unrecognized name is a hard error rather than a silent no-op, since a
/// document that asks for a dictionary and gets none would silently render
/// without hyphenation. The heavy `hyphenation::Standard` dictionary itself
/// is not loaded here — only the lightweight tag is; the actual load is
/// deferred (load-once, cached) to `crate::hyphenation::hyphenate_word`'s
/// first call for that tag.
fn prim_load_hyphenation_dictionary(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let arg = as_str(args.pop().unwrap())?;
    // Accept either a bare dictionary NAME ("english"/"en-US") or an
    // upstream-style PATH ending `.../<name>.rustyfi-hyph` — this is what
    // the real, vendored `hyph-english.satyh` stand-in package actually
    // passes (`here ^ "/../hyph/english.rustyfi-hyph"`, mirroring
    // upstream's `LoadHyph.main abspath` convention). This port has no
    // on-disk pattern-file loader (the dictionary is compiled in via
    // `embed_en-us`), so the path's file stem doubles as the dictionary
    // name.
    let stem = std::path::Path::new(&arg)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(arg.as_str())
        .to_ascii_lowercase();
    let tag = match stem.as_str() {
        "english" | "en-us" => HyphenLang::EnglishUS,
        // en-GB (en-GB option): "british"/"en-GB"/"british-english",
        // mirroring the "english"/ "en-US" naming pair above.
        "british" | "en-gb" | "british-english" => HyphenLang::EnglishGB,
        _ => {
            return eval_error(format!(
                "load-hyphenation-dictionary: unknown dictionary {arg:?} \
                 (supported: \"english\"/\"en-US\", \"british\"/\"en-GB\"/\"british-english\", \
                 bare or as a `.../<name>.rustyfi-hyph`-style path)"
            ))
        }
    };
    Ok(Value::Hyphenation(tag))
}

/// `load-unicode-char-database : string -> string -> string ->
/// unicode-char-database` (`vminst.ml`'s `LoadUnicodeCharDatabase`:
/// upstream builds `(ScriptDataMap, LineBreakDataMap)` from the three
/// Unicode data file paths into a `BCUnidata` constant). STAND-IN: no-op,
/// same rationale as `prim_load_hyphenation_dictionary` above — all three
/// paths are popped and dropped.
fn prim_load_unicode_char_database(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    args.truncate(0);
    Ok(Value::Unit)
}

/// `set-hyphenation-dictionary : hyphenation -> context -> context`
/// (`vminst.ml`'s setter: upstream stores `{ ctx with hyphen_dictionary }`).
/// REAL: writes `Context::hyphen_dictionary = Some(tag)`. This is the
/// ONLY way a `Context` acquires a dictionary — `Context::initial` seeds
/// `None`, so a document that never calls this gets no hyphenation at all.
fn prim_set_hyphenation_dictionary(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let tag = as_hyphenation(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        hyphen_dictionary: Some(tag),
        ..ctx
    })))
}

/// `set-unicode-char-database : unicode-char-database -> context ->
/// context` (`vminst.ml`'s setter: upstream stores `{ ctx with script_map;
/// line_break_map }`). STAND-IN no-op, same shape as
/// `prim_set_hyphenation_dictionary` above.
fn prim_set_unicode_char_database(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = args.pop().unwrap();
    let _db = args.pop().unwrap();
    Ok(ctx)
}

fn prim_math_char_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::Pure(MathElement::Char {
        class,
        big: false,
        chars: s,
    })))
}

/// `math-char : context -> math-class -> string -> math-boxes` (dev-0-1-0
/// vminst.ml:358) — ctx ACCEPTED, not stored on the atom (coarse,
/// `read-math`-granularity context capture only).
fn prim_math_char_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ctx = as_context(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math_boxes(Math::Pure(MathElement::Char {
        class,
        big: false,
        chars: s,
    })))
}

fn prim_math_big_char_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::Pure(MathElement::Char {
        class,
        big: true,
        chars: s,
    })))
}

/// `math-big-char : context -> math-class -> string -> math-boxes`
/// (vminst.ml:374) — same fork as `math-char`.
fn prim_math_big_char_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ctx = as_context(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math_boxes(Math::Pure(MathElement::Char {
        class,
        big: true,
        chars: s,
    })))
}

fn prim_math_char_with_kern_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let kern_r = args.pop().unwrap();
    let kern_l = args.pop().unwrap();
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::Pure(MathElement::CharWithKern {
        class,
        big: false,
        chars: s,
        kern_l: Box::new(kern_l),
        kern_r: Box::new(kern_r),
    })))
}

/// `math-char-with-kern : context -> math-class -> string -> kernf -> kernf
/// -> math-boxes` (vminst.ml:390).
fn prim_math_char_with_kern_v01(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let kern_r = args.pop().unwrap();
    let kern_l = args.pop().unwrap();
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ctx = as_context(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math_boxes(Math::Pure(MathElement::CharWithKern {
        class,
        big: false,
        chars: s,
        kern_l: Box::new(kern_l),
        kern_r: Box::new(kern_r),
    })))
}

fn prim_math_big_char_with_kern_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let kern_r = args.pop().unwrap();
    let kern_l = args.pop().unwrap();
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::Pure(MathElement::CharWithKern {
        class,
        big: true,
        chars: s,
        kern_l: Box::new(kern_l),
        kern_r: Box::new(kern_r),
    })))
}

/// `math-big-char-with-kern : context -> math-class -> string -> kernf ->
/// kernf -> math-boxes` (vminst.ml:411) — same fork as
/// `math-char-with-kern`.
fn prim_math_big_char_with_kern_v01(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let kern_r = args.pop().unwrap();
    let kern_l = args.pop().unwrap();
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ctx = as_context(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math_boxes(Math::Pure(MathElement::CharWithKern {
        class,
        big: true,
        chars: s,
        kern_l: Box::new(kern_l),
        kern_r: Box::new(kern_r),
    })))
}

/// `math-concat : math -> math -> math` (vminst.ml:193) — FAITHFUL: a plain
/// list append (`math` is always a flat sequence of atoms; see `value.rs`'s
/// `Value::Math` doc comment).
fn prim_math_concat_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let m1 = args.pop().unwrap();
    let m1 = as_math(interp, m1)?;
    let m2 = as_math(interp, m2)?;
    let mut out = (*m1).clone();
    out.extend((*m2).iter().cloned());
    Ok(Value::Math(Rc::new(out)))
}

/// `math-concat : math-boxes -> math-boxes -> math-boxes` (vminst.ml:181).
fn prim_math_concat_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = as_math_boxes(args.pop().unwrap())?;
    let m1 = as_math_boxes(args.pop().unwrap())?;
    let mut out = (*m1).clone();
    out.extend((*m2).iter().cloned());
    Ok(Value::MathBoxes(Rc::new(out)))
}

fn prim_math_group_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let cls2 = as_math_kind(args.pop().unwrap())?;
    let cls1 = as_math_kind(args.pop().unwrap())?;
    let inner = as_math(interp, m)?;
    Ok(single_math(Math::Group(cls1, cls2, (*inner).clone())))
}

/// `math-group : math-class -> math-class -> math-boxes -> math-boxes`
/// (vminst.ml:194).
fn prim_math_group_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = as_math_boxes(args.pop().unwrap())?;
    let cls2 = as_math_kind(args.pop().unwrap())?;
    let cls1 = as_math_kind(args.pop().unwrap())?;
    Ok(single_math_boxes(Math::Group(cls1, cls2, (*m).clone())))
}

fn prim_math_sup_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let m1 = args.pop().unwrap();
    let base = as_math(interp, m1)?;
    let script = as_math(interp, m2)?;
    Ok(single_math(Math::Sup((*base).clone(), (*script).clone())))
}

/// `math-sup : context -> math-boxes -> (context -> math-boxes) ->
/// math-boxes` (vminst.ml:208) — the script argument is a context-taking
/// callback, run under `enter_script`.
fn prim_math_sup_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let f = args.pop().unwrap();
    let base_v = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let base = as_math_boxes(base_v)?;
    let script_ctx = enter_script(interp, &ctx);
    let script_v = interp.apply(f, Value::Context(Box::new(script_ctx)))?;
    let script = as_math_boxes(script_v)?;
    Ok(single_math_boxes(Math::Sup(
        (*base).clone(),
        (*script).clone(),
    )))
}

fn prim_math_sub_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let m1 = args.pop().unwrap();
    let base = as_math(interp, m1)?;
    let script = as_math(interp, m2)?;
    Ok(single_math(Math::Sub((*base).clone(), (*script).clone())))
}

/// `math-sub : context -> math-boxes -> (context -> math-boxes) ->
/// math-boxes` (vminst.ml:228) — same shape as `math-sup`.
fn prim_math_sub_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let f = args.pop().unwrap();
    let base_v = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let base = as_math_boxes(base_v)?;
    let script_ctx = enter_script(interp, &ctx);
    let script_v = interp.apply(f, Value::Context(Box::new(script_ctx)))?;
    let script = as_math_boxes(script_v)?;
    Ok(single_math_boxes(Math::Sub(
        (*base).clone(),
        (*script).clone(),
    )))
}

fn prim_math_frac_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let m1 = args.pop().unwrap();
    let num = as_math(interp, m1)?;
    let den = as_math(interp, m2)?;
    Ok(single_math(Math::Fraction((*num).clone(), (*den).clone())))
}

/// `math-frac : context -> math-boxes -> math-boxes -> math-boxes`
/// (vminst.ml:248).
fn prim_math_frac_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = as_math_boxes(args.pop().unwrap())?;
    let m1 = as_math_boxes(args.pop().unwrap())?;
    let _ctx = as_context(args.pop().unwrap())?;
    Ok(single_math_boxes(Math::Fraction(
        (*m1).clone(),
        (*m2).clone(),
    )))
}

/// `math-radical : math option -> math -> math` (vminst.ml:274) — `None`
/// degree is `\sqrt`; upstream's `MathRadicalWithDegree` (`\sqrt[n]`) is
/// unimplemented too (`math.ml:886`), carried faithfully but not rendered
/// specially, matching upstream by parity (see `value.rs`'s `Math::Radical`).
fn prim_math_radical_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let opt = args.pop().unwrap();
    let radicand = as_math(interp, m2)?;
    let degree = match opt {
        Value::Ctor(name, payload) if name == "None" && payload.is_none() => None,
        Value::Ctor(name, Some(payload)) if name == "Some" => {
            Some((*as_math(interp, *payload)?).clone())
        }
        other => {
            return eval_error(format!(
                "expected a math option (None/Some), got {}",
                other.type_name()
            ))
        }
    };
    Ok(single_math(Math::Radical(degree, (*radicand).clone())))
}

/// `math-radical : context -> option math-boxes -> math-boxes ->
/// math-boxes` (vminst.ml:262).
fn prim_math_radical_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let opt = args.pop().unwrap();
    let _ctx = as_context(args.pop().unwrap())?;
    let radicand = as_math_boxes(m2)?;
    let degree = match opt {
        Value::Ctor(name, payload) if name == "None" && payload.is_none() => None,
        Value::Ctor(name, Some(payload)) if name == "Some" => {
            Some((*as_math_boxes(*payload)?).clone())
        }
        other => {
            return eval_error(format!(
                "expected a math-boxes option (None/Some), got {}",
                other.type_name()
            ))
        }
    };
    Ok(single_math_boxes(Math::Radical(
        degree,
        (*radicand).clone(),
    )))
}

fn prim_math_lower_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let m1 = args.pop().unwrap();
    let base = as_math(interp, m1)?;
    let lower = as_math(interp, m2)?;
    Ok(single_math(Math::LowerLimit(
        (*base).clone(),
        (*lower).clone(),
    )))
}

/// `math-lower : context -> math-boxes -> (context -> math-boxes) ->
/// math-boxes` (vminst.ml:338) — same script-callback shape as `math-sup`.
fn prim_math_lower_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let f = args.pop().unwrap();
    let base_v = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let base = as_math_boxes(base_v)?;
    let script_ctx = enter_script(interp, &ctx);
    let script_v = interp.apply(f, Value::Context(Box::new(script_ctx)))?;
    let lower = as_math_boxes(script_v)?;
    Ok(single_math_boxes(Math::LowerLimit(
        (*base).clone(),
        (*lower).clone(),
    )))
}

fn prim_math_upper_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m2 = args.pop().unwrap();
    let m1 = args.pop().unwrap();
    let base = as_math(interp, m1)?;
    let upper = as_math(interp, m2)?;
    Ok(single_math(Math::UpperLimit(
        (*base).clone(),
        (*upper).clone(),
    )))
}

/// `math-upper : context -> math-boxes -> (context -> math-boxes) ->
/// math-boxes` (vminst.ml:318) — same script-callback shape as `math-sup`.
fn prim_math_upper_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let f = args.pop().unwrap();
    let base_v = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let base = as_math_boxes(base_v)?;
    let script_ctx = enter_script(interp, &ctx);
    let script_v = interp.apply(f, Value::Context(Box::new(script_ctx)))?;
    let upper = as_math_boxes(script_v)?;
    Ok(single_math_boxes(Math::UpperLimit(
        (*base).clone(),
        (*upper).clone(),
    )))
}

/// `math-pull-in-scripts : math-class -> math-class -> (math option -> math
/// option -> math) -> math` (vminst.ml:368) — FAITHFUL construction: the
/// resolver closure is stored opaquely here, only ever invoked by
/// `layout_pull_in_scripts` — with
/// the subscript/superscript actually pulled in off an enclosing `Sub`/`Sup`
/// (`{scripts} m^{sup}`-style), or with `(None, None)` for the common
/// unscripted case (a bare `\sum`/`\int` with nothing pulled in).
fn prim_math_pull_in_scripts(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let resolver = args.pop().unwrap();
    let cls2 = as_math_kind(args.pop().unwrap())?;
    let cls1 = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::PullInScripts(
        cls1,
        cls2,
        Box::new(resolver),
    )))
}

fn prim_math_color(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let color = as_color(args.pop().unwrap())?;
    let inner = as_math(interp, m)?;
    Ok(single_math(Math::ChangeColor(color, (*inner).clone())))
}

fn prim_math_char_class(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let cls = as_math_char_class(args.pop().unwrap())?;
    let inner = as_math(interp, m)?;
    Ok(single_math(Math::ChangeCharClass(cls, (*inner).clone())))
}

fn prim_math_variant_char(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let style = as_math_variant_style(args.pop().unwrap())?;
    let class = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::Pure(MathElement::VariantChar {
        class,
        big: false,
        style: Box::new(style),
    })))
}

fn prim_math_paren_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let paren_r = args.pop().unwrap();
    let paren_l = args.pop().unwrap();
    let inner = as_math(interp, m)?;
    Ok(single_math(Math::Paren(
        Box::new(paren_l),
        Box::new(paren_r),
        (*inner).clone(),
    )))
}

/// `math-paren : context -> paren -> paren -> math-boxes -> math-boxes`
/// (vminst.ml:279).
fn prim_math_paren_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let paren_r = args.pop().unwrap();
    let paren_l = args.pop().unwrap();
    let _ctx = as_context(args.pop().unwrap())?;
    let inner = as_math_boxes(m)?;
    Ok(single_math_boxes(Math::Paren(
        Box::new(paren_l),
        Box::new(paren_r),
        (*inner).clone(),
    )))
}

fn prim_math_paren_with_middle_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let mlst = args.pop().unwrap();
    let middle = args.pop().unwrap();
    let paren_r = args.pop().unwrap();
    let paren_l = args.pop().unwrap();
    let items = as_list(mlst)?;
    let mut mlstlst = Vec::with_capacity(items.len());
    for it in items {
        mlstlst.push((*as_math(interp, it)?).clone());
    }
    Ok(single_math(Math::ParenWithMiddle(
        Box::new(paren_l),
        Box::new(paren_r),
        Box::new(middle),
        mlstlst,
    )))
}

/// `math-paren-with-middle : context -> paren -> paren -> paren -> list
/// math-boxes -> math-boxes` (vminst.ml:297).
fn prim_math_paren_with_middle_v01(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let mlst = args.pop().unwrap();
    let middle = args.pop().unwrap();
    let paren_r = args.pop().unwrap();
    let paren_l = args.pop().unwrap();
    let _ctx = as_context(args.pop().unwrap())?;
    let items = as_list(mlst)?;
    let mut mlstlst = Vec::with_capacity(items.len());
    for it in items {
        mlstlst.push((*as_math_boxes(it)?).clone());
    }
    Ok(single_math_boxes(Math::ParenWithMiddle(
        Box::new(paren_l),
        Box::new(paren_r),
        Box::new(middle),
        mlstlst,
    )))
}

fn prim_text_in_math(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let body = args.pop().unwrap();
    let class = as_math_kind(args.pop().unwrap())?;
    let _ = interp;
    Ok(single_math(Math::Pure(MathElement::EmbeddedText {
        class,
        body: Box::new(body),
    })))
}

/// `convert-string-for-math : context -> math-char-class -> string ->
/// string` (`vminstdef.yaml` `PrimitiveConvertStringForMath`). Faithful to
/// upstream: it overrides the context's `math_char_class` with the passed
/// `mccls`, then runs `MathContext.convert_math_variant_char`
/// (`types.cppo.ml:1602`) over the whole string —
///  1. if the WHOLE string is a key of the (token-level) `math_class_map`
///     (`default_math_class_map`, e.g. `"-"` → `"−"` U+2212), return its
///     replacement codepoints; else
///  2. remap each char via the runtime `math_variant_char_map`
///     (`set-math-variant-char` overrides, keyed by `(char, mccls)`) first,
///     then the built-in `default_math_variant_char` table (the
///     Mathematical-Alphanumeric-Symbols remap), keeping any char with no
///     mapping.
/// Unlike the *rendering*-path `resolve_variant_char`, this string primitive
/// does NOT gate on font glyph availability (upstream's
/// `convert_math_variant_char` never does — it returns codepoints, not
/// glyphs), so `abc` under `MathItalic` yields U+1D44E/44F/450 regardless of
/// the active font.
fn prim_convert_string_for_math(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let class = as_math_char_class(args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    // (1) whole-token class-map hit -> its replacement codepoints verbatim.
    if let Some((target, _mk)) = ctx.math_class_map.get(&s) {
        return Ok(Value::Str(target.clone()));
    }
    // (2) per-char variant remap under the PASSED class (which upstream
    // installs as the effective `math_char_class` before converting).
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        let mapped = ctx
            .math_variant_char_map
            .get(&(ch, class))
            .copied()
            .or_else(|| default_math_variant_char(class, ch))
            .unwrap_or(ch);
        out.push(mapped);
    }
    Ok(Value::Str(out))
}

/// `set-math-variant-char : math-char-class -> int -> int -> context ->
/// context` — FAITHFUL: installs a per-`(source char, style)`
/// override into `Context::math_variant_char_map`, consulted by
/// `resolve_variant_char` BEFORE the built-in `default_math_variant_char`
/// table. `Arc::make_mut` copy-on-writes the map so contexts that never
/// call this keep sharing one `Arc`-refcounted empty table.
fn prim_set_math_variant_char_v006(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let cpto = as_int(args.pop().unwrap())?;
    let cpfrom = as_int(args.pop().unwrap())?;
    let cls = as_math_char_class(args.pop().unwrap())?;
    let from = u32::try_from(cpfrom)
        .ok()
        .and_then(char::from_u32)
        .ok_or_else(|| EvalError {
            span: None,
            msg: format!("set-math-variant-char: {cpfrom} is not a valid Unicode codepoint"),
        })?;
    let to = u32::try_from(cpto)
        .ok()
        .and_then(char::from_u32)
        .ok_or_else(|| EvalError {
            span: None,
            msg: format!("set-math-variant-char: {cpto} is not a valid Unicode codepoint"),
        })?;
    Arc::make_mut(&mut ctx.math_variant_char_map).insert((from, cls), to);
    Ok(Value::Context(Box::new(ctx)))
}

/// `set-math-variant-char : int -> (math-char-class -> int) -> context ->
/// context` (vminst.ml:36) — the v01 body applies the selector once per
/// each of the 9 `MathCharClass` values and inserts into `math_variant_
/// char_map` (an eager materialization of upstream's stored selector
/// closure; the observable map is the same either way).
fn prim_set_math_variant_char_v01(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let selector = args.pop().unwrap();
    let cpfrom = as_int(args.pop().unwrap())?;
    let from = u32::try_from(cpfrom)
        .ok()
        .and_then(char::from_u32)
        .ok_or_else(|| EvalError {
            span: None,
            msg: format!("set-math-variant-char: {cpfrom} is not a valid Unicode codepoint"),
        })?;
    const CLASSES: [MathCharClass; 9] = [
        MathCharClass::Italic,
        MathCharClass::BoldItalic,
        MathCharClass::Roman,
        MathCharClass::BoldRoman,
        MathCharClass::Script,
        MathCharClass::BoldScript,
        MathCharClass::Fraktur,
        MathCharClass::BoldFraktur,
        MathCharClass::DoubleStruck,
    ];
    for cls in CLASSES {
        let cpto_v = interp.apply(selector.clone(), math_char_class_value(cls))?;
        let cpto = as_int(cpto_v)?;
        let to = u32::try_from(cpto)
            .ok()
            .and_then(char::from_u32)
            .ok_or_else(|| EvalError {
                span: None,
                msg: format!("set-math-variant-char: {cpto} is not a valid Unicode codepoint"),
            })?;
        Arc::make_mut(&mut ctx.math_variant_char_map).insert((from, cls), to);
    }
    Ok(Value::Context(Box::new(ctx)))
}

/// The `MathKind` one `MathElement` atom presents as its own boundary class
/// — `Char`/`CharWithKern`/`EmbeddedText`/`VariantChar` carry an explicit
/// `class` field; `VariantCharPending` (not yet resolved to a class
/// at this point in the tree) consults `ctx.math_class_map` the same way
/// `layout_math_atom`'s own arm does, defaulting to `Ord` when the token
/// isn't a whole-token class-map entry (mirrors `layout_math_atom`'s
/// fallback path, whose per-char variant remap never changes the class).
fn math_element_kind(ctx: &Context, me: &MathElement) -> MathKind {
    match me {
        MathElement::Char { class, .. }
        | MathElement::CharWithKern { class, .. }
        | MathElement::EmbeddedText { class, .. }
        | MathElement::VariantChar { class, .. }
        | MathElement::EmbeddedBoxes { class, .. } => *class,
        MathElement::VariantCharPending(s) => ctx
            .math_class_map
            .get(s.as_str())
            .map(|(_, kind)| *kind)
            .unwrap_or(MathKind::Ord),
    }
}

/// Upstream `get_left_math_kind`/`get_right_math_kind` (math.ml:481-524),
/// fused into one direction-parameterized walk over a `&[Math]` list's
/// FIRST (`left = true`) or LAST (`left = false`) element: `Pure` atoms
/// report their own class (`math_element_kind`); `Group`/`PullInScripts`
/// present an explicit, possibly-asymmetric left/right pair; `Sup`/`Sub`/
/// `UpperLimit`/`LowerLimit` recurse into their `base`; `Fraction`/
/// `Radical` are always `Inner`; `Paren`/`ParenWithMiddle` are always
/// `Open`/`Close`; `ChangeColor`/`ChangeCharClass` recurse into `inner`; an
/// empty list is the synthetic `End` boundary sentinel (`MathKind::End`,
/// `horzBox.ml:134`) — `make_math_class_option_value` maps that to `None`,
/// same as upstream's own list-boundary handling.
fn boundary_math_kind(ctx: &Context, ms: &[Math], left: bool) -> MathKind {
    let m = if left { ms.first() } else { ms.last() };
    let Some(m) = m else {
        return MathKind::End;
    };
    match m {
        Math::Pure(me) => math_element_kind(ctx, me),
        Math::Group(cls1, cls2, _) => {
            if left {
                *cls1
            } else {
                *cls2
            }
        }
        Math::PullInScripts(cls1, cls2, _) => {
            if left {
                *cls1
            } else {
                *cls2
            }
        }
        Math::Sup(base, _)
        | Math::Sub(base, _)
        | Math::UpperLimit(base, _)
        | Math::LowerLimit(base, _) => boundary_math_kind(ctx, base, left),
        Math::Fraction(..) | Math::Radical(..) => MathKind::Inner,
        Math::Paren(..) | Math::ParenWithMiddle(..) => {
            if left {
                MathKind::Open
            } else {
                MathKind::Close
            }
        }
        Math::ChangeColor(_, inner) | Math::ChangeCharClass(_, inner) => {
            boundary_math_kind(ctx, inner, left)
        }
        // V0_1 only (`read-math`): the boundary class is a property of the
        // wrapped content, not of which context laid it out under, so
        // recurse into `inner` with the SAME probing `ctx` (mirrors the
        // `ChangeColor`/`ChangeCharClass` arms above, which also recurse
        // with the ambient `ctx` rather than switching to their own stored
        // state).
        Math::WithContext(_, inner) => boundary_math_kind(ctx, inner, left),
    }
}

fn left_math_kind(ctx: &Context, ms: &[Math]) -> MathKind {
    boundary_math_kind(ctx, ms, true)
}

fn right_math_kind(ctx: &Context, ms: &[Math]) -> MathKind {
    boundary_math_kind(ctx, ms, false)
}

/// `math-class option` — `MathKind::End` (the empty-list sentinel) becomes
/// `None`; every real class becomes `Some(<ctor>)`, round-tripping exactly
/// with `as_math_kind`'s ctor names.
fn make_math_class_option_value(mk: MathKind) -> Value {
    let name = match mk {
        MathKind::Ord => "MathOrd",
        MathKind::Bin => "MathBin",
        MathKind::Rel => "MathRel",
        MathKind::Op => "MathOp",
        MathKind::Punct => "MathPunct",
        MathKind::Open => "MathOpen",
        MathKind::Close => "MathClose",
        MathKind::Prefix => "MathPrefix",
        MathKind::Inner => "MathInner",
        MathKind::End => return Value::Ctor("None".to_string(), None),
    };
    Value::Ctor(
        "Some".to_string(),
        Some(Box::new(Value::Ctor(name.to_string(), None))),
    )
}

/// `get-left-math-class : context -> math -> math-class option`.
fn prim_get_left_math_class_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let m = as_math(interp, args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    Ok(make_math_class_option_value(left_math_kind(&ctx, &m)))
}

/// `get-left-math-class : math-boxes -> math-class option` (vminst.ml:128)
/// — ctx DROPPED (matches upstream, which takes no context at all here).
/// The boundary-class probe still needs SOME `Context` to resolve an
/// unresolved `VariantCharPending` token's whole-token class map
/// (`math_element_kind`) — this port's own deferred-resolution design, not
/// upstream's, since upstream's `math` atoms already carry a resolved
/// class — so a bare default context stands in.
fn prim_get_left_math_class_v01(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let m = as_math_boxes(args.pop().unwrap())?;
    let ctx = Context::initial(Length::ZERO);
    Ok(make_math_class_option_value(left_math_kind(&ctx, &m)))
}

/// `get-right-math-class : context -> math -> math-class option`.
fn prim_get_right_math_class_v006(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let m = as_math(interp, args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    Ok(make_math_class_option_value(right_math_kind(&ctx, &m)))
}

/// `get-right-math-class : math-boxes -> math-class option` (vminst.ml:146)
/// — same fork as `get-left-math-class`.
fn prim_get_right_math_class_v01(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let m = as_math_boxes(args.pop().unwrap())?;
    let ctx = Context::initial(Length::ZERO);
    Ok(make_math_class_option_value(right_math_kind(&ctx, &m)))
}

/// `set-math-command : [math] inline-cmd -> context -> context`
/// FAITHFUL: installs the command `read_inline`'s `EmbedMath` arm applies
/// to bare `${…}`.
fn prim_set_math_command(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let cmd = args.pop().unwrap();
    ctx.math_command = Some(interp.register_math_command(cmd));
    Ok(Value::Context(Box::new(ctx)))
}

/// Resolve a font abbrev to one of the 3 base faces by name heuristic — the
/// only font-name resolution this port has. Shared by set-font/set-math-font.
fn resolve_font_abbrev(abbrev: &str) -> FontKey {
    let lower = abbrev.to_ascii_lowercase();
    if lower.contains("bold") {
        FONT_BOLD
    } else if lower.contains("it") || lower.contains("obl") || lower.contains("slant") {
        FONT_OBLIQUE
    } else {
        FONT_REGULAR
    }
}

/// `set-math-font : string -> context -> context` (0.0.6
/// `vminstdef.yaml:1364`) — `abbrev` resolves through the font metrics
/// provider's registry first (the same upgrade as `set-font`), falling back
/// to the 3-face name heuristic, so a math OTF configured under
/// any abbrev (not just the CLI regular face) can be selected.
fn prim_set_math_font_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let abbrev = as_str(args.pop().unwrap())?;
    let math_font = interp
        .metrics
        .resolve_font_abbrev(&abbrev)
        .unwrap_or_else(|| resolve_font_abbrev(&abbrev));
    Ok(Value::Context(Box::new(Context { math_font, ..ctx })))
}

/// `set-math-font : font -> context -> context` (saphe-split
/// `tools/gencode/vminst.ml:1462`, whose body is
/// `ctx with math_font_key = Some(mathkey)`) — the 0.1 arm takes the opaque
/// handle, so there is no abbrev left to resolve. The bundled 0.1 corpus
/// already calls it that way (`std-ja.satyh`'s `set-math-font
/// FontLatinModernMath.main`).
fn prim_set_math_font_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let math_font = as_font_key(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context { math_font, ..ctx })))
}

/// `load-single-font : string -> font` — LOCAL, non-upstream, V0_1-only.
///
/// Upstream has no surface name for this: `envelopeChecker.ml`'s
/// `check_font_envelope` synthesizes one binding per `files[]` row of a font
/// ENVELOPE, typed `BaseType(FontType)`, whose right-hand side is the
/// internal `LoadSingleFont{ path; used_as_math_font }` node — and
/// `evaluator.cppo.ml:427-434` evaluates that to `BaseConstant(BCFontKey
/// (FontInfo.add_single path))`. This port's bundled 0.1 font envelopes are
/// ordinary `.satyh` stand-ins (`dist-v01/packages/font-*.satyh`) rather
/// than envelopes the loader synthesizes bindings from, so they need a
/// spelling for the same step; this is it. Same LOCAL-primitive precedent as
/// `set-font-key`.
///
/// The argument stands in for upstream's font-file PATH: it is the port's
/// font-store key, resolved here through exactly the ladder `set-font` used
/// to run per call — the metrics provider's registry
/// (`FontMetrics::resolve_font_abbrev`, a real `TtfFontStore` built from
/// `fonts.satysfi-hash`), falling back to the 3-face name heuristic. Doing
/// it HERE rather than at `set-font` time is what makes the resulting `font`
/// a genuine handle: resolution is a pure function of the abbrev and the
/// provider (`&self`, no interior mutation), so moving it earlier is
/// observationally identical.
fn prim_load_single_font(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let abbrev = as_str(args.pop().unwrap())?;
    let key = interp
        .metrics
        .resolve_font_abbrev(&abbrev)
        .unwrap_or_else(|| resolve_font_abbrev(&abbrev));
    Ok(Value::Font(key))
}

/// `space-between-maths : context -> math -> math -> inline-boxes option`
/// (vminst.ml:173) — STAND-IN: the real inter-atom glue is the full
/// `space_between_math_kinds` table (`math.ml:319-410`); always returns
/// `None` (no extra glue), used by `math.satyh`'s
/// `+align` — never invoked eagerly (that binding is a `let-block` closure).
fn prim_space_between_maths_v006(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let _m2 = args.pop().unwrap();
    let _m1 = args.pop().unwrap();
    let _ctx = as_context(args.pop().unwrap())?;
    Ok(Value::Ctor("None".to_string(), None))
}

/// `space-between-maths : context -> math-boxes -> math-boxes -> inline-
/// boxes option` (vminst.ml:164) — shared STAND-IN body, only the extractor
/// forks (`as_math_boxes` vs `as_math`).
fn prim_space_between_maths_v01(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let _m2 = as_math_boxes(args.pop().unwrap())?;
    let _m1 = as_math_boxes(args.pop().unwrap())?;
    let _ctx = as_context(args.pop().unwrap())?;
    Ok(Value::Ctor("None".to_string(), None))
}

/// `raise-inline : length -> inline-boxes -> inline-boxes` — STAND-IN: the
/// line model has no per-box vertical-offset wrapper outside
/// `PureHorzBox::Math`'s own per-glyph `dy` ("structural difference"
/// note); returns the boxes unshifted (used by `math.satyh`'s `\cases`,
/// never invoked eagerly).
fn prim_raise_inline(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ib = as_inline_boxes(args.pop().unwrap())?;
    let _len = as_length(args.pop().unwrap())?;
    Ok(Value::InlineBoxes(ib))
}

/// `embed-block-breakable : context -> block-boxes -> inline-boxes`
/// (vminst.ml:973; upstream `HorzEmbeddedVertBreakable`) — a MANDATORY
/// break on both sides: upstream's `LBEmbeddedVertBreakable` resets the
/// width map to this breakpoint alone (`lineBreak.ml:1076-1087`), flushes
/// the accumulated line, emits the block as its own vertical item, then
/// starts a fresh line (`lineBreak.ml:809-818`).
///
/// Modelled here as a forced `Discretionary` either side of the block —
/// without them the block was just an inline box, so latexcmds'
/// `\linebreak` (`inline-fil ++ embed-block-breakable ctx (block-skip
/// gap)`, `latexcmds.satyh:150`) never broke: the `inline-fil` swallowed
/// the line's whole slack and shoved everything after it off the page
/// edge, silently losing it (`このように`/`使い`/`すぎると`/`読みにくく`
/// all vanished from the render).
fn prim_embed_block_breakable(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    // Embed the block inline, top-anchored (the block's FIRST line sits on the
    // surrounding text baseline — same as `embed-block-top`).
    // `make_embedded_block` splits the box's height/depth around the first line
    // so the pager accounts for the embedded figure's extent.
    let block = match make_embedded_block(ctx.paragraph_width, bb, false, true) {
        Value::InlineBoxes(boxes) => boxes,
        other => return Ok(other),
    };
    let forced = || {
        HorzBox::Pure(PureHorzBox::Discretionary {
            penalty: FORCED_BREAK_PENALTY,
            pre_break: Vec::new(),
            post_break: Vec::new(),
            no_break: Vec::new(),
        })
    };
    let mut out = vec![forced()];
    out.extend(block);
    out.push(forced());
    Ok(Value::InlineBoxes(out))
}

/// `unite-path : path -> path -> path` — FAITHFUL: `path` is upstream's
/// `path list` (a list of independently-closed subpaths — see
/// `graphics.rs`'s `Path` doc comment), so uniting two is a plain
/// subpath-list append. Used by `math.satyh`'s `\norm` (two parallel bars).
fn prim_unite_path(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let p2 = as_path(args.pop().unwrap())?;
    let p1 = as_path(args.pop().unwrap())?;
    let mut subpaths = p1.subpaths;
    subpaths.extend(p2.subpaths);
    Ok(Value::Path(Path { subpaths }))
}

/// `set-min-gap-of-lines : length -> context -> context` (vminst.ml:1291) —
/// STAND-IN: no separate `min_gap_of_lines` field on `Context` yet (see
/// `set-leading`'s own comment on why IT, not this, is the baseline-distance
/// setter); accepted and dropped. Used by `math.satyh`'s `+math-list`, never
/// invoked eagerly.
fn prim_set_min_gap_of_lines(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let _len = as_length(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(ctx)))
}

/// `embed-math : context -> math -> inline-boxes` (vminst.ml:520) — the
/// bridge to the page: the faithful, primitive-driven analog of `read_math`,
/// operating on a `Value::Math` tree instead. FAITHFUL for the atoms
/// `read_math` already draws (plain/kerned/variant chars, groups, sup/sub);
/// the structural forms (fraction/radical/paren/limits/pull-in-scripts/
/// embedded-text) get a deliberately cheap, documented stand-in rendering
/// rather than an error, so `${…}`-shaped math built through these
/// primitives is never *unusable*, just not yet typographically faithful.
fn prim_embed_math_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let elems = as_math(interp, m)?;
    let boxed = layout_math_value(interp, &ctx, &elems)?;
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(boxed)]))
}

/// `embed-math : context -> math-boxes -> inline-boxes` (vminst.ml:472) —
/// `as_math_boxes` then the SAME `layout_math_value` (:5165 below) — the
/// whole MATH-engine reuse in one primitive.
fn prim_embed_math_v01(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let m = args.pop().unwrap();
    let ctx = as_context(args.pop().unwrap())?;
    let elems = as_math_boxes(m)?;
    let boxed = layout_math_value(interp, &ctx, &elems)?;
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(boxed)]))
}

/// Lay out a faithful `&[Math]` run into one `PureHorzBox::Math`, mirroring
/// `read_math`'s glyph-emission shape (fixed-constant super/subscript
/// shift/scale, the same minimal `Bin`/`Rel` spacer) but keyed on each
/// atom's own EXPLICIT class (from `math-char`/`math-group`/…) rather than
/// `ascii_math_kind`'s inference.
fn layout_math_value(
    interp: &mut Interp,
    ctx: &Context,
    elems: &[Math],
) -> Result<PureHorzBox, EvalError> {
    let (glyphs, rules, width, _left, _right) =
        layout_math_list(interp, ctx, elems, ctx.font_size)?;
    let mut height = Length::ZERO;
    let mut depth = Length::ZERO;
    for g in &glyphs {
        height = height.max(g.dy + g.height);
        depth = depth.max(g.depth - g.dy);
    }
    // A fraction bar/radical sign is a `Fill` with no `MathGlyph` backing it
    // at all, so the glyph-only aggregation above would silently undercount
    // a run whose bar/sign extends above every glyph's own ink (e.g.
    // `${\sqrt{2}}`'s `l_extra` ascender). Fold every rule's own (y-up,
    // box-local — same frame as `MathGlyph::dy`) bounding box in too.
    for r in &rules {
        // `graphics_bbox` -> `Option`; a `None` rule (unreachable here
        // under 0.0.6 math rules) contributes nothing.
        if let Some(((_, min_y), (_, max_y))) = graphics_bbox(r) {
            height = height.max(max_y);
            depth = depth.max(-min_y);
        }
    }
    Ok(PureHorzBox::Math {
        width,
        height,
        depth,
        glyphs,
        rules,
    })
}

/// Lay out a flat `&[Math]` list at `size`, threading inter-atom spacing
/// (`space_before`, a minimal spacer) and returning the glyphs (at
/// LOCAL coordinates starting at `x = 0`), any graphics `rules` an atom
/// pushed (shifted horizontally by the same running `x` a glyph gets
/// — `layout_math_list` never shifts an atom vertically, only
/// `shift_and_append`'s callers do), the total width, and the boundary
/// classes on either end (needed by a `Group` ancestor, which can present
/// different left/right classes — see `Math::Group`'s doc comment).
fn layout_math_list(
    interp: &mut Interp,
    ctx: &Context,
    elems: &[Math],
    size: Length,
) -> Result<
    (
        Vec<MathGlyph>,
        Vec<GraphicsElem>,
        Length,
        MathKind,
        MathKind,
    ),
    EvalError,
> {
    // Lay every atom out FIRST, because `normalize_math_kind` below needs each
    // one's NEIGHBOURS' raw classes — upstream's `convert_to_low` passes
    // `mkprev`/`mknext` into `convert_to_low_single` for exactly this
    // (`math.ml:753-765`, via `get_right_math_kind`/`get_left_math_kind`).
    // The layout of an atom does not depend on its class, only the SPACING
    // between atoms does, so splitting the walk in two moves no glyph.
    let mut laid: Vec<(
        Vec<MathGlyph>,
        Vec<GraphicsElem>,
        Length,
        MathKind,
        MathKind,
    )> = Vec::with_capacity(elems.len());
    for atom in elems {
        laid.push(layout_math_atom(interp, ctx, atom, size)?);
    }

    let mut glyphs = Vec::new();
    let mut rules = Vec::new();
    let mut x = Length::ZERO;
    let mut last_kind: Option<MathKind> = None;
    let mut first_kind: Option<MathKind> = None;
    let in_script = math_in_script(ctx, size);
    for (i, (atom_glyphs, atom_rules, atom_width, left_raw, right_raw)) in
        laid.iter().cloned().enumerate()
    {
        // `mkprev`/`mknext` are the neighbours' RAW classes (upstream never
        // feeds a normalized class back in), and the ends of the list are
        // `MathEnd` — `math.ml:1270`'s `convert_to_low mathctx MathEnd MathEnd`.
        let prev_raw = if i == 0 { MathKind::End } else { laid[i - 1].4 };
        let next_raw = laid.get(i + 1).map_or(MathKind::End, |a| a.3);
        let left = normalize_math_kind(prev_raw, next_raw, left_raw);
        let right = normalize_math_kind(prev_raw, next_raw, right_raw);
        if let Some(prev) = last_kind {
            x += space_before(prev, left, in_script, size);
        }
        first_kind.get_or_insert(left);
        let base_x = x;
        for mut g in atom_glyphs {
            g.dx = base_x + g.dx;
            glyphs.push(g);
        }
        for r in &atom_rules {
            rules.push(shift_graphics((base_x, Length::ZERO), r));
        }
        x = base_x + atom_width;
        last_kind = Some(right);
    }
    let left = first_kind.unwrap_or(MathKind::Ord);
    let right = last_kind.unwrap_or(MathKind::Ord);
    Ok((glyphs, rules, x, left, right))
}

/// Upstream `check_subscript` (math.ml:682-699): if a superscript base's
/// LAST element is itself a `Sub`, strip it — returning `(subscript script,
/// new base)` where the new base is the preceding elements followed by the
/// inner `Sub`'s own base, so `{x_1}^2` becomes one base carrying both a
/// sub and a sup. Recurses through `ChangeColor`/`ChangeCharClass`.
fn check_subscript(base: &[Math]) -> Option<(Vec<Math>, Vec<Math>)> {
    let (last, head) = base.split_last()?;
    match last {
        Math::Sub(inner_base, sub_script) => {
            let mut new_base = head.to_vec();
            new_base.extend(inner_base.iter().cloned());
            Some((sub_script.clone(), new_base))
        }
        Math::ChangeColor(color, inner) => {
            let (sub_script, inner_new) = check_subscript(inner)?;
            let mut new_base = head.to_vec();
            new_base.push(Math::ChangeColor(color.clone(), inner_new));
            Some((vec![Math::ChangeColor(color.clone(), sub_script)], new_base))
        }
        Math::ChangeCharClass(cls, inner) => {
            let (sub_script, inner_new) = check_subscript(inner)?;
            let mut new_base = head.to_vec();
            new_base.push(Math::ChangeCharClass(cls.clone(), inner_new));
            Some((
                vec![Math::ChangeCharClass(cls.clone(), sub_script)],
                new_base,
            ))
        }
        _ => None,
    }
}

/// Upstream `invoke_pull_in_scripts` (math.ml:957-966): call a
/// `math-pull-in-scripts` resolver with the actual pulled-in scripts —
/// `resolver : math option -> math option -> math`, SUBSCRIPT option first,
/// SUPERSCRIPT second — then splice the returned math after the remaining
/// base as ONE `Group(cls1, cls2, …)` atom and lay the whole list out.
#[allow(clippy::too_many_arguments)]
fn layout_pull_in_scripts(
    interp: &mut Interp,
    ctx: &Context,
    head: &[Math],
    cls1: MathKind,
    cls2: MathKind,
    resolver: &Value,
    sub: Option<&[Math]>,
    sup: Option<&[Math]>,
    size: Length,
) -> Result<
    (
        Vec<MathGlyph>,
        Vec<GraphicsElem>,
        Length,
        MathKind,
        MathKind,
    ),
    EvalError,
> {
    let opt_math = |o: Option<&[Math]>| match o {
        Some(m) => Value::Ctor(
            "Some".to_string(),
            Some(Box::new(Value::Math(Rc::new(m.to_vec())))),
        ),
        None => Value::Ctor("None".to_string(), None),
    };
    let partial = interp.apply(resolver.clone(), opt_math(sub))?;
    let result = interp.apply(partial, opt_math(sup))?;
    let resolved = as_math(interp, result)?;
    let mut items: Vec<Math> = head.to_vec();
    items.push(Math::Group(cls1, cls2, (*resolved).clone()));
    layout_math_list(interp, ctx, &items, size)
}

/// The metrics-probe fallback policy: resolve `c` under `ctx`'s current
/// `math_char_class` (checking the runtime override map first, then the
/// built-in `default_math_variant_char` table), but only actually EMIT the
/// remapped codepoint if the current font can render it
/// (`interp.metrics.advance` returns `Some`) — otherwise fall back to the
/// source char `c` (its class, from `Context::math_class_map`/
/// `ascii_math_kind`-style inference, is kept regardless). This is what
/// keeps base-14/WinAnsi documents byte-identical (`Base14Metrics` returns
/// `None` outside ASCII 32-126) while a math-capable TTF, or a permissive
/// test stub, gets the real Mathematical-Alphanumeric glyph automatically.
fn resolve_variant_char(interp: &Interp, ctx: &Context, c: char, size: Length) -> char {
    let mapped = ctx
        .math_variant_char_map
        .get(&(c, ctx.math_char_class))
        .copied()
        .or_else(|| default_math_variant_char(ctx.math_char_class, c));
    match mapped {
        Some(m) if math_char_available(interp, ctx, m, size) => m,
        _ => c,
    }
}

/// Invoke ONE `paren` closure (`math.satyh`'s `paren-left`/
/// `paren-right`/`abs-left`/`brace-left`/…) exactly the way upstream's
/// `make_paren` does (`math.ml:644-649`): 5 CURRIED args in order — inner
/// height `h_in` (≥0), inner depth SIGNED (≤0, hence `-d_in` — this port
/// carries depths as non-negative magnitudes, see this function's `d_in`
/// param doc below), the axis height at the local size, the local
/// (script-scaled) size, and the current text color — then unpack the
/// returned `(inline-boxes, length -> length)` 2-tuple and harvest the
/// boxes' glyphs/rules/width via `math_boxes_of_inline_boxes` (the
/// graphics-harvesting sibling of `math_glyphs_of_inline_boxes`, since a
/// closure's delimiter is drawn `Fill`/`Stroke` ink via `inline-graphics`,
/// not a font glyph). The kernf itself is returned un-invoked (callers
/// re-derive/discard it as `math.ml:923` does for `ParenWithMiddle`'s own
/// middle).
///
/// `d_in`: this port's non-negative ink-depth MAGNITUDE (`inner_ink_extent`'s
/// second component). Upstream's own box depths are non-positive internally
/// (`convert_to_low`'s `dC` folds via `Length.min`, always ≤ `Length.zero`),
/// and `half-length` (`math.satyh:1023-1026`) computes the below-axis need
/// as `hgtaxis +' dpt` on that SIGNED value — so passing the magnitude
/// directly would OVERSIZE every delimiter below the axis (double-counts
/// the depth on the wrong side). Negating here is what keeps the closure's
/// own arithmetic faithful without changing this port's magnitude
/// convention everywhere else.
fn make_paren_run(
    interp: &mut Interp,
    ctx: &Context,
    paren: &Value,
    h_in: Length,
    d_in: Length,
    axis: Length,
    size: Length,
) -> Result<(Vec<MathGlyph>, Vec<GraphicsElem>, Length, Value), EvalError> {
    let mut v = paren.clone();
    if interp.version.math_is_split() {
        // 0.1 protocol (math.ml:640-642): `paren h d ictx` — (height, SIGNED
        // depth, context). The closure extracts fontsize / axis-ratio (via
        // `get-math-axis-height-ratio`) / color FROM the context instead of
        // receiving them as separate explicit arguments (the 0.0.6→0.1
        // delta, `t_paren`'s doc comment). Upstream's `ictx` is already
        // scaled to the local (script-level) size at this call site; this
        // port threads `size` as a separate parameter, so clone-and-set —
        // BIGGEST RISK: forgetting this silently
        // oversizes script-level delimiters (the closure would read the
        // OUTER context's font_size instead of the local scaled one).
        let mut c2 = ctx.clone();
        c2.font_size = size;
        let args = [
            Value::Length(h_in),
            Value::Length(-d_in),
            Value::Context(Box::new(c2)),
        ];
        for a in args {
            v = interp.apply(v, a)?;
        }
    } else {
        // 0.0.6 protocol.
        let args = [
            Value::Length(h_in),
            Value::Length(-d_in),
            Value::Length(axis),
            Value::Length(size),
            make_color_value(ctx.text_color),
        ];
        for a in args {
            v = interp.apply(v, a)?;
        }
    }
    let (boxes_v, kernf) = match v {
        Value::Tuple(mut items) if items.len() == 2 => {
            let kernf = items.pop().unwrap();
            (items.pop().unwrap(), kernf)
        }
        other => {
            return eval_error(format!(
                "math-paren: a paren closure must return (inline-boxes, length -> length), got {}",
                other.type_name()
            ))
        }
    };
    let boxes = as_inline_boxes(boxes_v)?;
    let (glyphs, rules, width) = math_boxes_of_inline_boxes(&boxes);
    Ok((glyphs, rules, width, kernf))
}

/// The original MATH-native stretchy-delimiter body, extracted verbatim as
/// the fallback `Math::Paren`/`Math::ParenWithMiddle` now take when the
/// closure route (`make_paren_run`, primary — upstream-faithful) errors:
/// every delimiter renders as a correctly-SIZED `(`/`)`/`|` regardless of
/// the requested paren kind (identity-wrong, but usable, for any closure
/// that can't be run — a synthetic/ill-shaped test closure, or a real error
/// from a malformed user-supplied one).
fn paren_variant_fallback(
    interp: &mut Interp,
    ctx: &Context,
    parts: Vec<(Vec<MathGlyph>, Vec<GraphicsElem>, Length)>,
    h_in: Length,
    d_in: Length,
    axis: Length,
    size: Length,
) -> Result<
    (
        Vec<MathGlyph>,
        Vec<GraphicsElem>,
        Length,
        MathKind,
        MathKind,
    ),
    EvalError,
> {
    let target = (h_in - axis).max(axis + d_in) * 2.0;
    let mut glyphs = Vec::new();
    let mut rules = Vec::new();
    let mut x = Length::ZERO;
    push_delimiter_glyph(interp, ctx, '(', size, target, axis, &mut glyphs, &mut x)?;
    for (i, (pg, pr, pw)) in parts.into_iter().enumerate() {
        if i > 0 {
            push_delimiter_glyph(interp, ctx, '|', size, target, axis, &mut glyphs, &mut x)?;
        }
        append_at(&mut glyphs, &mut rules, &mut x, pg, pr, pw);
    }
    push_delimiter_glyph(interp, ctx, ')', size, target, axis, &mut glyphs, &mut x)?;
    Ok((glyphs, rules, x, MathKind::Open, MathKind::Close))
}

/// Re-derive a paren base's TRAILING (right) delimiter's dense math
/// kern function by re-invoking its closure at the script-attachment site
/// (`superscript_kern`'s glyph-corner sampling doesn't apply to a paren
/// base — it has no single "last glyph" to sample italic-correction/corner
/// kerns off; the closure itself IS the source of truth for how much a
/// script should tuck into it, exactly upstream's `lp_math_kern_scheme`,
/// `math.ml:906`/`922`). Closures are pure (`math.satyh`'s bundled ones
/// have no side effects), so re-invoking with the SAME `(h_in, d_in, axis,
/// size)` the original `Math::Paren`/`ParenWithMiddle` layout used yields
/// the identical `kernf` value. Returns `None` when `base`'s last atom
/// isn't a paren, or when re-running its closure(s) errors (the delimiter
/// fallback path carries no math-kern scheme at all — `dense_kern`'s
/// caller then falls back to zero, matching that stand-in's own
/// `kerninfo _ = 0pt` shape).
fn paren_trailing_kernf(
    interp: &mut Interp,
    ctx: &Context,
    base: &[Math],
    size: Length,
) -> Option<Value> {
    let (r, h_in, d_in) = match base.last()? {
        Math::Paren(_, r, inner) => {
            let (g, ru, ..) = layout_math_list(interp, ctx, inner, size).ok()?;
            let (h, d) = inner_ink_extent(&g, &ru);
            (r, h, d)
        }
        Math::ParenWithMiddle(_, r, _, parts) => {
            let mut h = Length::ZERO;
            let mut d = Length::ZERO;
            for p in parts {
                let (g, ru, ..) = layout_math_list(interp, ctx, p, size).ok()?;
                let (ph, pd) = inner_ink_extent(&g, &ru);
                h = h.max(ph);
                d = d.max(pd);
            }
            (r, h, d)
        }
        _ => return None,
    };
    let mc = MathC::of(interp, ctx);
    let axis = mc.axis(size);
    let (_, _, _, kernf) = make_paren_run(interp, ctx, r, h_in, d_in, axis, size).ok()?;
    Some(kernf)
}

/// `fontInfo.ml:361`'s `DenseMathKern` branch: `Length.negate (kernf
/// corrhgt)` — the closure returns a POSITIVE tuck amount (how far to slide
/// the script INTO the delimiter's hollow), and the engine negates it into
/// a kern (negative = closer to the previous glyph, `get_math_kern`'s own
/// doc comment). Any failure (wrong-shaped return, closure error) collapses
/// to `Length::ZERO` — no kern, not a layout error; matches
/// `paren_trailing_kernf`'s own `None`-on-error contract.
fn dense_kern(interp: &mut Interp, kernf: &Value, corrhgt: Length) -> Length {
    match interp.apply(kernf.clone(), Value::Length(corrhgt)) {
        Ok(Value::Length(l)) => -l,
        _ => Length::ZERO,
    }
}

/// Lay out one `Math` atom at `size` (LOCAL coordinates, `x` starting at
/// 0), returning its glyphs, any graphics `rules` it pushed (only the
/// `Fraction`/`Radical` arms produce any; every other arm forwards its
/// children's), width, and left/right boundary class.
fn layout_math_atom(
    interp: &mut Interp,
    ctx: &Context,
    atom: &Math,
    size: Length,
) -> Result<
    (
        Vec<MathGlyph>,
        Vec<GraphicsElem>,
        Length,
        MathKind,
        MathKind,
    ),
    EvalError,
> {
    match atom {
        Math::Pure(MathElement::Char { class, big, chars })
        | Math::Pure(MathElement::CharWithKern {
            class, big, chars, ..
        }) => {
            let mut glyphs = Vec::new();
            let mut x = Length::ZERO;
            for c in chars.chars() {
                if *big {
                    push_big_char_glyph(interp, ctx, c, size, &mut glyphs, &mut x)?;
                } else {
                    push_char_glyph(interp, ctx, c, size, &mut glyphs, &mut x)?;
                }
            }
            Ok((glyphs, Vec::new(), x, *class, *class))
        }
        Math::Pure(MathElement::VariantChar { class, style, .. }) => {
            // Select the target codepoints by the CURRENT restyling
            // (`Context::math_char_class`, set by `ChangeCharClass`'s
            // layout arm below) rather than always `style.italic` — these
            // are explicit per-style codepoints the caller built
            // (`math-variant-char`), so no metrics-probe fallback (unlike
            // `resolve_variant_char`): `push_char_glyph` errors like any
            // other explicit-codepoint atom if the font can't render it.
            let text = match ctx.math_char_class {
                MathCharClass::Italic => &style.italic,
                MathCharClass::BoldItalic => &style.bold_italic,
                MathCharClass::Roman => &style.roman,
                MathCharClass::BoldRoman => &style.bold_roman,
                MathCharClass::Script => &style.script,
                MathCharClass::BoldScript => &style.bold_script,
                MathCharClass::Fraktur => &style.fraktur,
                MathCharClass::BoldFraktur => &style.bold_fraktur,
                MathCharClass::DoubleStruck => &style.double_struck,
                // `MathVariantStyle` (this
                // 9-field record) is deliberately NOT widened to 14 fields
                // — it models the 0.0.6 `math-variant-char` prim's record
                // shape, which upstream itself never grew sans-
                // serif/typewriter fields for either (only `math-char-class`
                // itself widened, `horzBox.ml:98-113`). This arm is
                // unreachable in practice: `math-variant-char`/
                // `MathElement::VariantChar` is a V0_0-only prim
                // (registered `v006` only, `primitives.rs`'s prim table),
                // and the 5 new `MathCharClass` ctors are V0_1-only
                // (`prim_types.rs::math_char_class_decl`) — the two can
                // never co-occur. Closest-analog fallback, purely to keep
                // the match exhaustive.
                MathCharClass::SansSerif | MathCharClass::Typewriter => &style.roman,
                MathCharClass::ItalicSansSerif => &style.italic,
                MathCharClass::BoldSansSerif => &style.bold_roman,
                MathCharClass::BoldItalicSansSerif => &style.bold_italic,
            };
            let mut glyphs = Vec::new();
            let mut x = Length::ZERO;
            for c in text.chars() {
                push_char_glyph(interp, ctx, c, size, &mut glyphs, &mut x)?;
            }
            Ok((glyphs, Vec::new(), x, *class, *class))
        }
        Math::Pure(MathElement::VariantCharPending(s)) => {
            // One MATHCHAR token, resolved now that `ctx` (font +
            // math_char_class + both override maps) is available: first
            // try the whole-TOKEN class map (`=`, `-`, `,`, … ->
            // (replacement, MathKind)); if the token isn't there, fall back
            // to a per-char variant remap (the metrics-probe policy)
            // with `MathKind::Ord`.
            let mut glyphs = Vec::new();
            let mut x = Length::ZERO;
            if let Some((target, kind)) = ctx.math_class_map.get(s.as_str()) {
                let kind = *kind;
                let all_renderable = target
                    .chars()
                    .all(|c| math_char_available(interp, ctx, c, size));
                let chosen = if all_renderable {
                    target.clone()
                } else {
                    s.clone()
                };
                for c in chosen.chars() {
                    push_char_glyph(interp, ctx, c, size, &mut glyphs, &mut x)?;
                }
                return Ok((glyphs, Vec::new(), x, kind, kind));
            }
            for c in s.chars() {
                let chosen = resolve_variant_char(interp, ctx, c, size);
                push_char_glyph(interp, ctx, chosen, size, &mut glyphs, &mut x)?;
            }
            Ok((glyphs, Vec::new(), x, MathKind::Ord, MathKind::Ord))
        }
        Math::Pure(MathElement::EmbeddedText { class, body }) => {
            let v = interp.apply((**body).clone(), Value::Context(Box::new(ctx.clone())))?;
            let boxes = as_inline_boxes(v)?;
            // `math_boxes_of_inline_boxes`, not the glyphs-only walk: embedded
            // inline content can carry its ink as GRAPHICS rather than glyphs.
            // latexcmds' `\underset`/`\overset` are exactly that — they reduce
            // to `text-in-math (… \normal-underset …)`, which draws through
            // `inline-graphics` + `draw-text`. Harvesting glyphs alone kept the
            // box's WIDTH and threw the drawing away, so the Schrödinger-equation
            // example rendered as `[−     + V(x)]Ψ`: a correctly-sized hole where
            // the fraction and its under-text should be.
            let (glyphs, rules, width) = math_boxes_of_inline_boxes(&boxes);
            Ok((glyphs, rules, width, *class, *class))
        }
        Math::Pure(MathElement::EmbeddedBoxes { class, boxes }) => {
            // V0_1 `embed-inline-to-math`: eager, already-materialized
            // boxes, so no closure application (contrast `EmbeddedText`
            // above) — but the same graphics-bearing content is possible.
            let (glyphs, rules, width) = math_boxes_of_inline_boxes(boxes);
            Ok((glyphs, rules, width, *class, *class))
        }
        Math::Group(cls1, cls2, inner) => {
            let (glyphs, rules, width, _, _) = layout_math_list(interp, ctx, inner, size)?;
            Ok((glyphs, rules, width, *cls1, *cls2))
        }
        Math::Sup(base, script) => {
            // Upstream MathSuperscript: (1) check_subscript merges a
            // base-tail `Sub` into one base + (sub, sup) pair;
            // (2) check_pull_in hands the script(s) to a base-tail
            // `PullInScripts` resolver.
            if let Some((sub_script, new_base)) = check_subscript(base) {
                if let Some((Math::PullInScripts(cls1, cls2, resolver), head)) =
                    new_base.split_last()
                {
                    return layout_pull_in_scripts(
                        interp,
                        ctx,
                        head,
                        *cls1,
                        *cls2,
                        resolver,
                        Some(&sub_script),
                        Some(script),
                        size,
                    );
                }
                // No pull-in (`{x_1}^2`): one sub+sup pair on the same base.
                let (mut glyphs, mut rules, base_width, left, _) =
                    layout_math_list(interp, ctx, &new_base, size)?;
                let mc = MathC::of(interp, ctx);
                let script_size = size * mc.script_scale();
                // Re-derive ONCE (a paren base's dense math
                // kern function, if `new_base`'s trailing atom is a paren —
                // `paren_trailing_kernf`'s doc comment) and reuse it for
                // BOTH the sup and sub kerns below, mirroring
                // `lp_math_kern_scheme`'s single scheme feeding both corner
                // attachments upstream.
                let paren_kernf = paren_trailing_kernf(interp, ctx, &new_base, size);
                // Subscripts are always cramped; the superscript inherits
                // the ambient cramped state unchanged (do NOT flip/reset it
                // here).
                let sub_ctx = Context {
                    math_cramped: true,
                    ..ctx.clone()
                };
                let (sub_glyphs, sub_rules, sub_width, _, _) =
                    layout_math_list(interp, &sub_ctx, &sub_script, script_size)?;
                let (sup_glyphs, sup_rules, sup_width, _, _) =
                    layout_math_list(interp, ctx, script, script_size)?;
                let (h_base, d_base) = inner_ink_extent(&glyphs, &rules);
                let (_, d_sup) = inner_ink_extent(&sup_glyphs, &sup_rules);
                let (h_sub, _) = inner_ink_extent(&sub_glyphs, &sub_rules);
                let sup_shift_raw = mc.sup_shift_clamped(ctx.font_size, h_base, d_sup);
                let sub_shift_raw = mc.sub_shift_clamped(ctx.font_size, d_base, h_sub);
                let (sup_shift, sub_shift) = mc.correct_script_gap(
                    ctx.font_size,
                    d_sup,
                    h_sub,
                    sup_shift_raw,
                    sub_shift_raw,
                );
                let kern = match &paren_kernf {
                    Some(kf) => dense_kern(interp, kf, sup_shift - d_sup),
                    None => superscript_kern(
                        interp,
                        ctx,
                        size,
                        script_size,
                        &glyphs,
                        &sup_glyphs,
                        sup_shift,
                        h_base,
                        d_sup,
                    ),
                };
                let sub_kern = paren_kernf
                    .as_ref()
                    .map(|kf| dense_kern(interp, kf, h_sub - d_base))
                    .unwrap_or(Length::ZERO);
                shift_and_append(
                    &mut glyphs,
                    &mut rules,
                    sub_glyphs,
                    sub_rules,
                    base_width + sub_kern,
                    -sub_shift,
                );
                shift_and_append(
                    &mut glyphs,
                    &mut rules,
                    sup_glyphs,
                    sup_rules,
                    base_width + kern,
                    sup_shift,
                );
                return Ok((
                    glyphs,
                    rules,
                    base_width + (sub_kern + sub_width).max(kern + sup_width),
                    left,
                    MathKind::Ord,
                ));
            }
            if let Some((Math::PullInScripts(cls1, cls2, resolver), head)) = base.split_last() {
                return layout_pull_in_scripts(
                    interp,
                    ctx,
                    head,
                    *cls1,
                    *cls2,
                    resolver,
                    None,
                    Some(script),
                    size,
                );
            }
            let (mut glyphs, mut rules, base_width, left, _) =
                layout_math_list(interp, ctx, base, size)?;
            let mc = MathC::of(interp, ctx);
            let script_size = size * mc.script_scale();
            let (script_glyphs, script_rules, script_width, _, _) =
                layout_math_list(interp, ctx, script, script_size)?;
            let (h_base, _) = inner_ink_extent(&glyphs, &rules);
            let (_, d_sup) = inner_ink_extent(&script_glyphs, &script_rules);
            let sup_shift = mc.sup_shift_clamped(ctx.font_size, h_base, d_sup);
            // A paren base has no italic correction / glyph
            // corner kern to sample (`superscript_kern`'s own last-glyph
            // sampling would hit the INNER run's last glyph, not the
            // delimiter) — its closure's dense kern REPLACES
            // `superscript_kern` outright rather than adding to it.
            let kern = match paren_trailing_kernf(interp, ctx, base, size) {
                Some(kf) => dense_kern(interp, &kf, sup_shift - d_sup),
                None => superscript_kern(
                    interp,
                    ctx,
                    size,
                    script_size,
                    &glyphs,
                    &script_glyphs,
                    sup_shift,
                    h_base,
                    d_sup,
                ),
            };
            shift_and_append(
                &mut glyphs,
                &mut rules,
                script_glyphs,
                script_rules,
                base_width + kern,
                sup_shift,
            );
            Ok((
                glyphs,
                rules,
                base_width + kern + script_width,
                left,
                MathKind::Ord,
            ))
        }
        Math::Sub(base, script) => {
            // Upstream MathSubscript: a `PullInScripts` at the base list's
            // TAIL receives the subscript itself instead of a corner script.
            if let Some((Math::PullInScripts(cls1, cls2, resolver), head)) = base.split_last() {
                return layout_pull_in_scripts(
                    interp,
                    ctx,
                    head,
                    *cls1,
                    *cls2,
                    resolver,
                    Some(script),
                    None,
                    size,
                );
            }
            let (mut glyphs, mut rules, base_width, left, _) =
                layout_math_list(interp, ctx, base, size)?;
            let mc = MathC::of(interp, ctx);
            let script_size = size * mc.script_scale();
            // Subscripts are always cramped.
            let sub_ctx = Context {
                math_cramped: true,
                ..ctx.clone()
            };
            let (script_glyphs, script_rules, script_width, _, _) =
                layout_math_list(interp, &sub_ctx, script, script_size)?;
            let (_, d_base) = inner_ink_extent(&glyphs, &rules);
            let (h_sub, _) = inner_ink_extent(&script_glyphs, &script_rules);
            let sub_shift = mc.sub_shift_clamped(ctx.font_size, d_base, h_sub);
            // Non-paren subscripts carry no kern (`kern = Length::ZERO`); a
            // paren base's closure supplies one via `paren_trailing_kernf`'s
            // `Some` arm.
            let kern = match paren_trailing_kernf(interp, ctx, base, size) {
                Some(kf) => dense_kern(interp, &kf, h_sub - d_base),
                None => Length::ZERO,
            };
            shift_and_append(
                &mut glyphs,
                &mut rules,
                script_glyphs,
                script_rules,
                base_width + kern,
                -sub_shift,
            );
            Ok((
                glyphs,
                rules,
                base_width + kern + script_width,
                left,
                MathKind::Ord,
            ))
        }
        Math::ChangeColor(_, inner) => {
            // STAND-IN: color restyling doesn't affect glyph rendering yet
            // — just render the content.
            let (glyphs, rules, width, left, right) = layout_math_list(interp, ctx, inner, size)?;
            Ok((glyphs, rules, width, left, right))
        }
        Math::ChangeCharClass(cls, inner) => {
            // Lay `inner` out under a
            // context with `math_char_class` set to `cls`, which is what
            // `VariantCharPending`/`VariantChar`'s arms above consult.
            let ctx2 = Context {
                math_char_class: *cls,
                ..ctx.clone()
            };
            let (glyphs, rules, width, left, right) = layout_math_list(interp, &ctx2, inner, size)?;
            Ok((glyphs, rules, width, left, right))
        }
        Math::Fraction(num, den) => {
            // Real numerator/denominator placement (`math.ml:574-594`
            // `numerator_baseline_height`/ `denominator_baseline_depth`)
            // plus a bar `Fill` — replaces the ASCII "num / den" stand-in.
            // `num`/`den` are laid out at the SAME `size` as this atom (no
            // script-scale reduction — a fraction's own
            // numerator/denominator aren't scripts, matching upstream's
            // `convert_to_low` call with the ambient `mathctx` unchanged).
            let (num_glyphs, num_rules, num_w, ..) = layout_math_list(interp, ctx, num, size)?;
            // The denominator is always cramped; the numerator inherits the
            // ambient cramped state unchanged.
            let den_ctx = Context {
                math_cramped: true,
                ..ctx.clone()
            };
            let (den_glyphs, den_rules, den_w, ..) = layout_math_list(interp, &den_ctx, den, size)?;
            let w = num_w.max(den_w);
            // Center the narrower of the two over/under the wider
            // (`math.ml:1140-1155`'s symmetric padding).
            let num_dx = (w - num_w) * 0.5;
            let den_dx = (w - den_w) * 0.5;
            let (_, d_numer) = inner_ink_extent(&num_glyphs, &num_rules);
            let (h_denom, _) = inner_ink_extent(&den_glyphs, &den_rules);
            let mc = MathC::of(interp, ctx);
            let numer_shift = mc.frac_numer_shift(size, d_numer);
            let denom_shift = mc.frac_denom_shift(size, h_denom);
            let axis = mc.axis(size);
            let rule = mc.frac_rule(size);
            let mut glyphs = Vec::new();
            let mut rules = Vec::new();
            // `num dy>0` (raised above the axis), `den dy<0` (`frac_denom_
            // shift` is already signed negative — see that method's doc
            // comment) — both applied via the SAME up-positive `dy_shift`
            // `shift_and_append` uses for Sup/Sub.
            shift_and_append(
                &mut glyphs,
                &mut rules,
                num_glyphs,
                num_rules,
                num_dx,
                numer_shift,
            );
            shift_and_append(
                &mut glyphs,
                &mut rules,
                den_glyphs,
                den_rules,
                den_dx,
                denom_shift,
            );
            // The bar itself: `rect x∈[0,w], y∈[axis·s, axis·s+rule·s]`
            // (a deliberate simplification of
            // upstream's own `Rectangle((xpos, ypos+h_bar+t_bar/2), (wid,
            // t_bar))`, which centers the rule on its OWN half-thickness
            // rather than sitting flush on the axis; this port picks the
            // simpler flush-on-axis placement instead).
            rules.push(GraphicsElem::Fill(
                ctx.text_color,
                rect_path((Length::ZERO, axis), (w, rule)),
            ));
            Ok((glyphs, rules, w, MathKind::Inner, MathKind::Inner))
        }
        Math::Radical(_degree, inner) => {
            // Real bar metrics (`math.ml:620-626` `radical_bar_
            // metrics`) plus a ported `default_radical` checkmark `Fill`
            // (`primitives.cppo.ml:311-355`) and an overbar rect `Fill` —
            // replaces the U+221A stand-in. `RadicalWithDegree` (`_degree =
            // Some(..)`, `\sqrt[n]{..}`) stays unimplemented — the degree is
            // carried faithfully in the
            // `Math` value but silently NOT drawn, matching upstream's own
            // parity note (`math.ml:886-899`'s `failwith "unsupported"` is
            // upstream's harder failure mode; this port's own stand-in
            // policy already chose "render the radicand
            // without the degree" over erroring, unchanged since).
            // The radicand is always cramped.
            let radicand_ctx = Context {
                math_cramped: true,
                ..ctx.clone()
            };
            let (inner_glyphs, inner_rules, inner_w, ..) =
                layout_math_list(interp, &radicand_ctx, inner, size)?;
            let (h_cont, d_cont) = inner_ink_extent(&inner_glyphs, &inner_rules);
            let mc = MathC::of(interp, ctx);
            let (h_bar, t_bar, l_extra) = mc.radical_bar_metrics(size, h_cont);
            // `_nonnegdpt` (the sign's own, slightly deeper, ink extent —
            // `default_radical`'s downward checkmark stroke pads `d_cont` by
            // `size*0.1`, upstream's own `nonnegdpt`) isn't threaded into
            // this atom's reported `depth` directly: unlike upstream's own
            // `d_whole = d_cont` (`math.ml:884`, a "temporary" simplification
            // per its own comment there), this port's `layout_math_value`
            // folds every rule's `graphics_bbox` into the OUTER box's
            // height/depth (a correctness fix, `PureHorzBox::Math`'s doc
            // comment), so the sign's real ink depth reaches the top-level
            // box automatically THROUGH the drawn `Fill` — no separate
            // manual accounting needed here.
            let (sign_path, sign_w, _nonnegdpt) = radical_sign_geometry(size, h_bar, t_bar, d_cont);
            let mut rules = vec![GraphicsElem::Fill(ctx.text_color, sign_path)];
            // Overbar + radicand share the same x-range right after the
            // sign (`math.ml:1163-1176`'s `hbbar`/`hbback`/`hblstC`); the
            // radicand itself stays at `dy = 0` (its own baseline), exactly
            // upstream — `h_bar` already clears it via the vertical-gap add
            // in `radical_bar_metrics`, so no raise is needed here.
            rules.push(GraphicsElem::Fill(
                ctx.text_color,
                rect_path((sign_w, h_bar), (inner_w, t_bar)),
            ));
            // `l_extra`: the extra ascender ABOVE the bar this run reports
            // to its container (upstream `h_whole = h_rad +% l_extra`,
            // `math.ml:882`) — no ink of its own, just headroom, so there's
            // no glyph/fill shape to naturally carry it. A single-point
            // "extent marker" `Fill` (a subpath with a `move_to` and no
            // further segments paints nothing — PDF's `f` on a degenerate
            // zero-length path is a no-op) reports it through the SAME
            // `graphics_bbox` fold `layout_math_value` already does for
            // every rule, without adding a new return channel just for this
            // one field.
            rules.push(GraphicsElem::Fill(
                ctx.text_color,
                Path {
                    subpaths: vec![Subpath {
                        start: (Length::ZERO, h_bar + t_bar + l_extra),
                        segs: Vec::new(),
                        closing: Closing::Open,
                    }],
                },
            ));
            let mut glyphs = Vec::new();
            for mut g in inner_glyphs {
                g.dx = sign_w + g.dx;
                glyphs.push(g);
            }
            for r in &inner_rules {
                rules.push(shift_graphics((sign_w, Length::ZERO), r));
            }
            Ok((
                glyphs,
                rules,
                sign_w + inner_w,
                MathKind::Inner,
                MathKind::Inner,
            ))
        }
        Math::Paren(l, r, inner) => {
            // PRIMARY route is upstream's own `make_paren` closure
            // invocation (`math.ml:644-649`, `make_paren_run` above) —
            // identity (a `\paren` drawing round parens vs. an `\abs`
            // drawing vertical bars, etc.) lives ENTIRELY in the `l`/`r`
            // closures (`math.satyh`'s `paren-left`/`abs-left`/…), so
            // running them is what makes different delimiter kinds actually
            // look different. Falls back to the MATH-native
            // stretchy-variant stand-in (`paren_variant_fallback`) only if
            // either closure errors (synthetic/ill-shaped test closures, or
            // a real user error) — that fallback's own delimiter kind is
            // always `(`/`)` regardless of what was requested. Inner is laid
            // out OUTSIDE the closure
            // route so an inner layout error still propagates normally
            // (only closure-route errors trigger the fallback); splice
            // order `lg ++ inner ++ rg` matches upstream's own
            // `LowMathParen(lpL, lpR, lmC)` (`math.ml:909`).
            let (inner_glyphs, inner_rules, inner_w, ..) =
                layout_math_list(interp, ctx, inner, size)?;
            let (h_in, d_in) = inner_ink_extent(&inner_glyphs, &inner_rules);
            let mc = MathC::of(interp, ctx);
            let axis = mc.axis(size);
            let closure_route =
                make_paren_run(interp, ctx, l, h_in, d_in, axis, size).and_then(|left| {
                    let right = make_paren_run(interp, ctx, r, h_in, d_in, axis, size)?;
                    Ok((left, right))
                });
            match closure_route {
                Ok(((lg, lr, lw, _), (rg, rr, rw, _))) => {
                    let mut glyphs = Vec::new();
                    let mut rules = Vec::new();
                    let mut x = Length::ZERO;
                    append_at(&mut glyphs, &mut rules, &mut x, lg, lr, lw);
                    append_at(
                        &mut glyphs,
                        &mut rules,
                        &mut x,
                        inner_glyphs,
                        inner_rules,
                        inner_w,
                    );
                    append_at(&mut glyphs, &mut rules, &mut x, rg, rr, rw);
                    Ok((glyphs, rules, x, MathKind::Open, MathKind::Close))
                }
                Err(_) => paren_variant_fallback(
                    interp,
                    ctx,
                    vec![(inner_glyphs, inner_rules, inner_w)],
                    h_in,
                    d_in,
                    axis,
                    size,
                ),
            }
        }
        Math::ParenWithMiddle(l, r, m, mlstlst) => {
            // Same closure-primary/fallback policy as `Math::Paren`,
            // but ONE shared `(h_in, d_in)` over every part (the tallest
            // part's ink drives the size of every delimiter, including the
            // middle separator(s)) — mirrors upstream's own
            // `MathParenWithMiddle` fold (`math.ml:912-916`). The middle
            // closure's own kernf is DISCARDED (`math.ml:923`: `let
            // (hblstmiddle, _) = make_paren mathctx middle hC dC in ...`) —
            // a separator never tucks a script into itself.
            let mut parts = Vec::with_capacity(mlstlst.len());
            let mut h_in = Length::ZERO;
            let mut d_in = Length::ZERO;
            for part in mlstlst {
                let (part_glyphs, part_rules, part_w, ..) =
                    layout_math_list(interp, ctx, part, size)?;
                let (h, d) = inner_ink_extent(&part_glyphs, &part_rules);
                h_in = h_in.max(h);
                d_in = d_in.max(d);
                parts.push((part_glyphs, part_rules, part_w));
            }
            let mc = MathC::of(interp, ctx);
            let axis = mc.axis(size);
            let closure_route =
                make_paren_run(interp, ctx, l, h_in, d_in, axis, size).and_then(|left| {
                    let right = make_paren_run(interp, ctx, r, h_in, d_in, axis, size)?;
                    let middle = make_paren_run(interp, ctx, m, h_in, d_in, axis, size)?;
                    Ok((left, right, middle))
                });
            match closure_route {
                Ok(((lg, lr, lw, _), (rg, rr, rw, _), (mg, mr, mw, _))) => {
                    let mut glyphs = Vec::new();
                    let mut rules = Vec::new();
                    let mut x = Length::ZERO;
                    append_at(&mut glyphs, &mut rules, &mut x, lg, lr, lw);
                    for (i, (part_glyphs, part_rules, part_w)) in parts.into_iter().enumerate() {
                        if i > 0 {
                            append_at(&mut glyphs, &mut rules, &mut x, mg.clone(), mr.clone(), mw);
                        }
                        append_at(
                            &mut glyphs,
                            &mut rules,
                            &mut x,
                            part_glyphs,
                            part_rules,
                            part_w,
                        );
                    }
                    append_at(&mut glyphs, &mut rules, &mut x, rg, rr, rw);
                    Ok((glyphs, rules, x, MathKind::Open, MathKind::Close))
                }
                Err(_) => paren_variant_fallback(interp, ctx, parts, h_in, d_in, axis, size),
            }
        }
        Math::UpperLimit(base, upper) => {
            let (mut glyphs, mut rules, base_width, left, right) =
                layout_math_list(interp, ctx, base, size)?;
            let mc = MathC::of(interp, ctx);
            let script_size = size * mc.script_scale();
            let (script_glyphs, script_rules, script_width, _, _) =
                layout_math_list(interp, ctx, upper, script_size)?;
            let (h_base, _) = inner_ink_extent(&glyphs, &rules);
            let (_, d_up) = inner_ink_extent(&script_glyphs, &script_rules);
            let up_shift = mc.upper_limit_shift(ctx.font_size, h_base, d_up);
            // A LIMIT is CENTERED over its base, not set beside it
            // (`math.ml:1219-1231`: upstream pads the narrower of the two with
            // half the difference on each side, so the whole is
            // `max(w_base, w_up)` wide). Placing it at `base_width` — i.e. to
            // the right, widening the box to the SUM — set `\sum_a^b`'s limits
            // off the operator's shoulder instead of above and below it.
            let (base_dx, script_dx) = center_offsets(base_width, script_width);
            shift_existing(&mut glyphs, &mut rules, base_dx);
            shift_and_append(
                &mut glyphs,
                &mut rules,
                script_glyphs,
                script_rules,
                script_dx,
                up_shift,
            );
            Ok((glyphs, rules, base_width.max(script_width), left, right))
        }
        Math::LowerLimit(base, lower) => {
            let (mut glyphs, mut rules, base_width, left, right) =
                layout_math_list(interp, ctx, base, size)?;
            let mc = MathC::of(interp, ctx);
            let script_size = size * mc.script_scale();
            let (script_glyphs, script_rules, script_width, _, _) =
                layout_math_list(interp, ctx, lower, script_size)?;
            let (_, d_base) = inner_ink_extent(&glyphs, &rules);
            let (h_low, _) = inner_ink_extent(&script_glyphs, &script_rules);
            let low_shift = mc.lower_limit_shift(ctx.font_size, d_base, h_low);
            // Centered under the base — see the `UpperLimit` arm above.
            let (base_dx, script_dx) = center_offsets(base_width, script_width);
            shift_existing(&mut glyphs, &mut rules, base_dx);
            shift_and_append(
                &mut glyphs,
                &mut rules,
                script_glyphs,
                script_rules,
                script_dx,
                -low_shift,
            );
            Ok((glyphs, rules, base_width.max(script_width), left, right))
        }
        Math::PullInScripts(cls1, cls2, resolver) => {
            // Not consumed by an enclosing Sub/Sup (bare `\sum` with no
            // scripts): resolver gets (None, None).
            layout_pull_in_scripts(interp, ctx, &[], *cls1, *cls2, resolver, None, None, size)
        }
        // V0_1 only (`read-math`): lay `inner` out
        // with ambient context = the STORED context, and size = the
        // stored context's OWN `font_size` — an ABSOLUTE override, not a
        // further multiply of the caller's `size`. This is deliberate: a
        // `WithContext` built under an `enter_script`-shrunk context
        // already carries the script-shrunk `font_size` in `stored`, so
        // laying it out at `stored.font_size` (rather than at this call's
        // `size`) means the engine's own Sup/Sub shrink is never applied a
        // second time on top of it.
        Math::WithContext(stored, inner) => {
            layout_math_list(interp, stored, inner, stored.font_size)
        }
    }
}

/// Append `glyphs`/`rules` (already at LOCAL coordinates relative to their
/// own run) onto `out_glyphs`/`out_rules` at the running `*x`, advancing `*x`
/// past them — the no-spacing-adjustment sibling of `layout_math_list`'s
/// per-atom loop, used by the structural stand-ins above (paren) that
/// concatenate sub-runs directly rather than through the spacing table.
/// `rules` shifts horizontally only (`shift_graphics` with a zero `dy` —
/// `append_at`'s callers never raise/lower a sub-run, only `dx`-place it;
/// contrast `shift_and_append` below, which does both).
fn append_at(
    out_glyphs: &mut Vec<MathGlyph>,
    out_rules: &mut Vec<GraphicsElem>,
    x: &mut Length,
    glyphs: Vec<MathGlyph>,
    rules: Vec<GraphicsElem>,
    width: Length,
) {
    let base_x = *x;
    for mut g in glyphs {
        g.dx = base_x + g.dx;
        out_glyphs.push(g);
    }
    for r in &rules {
        out_rules.push(shift_graphics((base_x, Length::ZERO), r));
    }
    *x = base_x + width;
}

/// Horizontal offsets that CENTER a limit against its base: half the width
/// difference goes to whichever of the two is narrower, so the pair occupies
/// `max(base, script)` (upstream `math.ml:1219-1231`).
fn center_offsets(base_width: Length, script_width: Length) -> (Length, Length) {
    if base_width < script_width {
        ((script_width - base_width) * 0.5, Length::ZERO)
    } else {
        (Length::ZERO, (base_width - script_width) * 0.5)
    }
}

/// Slide already-emitted glyphs/rules right by `dx` — used when a limit is
/// WIDER than its base, so the base itself has to move to stay centered.
fn shift_existing(glyphs: &mut [MathGlyph], rules: &mut [GraphicsElem], dx: Length) {
    if dx == Length::ZERO {
        return;
    }
    for g in glyphs.iter_mut() {
        g.dx = g.dx + dx;
    }
    for r in rules.iter_mut() {
        *r = shift_graphics((dx, Length::ZERO), r);
    }
}

/// Append `glyphs`/`rules` (LOCAL coordinates, from an isolated
/// `layout_math_list` call) onto `out_glyphs`/`out_rules`, shifting every
/// glyph/rule right by `dx_shift` (its base's own width — placing the
/// script/numerator/denominator/radicand right after the preceding content)
/// and up/down by `dy_shift` (`> 0` raises, `< 0` lowers) — the `Math`-atom
/// analog of `place_script`, which instead threads a single
/// running `x` across a flat `MathElem` list. `rules` go through the SAME
/// `shift_graphics` a standalone `inline-graphics` box's `shift-graphics`
/// primitive uses — box-local, y-**up** coordinates, exactly
/// `MathGlyph::dy`'s sign convention (a critical correctness note: get
/// this sign wrong and a fraction bar/ radical mirrors instead of landing
/// at the axis).
fn shift_and_append(
    out_glyphs: &mut Vec<MathGlyph>,
    out_rules: &mut Vec<GraphicsElem>,
    glyphs: Vec<MathGlyph>,
    rules: Vec<GraphicsElem>,
    dx_shift: Length,
    dy_shift: Length,
) {
    for mut g in glyphs {
        g.dx = dx_shift + g.dx;
        g.dy = g.dy + dy_shift;
        out_glyphs.push(g);
    }
    for r in &rules {
        out_rules.push(shift_graphics((dx_shift, dy_shift), r));
    }
}

/// An axis-aligned rectangle `Fill` path, box-local (y-**up**): bottom-left
/// corner `origin`, extending `size.0` right and `size.1` up. Shared by the
/// fraction bar and the radical overbar — both are exactly this
/// shape, just at different `y`/width.
fn rect_path(origin: Point, size: (Length, Length)) -> Path {
    let (x, y) = origin;
    let (w, h) = size;
    Path {
        subpaths: vec![Subpath {
            start: (x, y),
            segs: vec![
                PathSeg::Line((x + w, y)),
                PathSeg::Line((x + w, y + h)),
                PathSeg::Line((x, y + h)),
            ],
            closing: Closing::Line,
        }],
    }
}

/// Port of `default_radical` (`primitives.cppo.ml:311-355`): the radical
/// checkmark's `GeneralPath`, plus its own natural advance (`wid`, upstream's
/// `PHGFixedGraphics`'s declared width) and `nonnegdpt` (its own depth
/// extent, upstream's declared `depth` — returned for completeness though
/// The overall `Math::Radical` depth uses `d_cont` directly, matching
/// upstream's own "temporary" simplification, see that arm's call site).
/// `size` is the ambient LOCAL nesting size (upstream `fontsize`); `hgt_bar`/
/// `t_bar` come from `MathC::radical_bar_metrics`; `dpt` is the radicand's
/// own depth (a NON-NEGATIVE magnitude, this port's convention — see
/// `sup_shift_clamped`'s doc comment; upstream's signed `Length.negate dpt`
/// becomes a plain ADD of `dpt` here).
///
/// Box-local origin `(0, 0)` = this atom's own baseline-left corner (where
/// upstream's `graphics (xpos, ypos)` closure is finally called with the
/// box's placed anchor — every point below is relative to that same origin,
/// matching `PathSeg`/`Subpath`'s y-**up** convention).
fn radical_sign_geometry(
    size: Length,
    hgt_bar: Length,
    t_bar: Length,
    dpt: Length,
) -> (Path, Length, Length) {
    let w_m = size * 0.02;
    let w1 = size * 0.1;
    let w2 = size * 0.15;
    let w3 = size * 0.4;
    let w_a = size * 0.18;
    let h1 = size * 0.3;
    let h2 = size * 0.375;

    let nonnegdpt = dpt + size * 0.1;
    let l_r = hgt_bar + nonnegdpt;

    let wid = w_m + w1 + w2 + w3;
    let a1 = (h2 - h1) / w1;
    let a2 = h2 / w2;
    let a3 = l_r / w3;
    let t1 = t_bar * (1.0 + a1 * a1).sqrt();
    let t3 = t_bar * (((1.0 + a3 * a3).sqrt() - 1.0) / a3);
    let h_a = h1 + t1 + w_a * a1;
    let w_b = (l_r + t_bar - h_a - (w1 + w2 + w3 - t3 - w_a) * a3) * (-1.0 / (a2 + a3));
    let h_b = h_a - w_b * a2;

    let path = Path {
        subpaths: vec![Subpath {
            start: (wid, hgt_bar),
            segs: vec![
                PathSeg::Line((w_m + w1 + w2, -nonnegdpt)),
                PathSeg::Line((w_m + w1, -nonnegdpt + h2)),
                PathSeg::Line((w_m, -nonnegdpt + h1)),
                PathSeg::Line((w_m, -nonnegdpt + h1 + t1)),
                PathSeg::Line((w_m + w_a, -nonnegdpt + h_a)),
                PathSeg::Line((w_m + w_a + w_b, -nonnegdpt + h_b)),
                PathSeg::Line((wid - t3, hgt_bar + t_bar)),
                PathSeg::Line((wid, hgt_bar + t_bar)),
            ],
            closing: Closing::Line,
        }],
    };
    (path, wid, nonnegdpt)
}

/// Flatten `text-in-math`'s embedded `inline-boxes` (already laid out
/// by `read_inline` against the math atom's own context) into `MathGlyph`s
/// nestable in a math run — the box-in-math bridge `layout_math_atom`'s
/// `EmbeddedText` arm needs. Mirrors `linebreak.rs`'s `natural_metrics`
/// exhaustive `PureHorzBox` walk EXACTLY (same variant list, same "what
/// advances `x`" choice per variant) so an added/renamed `PureHorzBox`
/// variant can't silently drop content here without also breaking that
/// walk. Caveats (faithful to what's actually renderable here): only
/// `InnerString`/nested `Math` boxes contribute real glyphs (hence height/
/// depth, computed by the caller from the returned glyphs); every other
/// box kind (`Image`/`Graphics`/`Tabular`/`EmbeddedBlock`/…) keeps its
/// horizontal space but contributes no ink; text run at full (non-script)
/// size regardless of the math run's own `size` (upstream-faithful — a
/// `text-in-math` body is laid out once, by `read_inline`, before this
/// function ever sees it).
// UNWIRED. `layout_script` builds the same `(Vec<MathGlyph>, Length)` on the
// live path, so nothing calls this. Kept rather than deleted because
// `math_boxes_of_inline_boxes` below is documented as its sibling, and
// because it is the upstream-faithful flattening a `text-in-math` body needs
// if that path is ever wired back up.
#[allow(dead_code)]
fn math_glyphs_of_inline_boxes(boxes: &[HorzBox]) -> (Vec<MathGlyph>, Length) {
    fn go(pure: &PureHorzBox, out: &mut Vec<MathGlyph>, x: &mut Length) {
        match pure {
            PureHorzBox::InnerString {
                info,
                text,
                width,
                height,
                depth,
            } => {
                out.push(MathGlyph {
                    info: info.clone(),
                    text: text.clone(),
                    gid: None,
                    dx: *x,
                    dy: Length::ZERO,
                    width: *width,
                    height: *height,
                    depth: *depth,
                });
                *x += *width;
            }
            PureHorzBox::OuterEmpty { natural, .. } => *x += *natural,
            PureHorzBox::OuterFil => {}
            PureHorzBox::FixedEmpty { width } => *x += *width,
            PureHorzBox::Image { width, .. } => *x += *width,
            PureHorzBox::Discretionary { no_break, .. } => {
                for p in no_break {
                    go(p, out, x);
                }
            }
            PureHorzBox::Graphics { width, .. } => *x += *width,
            // An unresolved `inline-graphics-outer` marker has zero width
            // (fil semantics, see the variant's doc comment) and no glyph
            // representation this walk can extract — advance past it like
            // `Image`/`Tabular` (a resolved one is an ordinary `Graphics`,
            // handled by the arm above).
            PureHorzBox::GraphicsOuter { width, .. } => *x += *width,
            PureHorzBox::Math { width, glyphs, .. } => {
                for g in glyphs {
                    let mut g = g.clone();
                    g.dx = *x + g.dx;
                    out.push(g);
                }
                *x += *width;
            }
            PureHorzBox::HookPageBreak { .. } => {}
            PureHorzBox::Tabular(tab) => *x += tab.width,
            PureHorzBox::EmbeddedBlock { width, .. } => *x += *width,
            // A frame in a math context has no glyph representation this
            // walk can extract — advance past it like `Image`/`Tabular`.
            PureHorzBox::Frame { width, .. } => *x += *width,
            PureHorzBox::FrameMarker { .. } => {}
            // Zero-width bracket; its contents are spliced siblings, already
            // walked by this same loop.
            PureHorzBox::InlineFrameMarker { .. } => {}
            // Zero-width marker; no glyph representation. Same treatment
            // as `HookPageBreak`.
            PureHorzBox::Footnote { .. } => {}
            // inert reflow marker, no glyph representation — same
            // treatment as `HookPageBreak`/`FrameMarker`/`Footnote`
            // above.
            PureHorzBox::InlineMark(_) => {}
        }
    }
    let mut glyphs = Vec::new();
    let mut x = Length::ZERO;
    for HorzBox::Pure(p) in boxes {
        go(p, &mut glyphs, &mut x);
    }
    (glyphs, x)
}

/// `math_glyphs_of_inline_boxes`'s graphics-harvesting sibling — the
/// shape a `make_paren` closure's result needs, since a delimiter drawn via
/// `inline-graphics` (`math.satyh`'s `paren-left`/`abs-left`/…, `fill`/
/// `stroke` a path) carries its ink as a `PureHorzBox::Graphics` box, not a
/// `MathGlyph`. The same exhaustive `PureHorzBox` variant list as
/// `math_glyphs_of_inline_boxes` (do NOT modify that function — every OTHER
/// caller still wants glyphs-only, e.g. `EmbeddedText`), but additionally
/// harvests `Graphics::elems` (`dx`-shifted via `shift_graphics`, the box's
/// own local-origin convention — see `PureHorzBox::Graphics`'s doc comment)
/// and forwards BOTH the glyphs AND `rules` out of any nested
/// `PureHorzBox::Math` box (a paren closure could, in principle, embed one
/// via `text-in-math`/`embed-math`).
///
/// ONE arm diverges from that sibling and makes this walk VERTICAL too: `dy`
/// (y-up, box-local — `MathGlyph::dy`'s own frame) carries the offset of the
/// stacked line a nested `EmbeddedBlock`'s content sits on. `Frame` and
/// `Tabular` still contribute width alone; they could be descended into the
/// same way, but nothing in the corpus puts either inside a `text-in-math`
/// body, so neither has a measured shape to be faithful to.
fn math_boxes_of_inline_boxes(boxes: &[HorzBox]) -> (Vec<MathGlyph>, Vec<GraphicsElem>, Length) {
    fn go(
        pure: &PureHorzBox,
        out: &mut Vec<MathGlyph>,
        rules: &mut Vec<GraphicsElem>,
        x: &mut Length,
        dy: Length,
    ) {
        match pure {
            PureHorzBox::InnerString {
                info,
                text,
                width,
                height,
                depth,
            } => {
                out.push(MathGlyph {
                    info: info.clone(),
                    text: text.clone(),
                    gid: None,
                    dx: *x,
                    dy,
                    width: *width,
                    height: *height,
                    depth: *depth,
                });
                *x += *width;
            }
            PureHorzBox::OuterEmpty { natural, .. } => *x += *natural,
            PureHorzBox::OuterFil => {}
            PureHorzBox::FixedEmpty { width } => *x += *width,
            PureHorzBox::Image { width, .. } => *x += *width,
            PureHorzBox::Discretionary { no_break, .. } => {
                for p in no_break {
                    go(p, out, rules, x, dy);
                }
            }
            PureHorzBox::Graphics { width, elems, .. } => {
                for e in elems {
                    rules.push(shift_graphics((*x, dy), e));
                }
                *x += *width;
            }
            // See `math_glyphs_of_inline_boxes`'s matching arm.
            PureHorzBox::GraphicsOuter { width, .. } => *x += *width,
            PureHorzBox::Math {
                width,
                glyphs,
                rules: inner_rules,
                ..
            } => {
                for g in glyphs {
                    let mut g = g.clone();
                    g.dx = *x + g.dx;
                    g.dy += dy;
                    out.push(g);
                }
                for r in inner_rules {
                    rules.push(shift_graphics((*x, dy), r));
                }
                *x += *width;
            }
            PureHorzBox::HookPageBreak { .. } => {}
            PureHorzBox::Tabular(tab) => *x += tab.width,
            // A `line-stack-top`/`-bottom` (or `embed-block-top`/`-bottom`) box
            // handed BACK to math through `text-in-math` — azmath's
            // `\overbrace`/`\underbrace` (`parens.satyh:533`/`:561`) stack the
            // brace over the braced formula this way. Placed with
            // `place_embedded_block`'s (rustyfi-pdf) geometry but in this walk's
            // y-UP frame: `place_block_at` seats the stack at a page-y-DOWN
            // origin, the anchored line lands on the math baseline
            // (`anchor_last`: the LAST for `-bottom`, the FIRST for `-top` —
            // upstream's `adjust_to_last_line`/`adjust_to_first_line`), and
            // every other line is offset by the NEGATED difference of their
            // placed baselines. That is the same split `make_embedded_block`
            // measured the box's own height/depth from, so what
            // `layout_math_value` folds back up agrees with the box metrics the
            // rest of the pipeline already saw.
            PureHorzBox::EmbeddedBlock {
                width,
                block,
                anchor_last,
                ..
            } => {
                let placed = place_block_at((Length::ZERO, Length::ZERO), block.clone());
                let anchor = if *anchor_last {
                    placed.last()
                } else {
                    placed.first()
                };
                if let Some(anchor) = anchor {
                    let anchor_y = anchor.baseline_y;
                    for line in &placed {
                        let line_dy = dy - (line.baseline_y - anchor_y);
                        for (cdx, cbx) in &line.contents {
                            // Each stacked line has its own horizontal origin,
                            // and must not advance the OUTER run's pen — the
                            // block's own `width` accounts for that once below.
                            let mut cx = *x + line.x + *cdx;
                            go(cbx, out, rules, &mut cx, line_dy);
                        }
                    }
                }
                *x += *width;
            }
            // See `math_glyphs_of_inline_boxes`'s matching arm.
            PureHorzBox::Frame { width, .. } => *x += *width,
            PureHorzBox::FrameMarker { .. } => {}
            // See `math_glyphs_of_inline_boxes`'s matching arm.
            PureHorzBox::InlineFrameMarker { .. } => {}
            // See `math_glyphs_of_inline_boxes`'s matching arm.
            PureHorzBox::Footnote { .. } => {}
            // See `math_glyphs_of_inline_boxes`'s matching arm.
            PureHorzBox::InlineMark(_) => {}
        }
    }
    let mut glyphs = Vec::new();
    let mut rules = Vec::new();
    let mut x = Length::ZERO;
    for HorzBox::Pure(p) in boxes {
        go(p, &mut glyphs, &mut rules, &mut x, Length::ZERO);
    }
    (glyphs, rules, x)
}

// ============================================================================
// ---- context-setter + box-combinator prims `code.satyh`/`itemize.satyh`
// need. ------------------------------------------------------------------
// ============================================================================

/// The inverse of `as_color` (mirrors `evalUtil.ml:124`'s `get_color` the
/// other way) — `get-text-color`'s result, which `itemize.satyh` feeds
/// straight into `fill`, so the tag/payload shape must match `as_color`
/// exactly (see that primitive's doc comment).
fn make_color_value(c: Color) -> Value {
    match c {
        Color::Gray(g) => Value::Ctor("Gray".to_string(), Some(Box::new(Value::Float(g)))),
        Color::Rgb(r, g, b) => Value::Ctor(
            "RGB".to_string(),
            Some(Box::new(Value::Tuple(vec![
                Value::Float(r),
                Value::Float(g),
                Value::Float(b),
            ]))),
        ),
        Color::Cmyk(c, m, y, k) => Value::Ctor(
            "CMYK".to_string(),
            Some(Box::new(Value::Tuple(vec![
                Value::Float(c),
                Value::Float(m),
                Value::Float(y),
                Value::Float(k),
            ]))),
        ),
    }
}

/// `font` = `Value::Tuple([string, float, float])` in `(abbrev, size_ratio,
/// rising_ratio)` order (vminst.ml's `tFONT`) — `set-font`'s second argument.
fn as_font(v: Value) -> Result<(String, f64, f64), EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 3 => {
            let mut it = vs.into_iter();
            let abbrev = as_str(it.next().unwrap())?;
            let size_ratio = as_float(it.next().unwrap())?;
            let rising_ratio = as_float(it.next().unwrap())?;
            Ok((abbrev, size_ratio, rising_ratio))
        }
        other => eval_error(format!(
            "expected a font (string * float * float), got {}",
            other.type_name()
        )),
    }
}

/// [`as_font`]'s V0_1 twin — saphe-split's `tFONTWR = font * float * float`,
/// whose head is the opaque handle rather than an abbrev.
fn as_font_with_ratio(v: Value) -> Result<(FontKey, f64, f64), EvalError> {
    match v {
        Value::Tuple(vs) if vs.len() == 3 => {
            let mut it = vs.into_iter();
            let key = as_font_key(it.next().unwrap())?;
            let size_ratio = as_float(it.next().unwrap())?;
            let rising_ratio = as_float(it.next().unwrap())?;
            Ok((key, size_ratio, rising_ratio))
        }
        other => eval_error(format!(
            "expected a font (font * float * float), got {}",
            other.type_name()
        )),
    }
}

/// The opaque V0_1 `font` handle (upstream's `BCFontKey of FontKey.t`).
fn as_font_key(v: Value) -> Result<FontKey, EvalError> {
    match v {
        Value::Font(key) => Ok(key),
        other => eval_error(format!("expected a font, got {}", other.type_name())),
    }
}

/// `set-text-color : color -> context -> context` (vminst.ml:1603) —
/// FAITHFUL store (`Context::text_color`, the `set-font-size` shape); it
/// rides on every `HorzStringInfo` and both PDF writers emit `rg`/`g`
/// before `Tj` for a non-black run.
fn prim_set_text_color(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let color = as_color(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        text_color: color,
        ..ctx
    })))
}

/// `get-text-color : context -> color` (vminst.ml:1618) — FAITHFUL and
/// load-bearing: `itemize.satyh`'s `make-bullet` feeds this straight into
/// `fill color (Gr.circle …)`, so it must round-trip exactly what
/// `set-text-color` stored (see `make_color_value`'s doc comment).
fn prim_get_text_color(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    Ok(make_color_value(ctx.text_color))
}

/// `set-hyphen-penalty : int -> context -> context` (vminst.ml:1692) —
/// FAITHFUL store (`Context::hyphen_badness`), now a real consumer:
/// `text_to_boxes`'s `flush_word` uses this as each injected
/// `Discretionary`'s `penalty`, but only when a dictionary is installed via
/// `set-hyphenation-dictionary` — with no dictionary installed (the
/// default), this is stored but has no layout effect, same as before.
/// `code.satyh`'s `set-hyphen-penalty 100000` still works as "disable
/// hyphenation" (huge positive penalty, DP avoids it).
fn prim_set_hyphen_penalty(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let n = as_int(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        hyphen_badness: n,
        ..ctx
    })))
}

/// `set-hyphen-min : int -> int -> context -> context` (upstream
/// `vminstdef.yaml:1163-1177`) — writes
/// `Context::left_hyphen_min`/`right_hyphen_min`, each clamped to `>= 0`
/// (mirrors `set-space-ratio`'s `.max(0.0)` clamping style; a negative
/// minimum would be meaningless to the min-fragment filter in
/// `crate::hyphenation::hyphenate_word`).
fn prim_set_hyphen_min(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let right = as_int(args.pop().unwrap())?.max(0);
    let left = as_int(args.pop().unwrap())?.max(0);
    Ok(Value::Context(Box::new(Context {
        left_hyphen_min: left,
        right_hyphen_min: right,
        ..ctx
    })))
}

/// `set-space-ratio : float -> float -> float -> context -> context`
/// (vminst.ml:1309), params `(natural, shrink, stretch)` — FAITHFUL store
/// (`Context::space_natural`/`space_shrink`/`space_stretch`, clamped to
/// `>= 0.0` like upstream), read by `text_to_boxes`'s interword-glue
/// computation.
fn prim_set_space_ratio(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let stretch = as_float(args.pop().unwrap())?.max(0.0);
    let shrink = as_float(args.pop().unwrap())?.max(0.0);
    let natural = as_float(args.pop().unwrap())?.max(0.0);
    Ok(Value::Context(Box::new(Context {
        space_natural: natural,
        space_shrink: shrink,
        space_stretch: stretch,
        ..ctx
    })))
}

/// `set-space-ratio-between-scripts : float -> float -> float -> script ->
/// script -> context -> context` (`vminstdef.yaml:1230-1250`) — writes one
/// ordered script pair's entry of `ctx.script_space_map`
/// (`convertText.ml:34-50` reads it back).
///
/// Only the NATURAL ratio is stored. The other two arguments are accepted and
/// dropped, because upstream drops them too: `pure_space_between_scripts`
/// misplaces them into `LBAtom`'s height and depth slots, so no
/// `set-space-ratio-between-scripts` call in any document has ever been able
/// to give this glue stretch or shrink. See [`interscript_glue`].
///
/// This was a STAND-IN that ignored all three, on the reasoning that slydifi
/// only ever calls it with `0. 0. 0.` to SUPPRESS the spacing and the port
/// inserted none anyway. The port has inserted Latin↔CJK glue for some time
/// now, so ignoring the call left slydifi with a 0.24em space at every
/// Japanese/Latin junction that upstream does not set.
fn prim_set_space_ratio_between_scripts(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let script2 = as_script(args.pop().unwrap())?;
    let script1 = as_script(args.pop().unwrap())?;
    let _stretch = as_float(args.pop().unwrap())?;
    let _shrink = as_float(args.pop().unwrap())?;
    // `max 0.`, as `vminstdef.yaml`'s own `set_space_ratio_between_scripts`
    // clamps each ratio before storing it.
    let natural = as_float(args.pop().unwrap())?.max(0.0);
    let mut script_space_map = ctx.script_space_map;
    script_space_map[script1 as usize][script2 as usize] = natural;
    Ok(Value::Context(Box::new(Context {
        script_space_map,
        ..ctx
    })))
}

/// `split-into-lines : string -> (int * string) list` (vminst.ml:2269) —
/// FAITHFUL: splits on `'\n'` and, per line, counts the leading ASCII spaces
/// `i` and returns `(i, rest_after_indent)` — exactly `evalUtil.ml:36`'s
/// `chop_space_indent`. Pure string op: no context, no box, no new type.
fn prim_split_into_lines(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let s = as_str(args.pop().unwrap())?;
    let mut out = Vec::new();
    for line in s.split('\n') {
        let indent = line.chars().take_while(|c| *c == ' ').count();
        let rest: String = line.chars().skip(indent).collect();
        out.push(Value::Tuple(vec![
            Value::Int(indent as i64),
            Value::Str(rest),
        ]));
    }
    Ok(Value::List(out))
}

/// Shift every content box in `block`'s `Line`s right by `pad_l`
/// (`block-frame-breakable`'s left-indent, point 4) — the simplest of the
/// two options that section names: adjusting each box's own `x` offset
/// directly rather than prepending an extra `FixedEmpty` box (`Skip`s carry
/// no `x` offsets to shift, so they pass through unchanged).
fn indent_left(block: Vec<VertBox>, pad_l: Length) -> Vec<VertBox> {
    block
        .into_iter()
        .map(|vb| match vb {
            VertBox::Line {
                height,
                depth,
                leading,
                contents,
            } => VertBox::Line {
                height,
                depth,
                leading,
                contents: contents
                    .into_iter()
                    .map(|(x, bx)| (x + pad_l, bx))
                    .collect(),
            },
            // `Skip`/`ClearPage`/`HookPageBreak` carry no `x` offsets to shift.
            other => other,
        })
        .collect()
}

/// `block-frame-breakable : context -> paddings -> deco-set -> (context ->
/// block-boxes) -> block-boxes` (vminst.ml:1090) — the `inline-frame-outer`
/// playbook, one dimension up:
/// `paddingL`/`paddingR` shrink the inner `reducef` closure's context width,
/// and the result is indented and top/bottom-padded with plain `Skip`s,
/// bracketed by a `FrameStart(id)`/`FrameEnd(id)` marker pair — the frame's
/// pads/width/deco-set are interned into `interp.decos` under `id`
/// (`DecoEntry::Block`), and `fire_hooks`'s block-fragment pass fires
/// `decoS` once the frame's whole single-page fragment is placed (the first
/// cut: multi-page fragments/`decoH`/`decoM`/`decoT` are a documented
/// follow-up, see `fire_hooks`'s doc comment).
/// Drop the margin boxes at either END of a `block-frame-breakable`'s body —
/// the first inner block's top margin and the last inner block's bottom
/// margin, which upstream's `normalize` never produces for a frame's contents
/// (`pageBreak.ml:664` and `:582-585`; see the call site). Margins in the
/// MIDDLE of the body are untouched: those are real inter-block gaps, squashed
/// there exactly as they are outside a frame.
fn strip_outer_margins(body: &mut Vec<VertBox>) {
    let is_margin = |vb: &VertBox| matches!(vb, VertBox::Skip(_) | VertBox::ParagTop(_));
    if body.first().is_some_and(is_margin) {
        body.remove(0);
    }
    if body.last().is_some_and(is_margin) {
        body.pop();
    }
}

fn prim_block_frame_breakable(
    interp: &mut Interp,
    version: RustyfiVersion,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let k = args.pop().unwrap();
    let decoset = as_decoset(args.pop().unwrap())?;
    let (pad_l, pad_r, pad_t, pad_b) = as_paddings(args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    let id = DecoId(interp.decos.len());
    interp.decos.push(DecoEntry::Block {
        pads: Paddings {
            l: pad_l,
            r: pad_r,
            t: pad_t,
            b: pad_b,
        },
        width: ctx.paragraph_width,
        decoset,
        // See `make_inline_frame`'s identical capture.
        version,
    });
    let inner_ctx = Context {
        paragraph_width: ctx.paragraph_width - pad_l - pad_r,
        ..ctx
    };
    let inner = as_block_boxes(interp.apply(k, Value::Context(Box::new(inner_ctx)))?)?;
    let mut indented = indent_left(inner, pad_l);
    // THE FRAME CARRIES THE MARGINS, ITS BODY DOES NOT. Upstream normalizes a
    // frame's contents STANDALONE — `aux None TopMarginProhibited Alist.empty
    // vblstsub` (`pageBreak.ml:664`) — so the first inner block's `margin_top`
    // is never appended, and the last inner block's `margin_bottom` goes
    // through `squash_margins _ []`, whose empty-list arm (`:582-585`) emits
    // no skip at all. What surrounds the frame instead is the frame's OWN
    // `margins`, taken from the OUTER context (`vminstdef.yaml`'s
    // `BackendVertFrame`: `margin_top = ctx.paragraph_top`, `margin_bottom =
    // ctx.paragraph_bottom`), which `squash_margins` max-collapses against the
    // neighbouring blocks' margins exactly as `chop_page` collapses adjacent
    // `Skip`s.
    //
    // The distinction is not cosmetic: the body's `ParagTop` carries
    // `min_first_line_ascender` folded in (`prim_line_break`,
    // `lineBreak.ml:855-857`), and the frame's margin does NOT. Keeping the
    // body's made the advance INTO a frame a constant — `max(0, 9pt - hgt)`
    // cancels the first line's own height — where upstream's tracks the ink:
    // measured on `layout-tests/probes/code_line_height.saty` against real
    // SATySFi 0.0.11, `+code(`ooo`)` / `lll` / `ggg` advance 29.114 / 31.166 /
    // 29.138pt upstream and a flat 32.835pt here.
    strip_outer_margins(&mut indented);
    let mut out = Vec::with_capacity(indented.len() + 6);
    out.push(VertBox::Skip(ctx.paragraph_top));
    out.push(VertBox::FrameStart(id));
    out.push(VertBox::FramePad(pad_t));
    out.extend(indented);
    out.push(VertBox::FramePad(pad_b));
    out.push(VertBox::FrameEnd(id));
    out.push(VertBox::Skip(ctx.paragraph_bottom));
    Ok(Value::BlockBoxes(out))
}

/// Build the `PureHorzBox::EmbeddedBlock` shared by `embed-block-top`
/// (vminst.ml:1145) and `embed-block-bottom` (vminst.ml:1185). FAITHFUL:
/// `anchor_last` selects which of `block`'s lines lands on the surrounding
/// text baseline — the FIRST for top (upstream's `adjust_to_first_line`) or
/// the LAST for bottom (`adjust_to_last_line`) — computed by placing the
/// block once (`place_block_at`) to find where each line's baseline falls,
/// then splitting the box's total vertical extent around the anchored line:
/// around the first line for TOP, so the box hangs DOWN from the baseline;
/// around the last line for BOTTOM, so it hangs UP. A degenerate line-less
/// block (only skips, no baseline to anchor) falls back to
/// `measure_block`'s skip-as-height sum for both.
fn make_embedded_block(
    width: Length,
    block: Vec<VertBox>,
    anchor_last: bool,
    breakable: bool,
) -> Value {
    let first_line_height = block.iter().find_map(|vb| match vb {
        VertBox::Line { height, .. } => Some(*height),
        _ => None,
    });
    let last_line_depth = block.iter().rev().find_map(|vb| match vb {
        VertBox::Line { depth, .. } => Some(*depth),
        _ => None,
    });
    let (height, depth) = match (first_line_height, last_line_depth) {
        // Place once to learn each line's baseline, then split the box's
        // total vertical extent around the anchored line: `place_block_at`
        // seats the first baseline at `first_h` (origin 0), so the block
        // spans `[0, last_baseline + last_d]`.
        (Some(first_h), Some(last_d)) => {
            let placed = place_block_at((Length::ZERO, Length::ZERO), block.clone());
            let last_baseline = placed.last().map(|l| l.baseline_y).unwrap_or(first_h);
            let bottom_edge = last_baseline + last_d;
            if anchor_last {
                (last_baseline, last_d)
            } else {
                (first_h, bottom_edge - first_h)
            }
        }
        // A degenerate line-less block (only skips — no baseline to anchor):
        // keep `measure_block` (its skip-as-height fallback is right there).
        _ => measure_block(&block),
    };
    Value::InlineBoxes(vec![HorzBox::Pure(PureHorzBox::EmbeddedBlock {
        width,
        height,
        depth,
        block,
        anchor_last,
        breakable,
    })])
}

/// `embed-block-top : context -> length -> (context -> block-boxes) ->
/// inline-boxes` (vminst.ml:1145) — see [`make_embedded_block`].
fn prim_embed_block_top(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let k = args.pop().unwrap();
    let wid = as_length(args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    let inner_ctx = Context {
        paragraph_width: wid,
        ..ctx
    };
    let block = as_block_boxes(interp.apply(k, Value::Context(Box::new(inner_ctx)))?)?;
    Ok(make_embedded_block(wid, block, false, false))
}

/// `embed-block-bottom : context -> length -> (context -> block-boxes) ->
/// inline-boxes` (vminst.ml:1185) — see [`make_embedded_block`]; anchors the
/// LAST line, used by latexcmds' `\parbox?:(Bottom)`.
fn prim_embed_block_bottom(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let k = args.pop().unwrap();
    let wid = as_length(args.pop().unwrap())?;
    let ctx = as_context(args.pop().unwrap())?;
    let inner_ctx = Context {
        paragraph_width: wid,
        ..ctx
    };
    let block = as_block_boxes(interp.apply(k, Value::Context(Box::new(inner_ctx)))?)?;
    Ok(make_embedded_block(wid, block, true, false))
}

/// `line-stack-bottom : inline-boxes list -> inline-boxes` (vminst.ml:1229,
/// `evalUtil.ml`'s `make_line_stack`) — FAITHFUL: each `inline-boxes` in the
/// list becomes exactly one line, fit (not broken) to the widest line's
/// natural width via `fit_cell` (this port's `LineBreak.fit`, already used
/// by the tabular grid solver — same "no `Context`, `natural_metrics`
/// height/depth" fallback upstream's `make_line_stack` needs since it too
/// has no context to lean on). Lines are stacked with zero extra margin
/// (upstream's `VertParagraph`s all have `margin_top`/`margin_bottom =
/// None`): each line's `leading` is set to the previous line's depth plus
/// this line's height, so consecutive baselines sit exactly
/// `prev_depth + this_height` apart (see `pagebreak.rs`'s
/// `leading.max(height)` placement formula — this choice makes that `max`
/// always resolve to our computed `leading`). See `line_stack` for the
/// shared body and [`prim_line_stack_top`] for the other half.
fn prim_line_stack_bottom(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    line_stack(args.pop().unwrap(), true)
}

/// `line-stack-top : inline-boxes list -> inline-boxes`
/// (vminstdef.yaml:1109 `BackendLineStackTop`) — FAITHFUL: the same
/// `make_line_stack` construction as [`prim_line_stack_bottom`], differing
/// only in which stacked line's baseline becomes the result's — one shared
/// body and one flag rather than two copies that could drift.
///
/// `ruby` calls this to sit its annotation above the base run.
fn prim_line_stack_top(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    line_stack(args.pop().unwrap(), false)
}

/// `evalUtil.ml`'s `make_line_stack` — shared body of the two `line-stack-*`
/// prims; `anchor_last` picks upstream's `adjust_to_last_line` (`true`) or
/// `adjust_to_first_line` (`false`).
fn line_stack(arg: Value, anchor_last: bool) -> Result<Value, EvalError> {
    let hblstlst = as_list(arg)?
        .into_iter()
        .map(as_inline_boxes)
        .collect::<Result<Vec<_>, _>>()?;
    let wid = hblstlst
        .iter()
        .map(|hbs| natural_metrics(hbs).0)
        .fold(Length::ZERO, |acc, w| if w > acc { w } else { acc });
    let mut block = Vec::with_capacity(hblstlst.len());
    let mut prev_depth = Length::ZERO;
    for (idx, hbs) in hblstlst.into_iter().enumerate() {
        let (contents, height, depth) = fit_cell(hbs, wid);
        let leading = if idx == 0 {
            height + depth
        } else {
            prev_depth + height
        };
        block.push(VertBox::Line {
            height,
            depth,
            leading,
            contents,
        });
        prev_depth = depth;
    }
    // `anchor_last` IS upstream's `adjust_to_last_line`/`adjust_to_first_line`
    // choice: `line-stack-bottom` is BOTTOM-anchored (SATySFi vminst.ml:1229 —
    // the result baseline is the LAST stacked line's baseline), so the box's
    // height spans everything above that last line and its depth is the last
    // line's depth. Top-anchoring it instead put the baseline at the FIRST
    // line, which dropped the whole stack below the baseline — e.g. figbox's
    // `margin`/`hvmargin` (a `line-stack-bottom` of [top-mgn; content;
    // bot-mgn]) had its content rendered below its frame (the E=mc² bug). For
    // `line-stack-top` the first line IS the right anchor, which is the whole
    // difference between the two prims.
    Ok(make_embedded_block(wid, block, anchor_last, false))
}

/// `add-footnote : block-boxes -> inline-boxes` (vminst.ml:1130
/// `BackendAddFootnote`) — FAITHFUL: wraps the block in a zero-metric
/// `PureHorzBox::Footnote` marker (upstream `PHGFootnote`,
/// vminstdef.yaml:1034-1044; the upstream body's `PageBreak.solidify` is a
/// no-op here because this port's block-boxes are already solid
/// `Vec<VertBox>`). `chop_page` (rustyfi-backend) extracts the marker when
/// its line is committed to a page, reserves the stack's height at the
/// column bottom, and places the block bottom-aligned there — see that
/// function's doc comment. The cross-trial `changed`-flag protocol
/// `footnote-scheme.satyh` layers on top rides the crossref fixpoint.
fn prim_add_footnote(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let block = as_block_boxes(args.pop().unwrap())?;
    Ok(Value::InlineBoxes(vec![HorzBox::Pure(
        PureHorzBox::Footnote { block },
    )]))
}

/// `set-font : script -> string * float * float -> context -> context`
/// (0.0.6 `vminstdef.yaml:1335`, `tFONT` head) — real per-script wiring.
/// `abbrev` resolves through the font metrics
/// provider's registry first (`FontMetrics::resolve_font_abbrev` — a real
/// `TtfFontStore` built from `fonts.satysfi-hash`), falling back to
/// the 3-face name heuristic (`resolve_font_abbrev` free fn)
/// when the provider has no registry entry for it (an abbrev the config
/// doesn't name) — never an error, matching this
/// port's existing accept-and-degrade stance on unresolvable font names.
///
/// **Resolution rule (back-compat critical).** `Latin`-script text keeps
/// reading `Context::font` directly rather than `font_scheme[Latin]` (see
/// that field's doc comment) — `set-font Latin f` therefore writes BOTH so
/// the two stay in sync, but `set-font` on any OTHER script only touches
/// `font_scheme`, leaving `ctx.font` (and hence `set-font-key`/`\bold`/
/// `\emph`, which only ever read `ctx.font`) untouched.
fn prim_set_font_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let (abbrev, size_ratio, rising_ratio) = as_font(args.pop().unwrap())?;
    let script = as_script(args.pop().unwrap())?;
    let font = interp
        .metrics
        .resolve_font_abbrev(&abbrev)
        .unwrap_or_else(|| resolve_font_abbrev(&abbrev));
    install_script_font(&mut ctx, script, font, size_ratio, rising_ratio);
    Ok(Value::Context(Box::new(ctx)))
}

/// `set-font : script -> font * float * float -> context -> context`
/// (saphe-split `tools/gencode/vminst.ml:1433`, `tFONTWR` head). Identical
/// to [`prim_set_font_v006`] except that the triple's head is ALREADY a
/// resolved handle — 0.1 has no abbrev at this point and nothing to resolve;
/// `load-single-font` did that when the font envelope's member was minted.
fn prim_set_font_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let (font, size_ratio, rising_ratio) = as_font_with_ratio(args.pop().unwrap())?;
    let script = as_script(args.pop().unwrap())?;
    install_script_font(&mut ctx, script, font, size_ratio, rising_ratio);
    Ok(Value::Context(Box::new(ctx)))
}

/// `get-font : script -> context -> string * float * float`
/// (vminstdef.yaml:1350 `PrimitiveGetFont`) — FAITHFUL: `script_font` IS
/// upstream's `get_font_with_ratio` (normalize the script, then read the
/// scheme slot), and the triple is `evalUtil.ml:196`'s `make_font_value`.
///
/// The head is a font ABBREV. Upstream's `font_scheme` stores abbrevs and
/// resolves them to files only at render time; this port resolves eagerly in
/// [`prim_set_font_v006`] and stores a `FontKey`, so the name comes back from
/// the store that minted it (`FontMetrics::font_abbrev`) and is `""` when the
/// key was never named by a registry — see that method for exactly when, and
/// why the corpus does not care (every caller in it, and upstream's own
/// `convertText.ml:78`, writes `let (_, ratio, _) =` and uses the RATIO,
/// which is exact).
///
/// This is what `ruby` and `quotation` need: the CJK face's size ratio, so a
/// ruby annotation or a two-em Japanese indent scales with the face rather
/// than with the Latin `get-font-size`.
fn prim_get_font_v006(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let script = as_script(args.pop().unwrap())?;
    let sf = script_font(&ctx, script);
    let abbrev = interp.metrics.font_abbrev(sf.font).unwrap_or_default();
    Ok(Value::Tuple(vec![
        Value::Str(abbrev),
        Value::Float(sf.ratio),
        Value::Float(sf.rising),
    ]))
}

/// `get-font : script -> context -> font * float * float` — the 0.1 arm,
/// mirroring [`prim_set_font_v006`]/[`prim_set_font_v01`]'s split. 0.1's
/// `font` IS the opaque handle this port already stores, so unlike the 0.0.6
/// arm there is nothing to recover: the value round-trips exactly.
fn prim_get_font_v01(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let script = as_script(args.pop().unwrap())?;
    let sf = script_font(&ctx, script);
    Ok(Value::Tuple(vec![
        Value::Font(sf.font),
        Value::Float(sf.ratio),
        Value::Float(sf.rising),
    ]))
}

/// The half of `set-font` that is NOT version-forked — the `Context` write
/// both arms end at, kept in one place so the 0.0.6 behaviour cannot drift
/// when the 0.1 one changes. See `prim_set_font_v006`'s "Resolution rule".
fn install_script_font(ctx: &mut Context, script: Script, font: FontKey, ratio: f64, rising: f64) {
    ctx.font_scheme[script as usize] = ScriptFont {
        font,
        ratio,
        rising,
    };
    if script == Script::Latin {
        ctx.font = font;
    }
}

/// `set-code-text-command : [string] inline-cmd -> context -> context`
/// (`stdja:116`; no vminst.ml entry to cite). STAND-IN, same
/// shape as `set-math-command`/`set-math-font` above: `(command \cmd)`
/// means a real program CAN build a `[string]
/// inline-cmd` value to pass here — but `Context` (`rustyfi-backend`) still
/// cannot hold an arbitrary lang-side `Value` without a reverse crate
/// dependency, and the one seam this codebase uses for that indirection
/// (`Interp::hooks`'s ID-table, `eval.rs`) sits outside this file's
/// boundary — so the command argument is accepted (to keep the
/// arity/signature faithful) and dropped.
fn prim_set_code_text_command(
    interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let mut ctx = as_context(args.pop().unwrap())?;
    let cmd = args.pop().unwrap();
    ctx.code_text_command = Some(interp.register_math_command(cmd));
    Ok(Value::Context(Box::new(ctx)))
}

/// `get-natural-length : block-boxes -> length` (vminst.ml:2040) —
/// FAITHFUL: `get-natural-width`'s block sibling (`get-natural-width` itself
/// is a `pervasives.satyh` wrapper over `get-natural-metrics`, not a
/// primitive). A block's own "natural length" is its total vertical extent
/// — `measure_block`'s two components (height above the nominal top, depth
/// of the last line) summed into one length.
fn prim_get_natural_length(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let bb = as_block_boxes(args.pop().unwrap())?;
    let (height, depth) = measure_block(&bb);
    Ok(Value::Length(height + depth))
}

/// `set-dominant-wide-script : script -> context -> context`
/// (vminst.ml:1511 `PrimitiveSetDominantWideScript`) — FAITHFUL store,
/// consumed by `get-dominant-wide-script` now, by CJK script normalization
/// later.
fn prim_set_dominant_wide_script(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let dominant_wide_script = as_script(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        dominant_wide_script,
        ..ctx
    })))
}

/// `set-dominant-narrow-script : script -> context -> context`
/// (vminst.ml:1539) — FAITHFUL store, mirror of the wide setter.
fn prim_set_dominant_narrow_script(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let dominant_narrow_script = as_script(args.pop().unwrap())?;
    Ok(Value::Context(Box::new(Context {
        dominant_narrow_script,
        ..ctx
    })))
}

/// `set-language : script -> language -> context -> context`
/// (vminst.ml:1568 `PrimitiveSetLangSys`) — FAITHFUL per-script map insert
/// (`langsys_scheme |> ScriptSchemeMap.add script langsys` upstream; a
/// 4-slot array write here).
fn prim_set_language(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let langsys = as_language(args.pop().unwrap())?;
    let script = as_script(args.pop().unwrap())?;
    let mut langsys_scheme = ctx.langsys_scheme;
    langsys_scheme[script as usize] = langsys;
    Ok(Value::Context(Box::new(Context {
        langsys_scheme,
        ..ctx
    })))
}

/// `get-dominant-wide-script : context -> script` (vminst.ml:1526) — FAITHFUL.
fn prim_get_dominant_wide_script(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    Ok(make_script_value(ctx.dominant_wide_script))
}

/// `get-dominant-narrow-script : context -> script` (vminst.ml:1555) — FAITHFUL.
fn prim_get_dominant_narrow_script(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    Ok(make_script_value(ctx.dominant_narrow_script))
}

/// `get-language : script -> context -> language` (vminst.ml:1587
/// `PrimitiveGetLangSys`) — FAITHFUL. Upstream routes through
/// `get_language_system`, whose `normalize_script` step is the identity on
/// every script a VALUE can carry (only the char-decoder-internal
/// CommonNarrow/CommonWide/Inherited normalize, horzBox.ml:470-479), so
/// this is a plain indexed read; absent-entry default `NoLanguageSystem`
/// is baked into the array's initial value.
fn prim_get_language(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let script = as_script(args.pop().unwrap())?;
    Ok(make_language_value(ctx.langsys_scheme[script as usize]))
}

/// `set-every-word-break : inline-boxes -> inline-boxes -> context -> context`
/// (vminst.ml:3007 `PrimitiveSetEveryWordBreak`) — sets the inline-boxes
/// inserted before/after every inter-word break (mdja.satyh uses it for a
/// CJK word-break strut). STAND-IN: accepted and dropped (no per-context
/// every-word-break state yet), same pattern as `prim_set_language` above.
fn prim_set_every_word_break(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let ctx = as_context(args.pop().unwrap())?;
    let _after = args.pop().unwrap();
    let _before = args.pop().unwrap();
    Ok(Value::Context(Box::new(ctx)))
}

/// `register-outline : (int * string * string * bool) list -> unit`
/// (vminstdef.yaml:2794 `BackendRegisterOutline`) — FAITHFUL: upstream
/// REPLACES the whole registered list (`outline.ml`: `registered_outline :=
/// ol`), it does not append; and it is callable anywhere (no
/// during-page-break gate — upstream's `Outline.register` has no `State`
/// check). Keys resolve through [`Interp::dest_name`] (upstream
/// `make_entry`'s `NamedDest.get key`).
fn prim_register_outline(interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let entries = as_list(args.pop().unwrap())?;
    let mut out = Vec::with_capacity(entries.len());
    for e in entries {
        let Value::Tuple(vs) = e else {
            return eval_error("register-outline expects a list of (int * string * string * bool)");
        };
        if vs.len() != 4 {
            return eval_error("register-outline expects 4-tuples (level, text, key, is-open)");
        }
        let mut it = vs.into_iter();
        let level = as_int(it.next().unwrap())?;
        let text = as_str(it.next().unwrap())?;
        let key = as_str(it.next().unwrap())?;
        let is_open = as_bool(it.next().unwrap())?;
        let dest_name = interp.dest_name(&key);
        out.push(OutlineEntry {
            level,
            text,
            dest_name,
            is_open,
        });
    }
    interp.outline = out; // replace, not extend
    Ok(Value::Unit)
}

/// Recursive `extract_one` helper for [`prim_extract_string`] — mirrors
/// `horzBox.ml`'s `extract_string`'s `extract_one`: an `InnerString`
/// contributes its own text, a `Discretionary` recurses into `no_break`
/// (the "not yet broken" reading), every other box contributes nothing.
/// This port's box vocabulary has no separate Rising/Frame/ScriptGuard
/// wrapper (`inline-frame-breakable` et al. already flatten their padding
/// into the same flat `Vec<HorzBox>` — see `prim_inline_frame_breakable`),
/// so there is nothing else to recurse into.
fn extract_string_pure_one(phb: &PureHorzBox) -> String {
    match phb {
        PureHorzBox::InnerString { text, .. } => text.clone(),
        PureHorzBox::Discretionary { no_break, .. } => {
            no_break.iter().map(extract_string_pure_one).collect()
        }
        // Upstream `extract_string` recurses into frames.
        PureHorzBox::Frame { contents, .. } => contents
            .iter()
            .map(|(_, b)| extract_string_pure_one(b))
            .collect(),
        _ => String::new(),
    }
}

fn extract_string_one(hb: &HorzBox) -> String {
    match hb {
        HorzBox::Pure(phb) => extract_string_pure_one(phb),
    }
}

/// `extract-string : inline-boxes -> string` (vminstdef.yaml:1565
/// `PrimitiveExtract`) — FAITHFUL (see [`extract_string_one`]).
fn prim_extract_string(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let boxes = as_inline_boxes(args.pop().unwrap())?;
    let s: String = boxes.iter().map(extract_string_one).collect();
    Ok(Value::Str(s))
}

/// `get-initial-text-info : unit -> text-info` (v0.0.6 vminst.ml:953
/// `TextGetInitialTextModeContext`) — FAITHFUL:
/// `TextBackend.get_initial_text_mode_context` is `{ indent = 0;
/// escape_list = [] }` (textBackend.ml:9-12); escape_list is omitted from
/// the port's `TextInfo` (see its doc comment). The v0.0.6 fork side.
fn prim_get_initial_text_info_v006(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let _unit = args.pop().unwrap();
    Ok(Value::TextInfo(TextInfo { indent: 0 }))
}

/// `get-initial-text-info : inline [math-text] -> (string -> option string
/// -> option string -> string) -> text-info` (dev-0-1-0 vminst.ml:904-925)
/// — the v0.1 fork side. STAND-IN: pops and
/// drops both new arguments (the text-mode default math command and the
/// math-scripts stringifier) — this port's `TextInfo` carries no text-mode
/// command state, same degenerate policy as `stringify-math`. Returns the
/// same `TextInfo{indent: 0}` as the v0.0.6 side.
fn prim_get_initial_text_info_v01(
    _interp: &mut Interp,
    mut args: Vec<Value>,
) -> Result<Value, EvalError> {
    let _stringifier = args.pop().unwrap();
    let _default_math_cmd = args.pop().unwrap();
    Ok(Value::TextInfo(TextInfo { indent: 0 }))
}

/// `deepen-indent : int -> text-info -> text-info` (vminst.ml:921
/// `TextDeepenIndent`) — FAITHFUL: `indent + max i 0`
/// (`TextBackend.deepen_indent`, textBackend.ml:15-16 — the INCREMENT is
/// clamped, not the total).
fn prim_deepen_indent(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let tinfo = as_text_info(args.pop().unwrap())?;
    let i = as_int(args.pop().unwrap())?;
    Ok(Value::TextInfo(TextInfo {
        indent: tinfo.indent + i.max(0),
    }))
}

/// `break : text-info -> string` (vminst.ml:935 `TextBreak`) — FAITHFUL:
/// `"\n" ^ String.make indent ' '` (`TextBackend.get_indent`).
fn prim_break(_interp: &mut Interp, mut args: Vec<Value>) -> Result<Value, EvalError> {
    let tinfo = as_text_info(args.pop().unwrap())?;
    let mut s = String::with_capacity(1 + tinfo.indent as usize);
    s.push('\n');
    for _ in 0..tinfo.indent {
        s.push(' ');
    }
    Ok(Value::Str(s))
}

// ============================================================================
// unit tests: `as_page` (every paper-size ctor),
// `read_content_scheme`/`read_parts_scheme` (field extraction +
// missing-field errors). These extractors are private, so the tests live
// in-module rather than in `tests/`, same pattern as `crossref.rs`'s own
// `#[cfg(test)] mod tests`.
// ============================================================================
#[cfg(test)]
mod page_model_tests {
    use super::*;

    #[test]
    fn as_page_maps_every_nullary_ctor_to_the_right_paper_size() {
        let cases: &[(&str, PaperSize)] = &[
            ("A0Paper", PaperSize::A0),
            ("A1Paper", PaperSize::A1),
            ("A2Paper", PaperSize::A2),
            ("A3Paper", PaperSize::A3),
            ("A4Paper", PaperSize::A4),
            ("A5Paper", PaperSize::A5),
            ("USLetter", PaperSize::USLetter),
            ("USLegal", PaperSize::USLegal),
        ];
        for (name, expected) in cases {
            let v = Value::Ctor((*name).to_string(), None);
            assert_eq!(as_page(v).unwrap(), *expected, "ctor {name}");
        }
    }

    #[test]
    fn as_page_unwraps_user_defined_papers_tuple_payload() {
        let v = Value::Ctor(
            "UserDefinedPaper".to_string(),
            Some(Box::new(Value::Tuple(vec![
                Value::Length(Length::pt(100.0)),
                Value::Length(Length::pt(200.0)),
            ]))),
        );
        assert_eq!(
            as_page(v).unwrap(),
            PaperSize::UserDefined(Length::pt(100.0), Length::pt(200.0))
        );
    }

    #[test]
    fn a4_paper_dims_are_595_by_842_points() {
        let (w, h) = PaperSize::A4.dims();
        assert!((w.0 - 595.0).abs() < 1.0, "width: {}", w.0);
        assert!((h.0 - 842.0).abs() < 1.0, "height: {}", h.0);
    }

    #[test]
    fn read_content_scheme_extracts_origin_and_height() {
        let mut fields = BTreeMap::new();
        fields.insert(
            "text-origin".to_string(),
            Value::Tuple(vec![
                Value::Length(Length::pt(10.0)),
                Value::Length(Length::pt(20.0)),
            ]),
        );
        fields.insert("text-height".to_string(), Value::Length(Length::pt(300.0)));
        let (origin, height) = read_content_scheme(Value::Record(fields)).unwrap();
        assert_eq!(origin, (Length::pt(10.0), Length::pt(20.0)));
        assert_eq!(height, Length::pt(300.0));
    }

    #[test]
    fn read_content_scheme_errors_on_a_missing_field() {
        let mut fields = BTreeMap::new();
        fields.insert(
            "text-origin".to_string(),
            Value::Tuple(vec![
                Value::Length(Length::ZERO),
                Value::Length(Length::ZERO),
            ]),
        );
        let err = read_content_scheme(Value::Record(fields)).unwrap_err();
        assert!(
            err.msg.contains("text-height"),
            "error should name the missing field: {}",
            err.msg
        );
    }

    #[test]
    fn read_parts_scheme_extracts_all_four_fields() {
        let mut fields = BTreeMap::new();
        fields.insert(
            "header-origin".to_string(),
            Value::Tuple(vec![
                Value::Length(Length::ZERO),
                Value::Length(Length::ZERO),
            ]),
        );
        fields.insert("header-content".to_string(), Value::BlockBoxes(Vec::new()));
        fields.insert(
            "footer-origin".to_string(),
            Value::Tuple(vec![
                Value::Length(Length::pt(1.0)),
                Value::Length(Length::pt(2.0)),
            ]),
        );
        fields.insert("footer-content".to_string(), Value::BlockBoxes(Vec::new()));
        let (horg, hbb, forg, fbb) = read_parts_scheme(Value::Record(fields)).unwrap();
        assert_eq!(horg, (Length::ZERO, Length::ZERO));
        assert!(hbb.is_empty());
        assert_eq!(forg, (Length::pt(1.0), Length::pt(2.0)));
        assert!(fbb.is_empty());
    }

    #[test]
    fn read_parts_scheme_errors_on_a_missing_field() {
        let err = read_parts_scheme(Value::Record(BTreeMap::new())).unwrap_err();
        assert!(
            err.msg.contains("header-origin"),
            "error should name the missing field: {}",
            err.msg
        );
    }
}

/// `enter_script_scales_and_saturates`:
/// `enter_script` is crate-private, so this lives here rather than in the
/// external `tests/v01_math.rs` integration suite, which can only reach
/// `pub` items.
#[cfg(test)]
mod math_split_tests {
    use super::*;
    use rustyfi_backend::FontMetrics;

    /// A `FontMetrics` stub with NO MATH table (`math_constants` defaults
    /// to `None`) — exercises `enter_script`'s documented fallback
    /// constants (`0.7`, `5.0/7.0`), the shape every other base-14 fixture
    /// in this crate already relies on.
    struct NoMath;
    impl FontMetrics for NoMath {
        fn advance(&self, _f: FontKey, c: char, size: Length) -> Option<Length> {
            if c.is_ascii() {
                Some(size * 0.5)
            } else {
                None
            }
        }
        fn ascender(&self, _f: FontKey, size: Length) -> Length {
            size * 0.75
        }
        fn descender(&self, _f: FontKey, size: Length) -> Length {
            size * 0.25
        }
    }

    #[test]
    fn enter_script_scales_and_saturates() {
        let metrics = NoMath;
        let interp = Interp::new(&metrics);
        let ctx = Context::initial(Length::pt(400.0));
        assert_eq!(ctx.math_script_level, MathScriptLevel::Base);
        assert_eq!(ctx.font_size, Length::pt(12.0));

        // Base -> Script: font_size * script_scale_down (fallback 0.7).
        let s1 = enter_script(&interp, &ctx);
        assert_eq!(s1.math_script_level, MathScriptLevel::Script);
        assert!(
            (s1.font_size.0 - ctx.font_size.0 * 0.7).abs() < 1e-9,
            "expected {} * 0.7, got {}",
            ctx.font_size.0,
            s1.font_size.0
        );

        // Script -> ScriptScript: font_size * (script_script_scale_down /
        // script_scale_down) (fallback 5.0/7.0).
        let s2 = enter_script(&interp, &s1);
        assert_eq!(s2.math_script_level, MathScriptLevel::ScriptScript);
        assert!(
            (s2.font_size.0 - s1.font_size.0 * (5.0 / 7.0)).abs() < 1e-9,
            "expected {} * 5/7, got {}",
            s1.font_size.0,
            s2.font_size.0
        );

        // ScriptScript saturates: no further shrink, level stays put.
        let s3 = enter_script(&interp, &s2);
        assert_eq!(s3.math_script_level, MathScriptLevel::ScriptScript);
        assert_eq!(s3.font_size, s2.font_size);
    }
}