phplang 0.2.17

PHP as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PhpHost heap — the first compiled standalone PHP runtime
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
//! Te phplang builtins: the `CallBuiltin` handlers the compiler emits, the
//! strict numeric hook, and the PHP standard-library functions reached through
//! `CALL`.
//!
//! Every handler has the fusevm signature `fn(&mut VM, u8) -> Value` and leaves
//! exactly one value on the stack. Operations that can fail (division by zero, an
//! undefined function) record the message on the host and halt the current chunk
//! by setting `vm.ip` past the end; `host::run_chunk_on` then surfaces it as an
//! `Err`.

use crate::host::{self, ops, with_host, PropAccess};
use crate::stdlib::common::bytes_arg;
use fusevm::{NumOp, NumericCall, Value, VM};

/// Register `$f` for `$op`, wrapped so a diagnostic a user error handler takes
/// is handed to it at this boundary: before the handler (one the numeric hook
/// raised, which runs no builtin) and after it (one it raised itself). A
/// handler that throws halts the chunk, as a throwing builtin does.
macro_rules! reg {
    ($vm:expr, $op:expr, $f:path) => {{
        fn wrapped(vm: &mut VM, argc: u8) -> Value {
            if host::drain_error_handlers() {
                vm.ip = vm.chunk.ops.len();
                return Value::Undef;
            }
            let v = $f(vm, argc);
            // A write that filled a `chunk_size` runs its output handler here.
            if crate::stdlib::output::drain_chunks() {
                vm.ip = vm.chunk.ops.len();
            }
            if host::drain_error_handlers() {
                vm.ip = vm.chunk.ops.len();
            }
            v
        }
        $vm.register_builtin($op, wrapped);
    }};
}

/// Register every compiler-emitted builtin on a fresh VM.
pub fn install(vm: &mut VM) {
    reg!(vm, ops::ECHO, b_echo);
    reg!(vm, ops::INCLUDE, b_include);
    reg!(vm, ops::EVAL, b_eval);
    reg!(vm, ops::GETVAR, b_getvar);
    reg!(vm, ops::GETSLOT, b_getslot);
    reg!(vm, ops::INCDEC_SLOT, b_incdec_slot);
    reg!(vm, ops::GETSLOT_Q, b_getslot_q);
    reg!(vm, ops::SETSLOT, b_setslot);
    reg!(vm, ops::SETVAR, b_setvar);
    reg!(vm, ops::COPY, b_copy);
    reg!(vm, ops::CONCAT, b_concat);
    reg!(vm, ops::CONCAT_ASSIGN_FSLOT, b_concat_assign_fslot);
    reg!(vm, ops::CONCAT_ASSIGN_SLOT, b_concat_assign_slot);
    reg!(vm, ops::CONCAT_ASSIGN_VAR, b_concat_assign_var);
    reg!(vm, ops::FOREACH_KEYS, b_foreach_keys);
    reg!(vm, ops::IS_PLAIN_OBJECT, b_is_plain_object);
    reg!(vm, ops::PROP_DIM_WRITEBACK, b_prop_dim_writeback);
    reg!(vm, ops::SPROP_DIM_WRITEBACK, b_sprop_dim_writeback);
    reg!(vm, ops::TRUTHY, b_truthy);
    reg!(vm, ops::CALL, b_call);
    reg!(vm, ops::MINMAX_FLF2, b_minmax_flf2);
    reg!(vm, ops::BYREF_ARG_DIAG, b_byref_arg_diag);
    reg!(vm, ops::GLOBAL_BIND, b_global_bind);
    reg!(vm, ops::INCDEC_STEP, b_incdec_step);
    reg!(vm, ops::MATCH_ERROR_MSG, b_match_error_msg);
    reg!(vm, ops::CALL_SPREAD, b_call_spread);
    reg!(vm, ops::MKARRAY, b_mkarray);
    reg!(vm, ops::MKARRAY_ADD, b_mkarray_add);
    reg!(vm, ops::INDEX_GET, b_index_get);
    reg!(vm, ops::INDEX_SET, b_index_set);
    reg!(vm, ops::ARR_APPEND, b_arr_append);
    reg!(vm, ops::SET_PATH, b_set_path);
    reg!(vm, ops::APPEND_PATH, b_append_path);
    reg!(vm, ops::GET_PATH, b_get_path);
    reg!(vm, ops::INCDEC_PATH, b_incdec_path);
    reg!(vm, ops::PATH_APPEND_CHILD, b_path_append_child);
    reg!(vm, ops::DIV, b_div);
    reg!(vm, ops::MOD, b_mod);
    reg!(vm, ops::POW, b_pow);
    reg!(vm, ops::LOOSE_EQ, b_loose_eq);
    reg!(vm, ops::LOOSE_NE, b_loose_ne);
    reg!(vm, ops::STRICT_EQ, b_strict_eq);
    reg!(vm, ops::STRICT_NE, b_strict_ne);
    reg!(vm, ops::LT, b_lt);
    reg!(vm, ops::GT, b_gt);
    reg!(vm, ops::LE, b_le);
    reg!(vm, ops::GE, b_ge);
    reg!(vm, ops::SIG_RETURN, b_sig_return);
    reg!(vm, ops::INCDEC, b_incdec);
    reg!(vm, ops::ARRAYKEYS, b_arraykeys);
    reg!(vm, ops::ARRAYLEN, b_arraylen);
    reg!(vm, ops::BITAND, b_bitand);
    reg!(vm, ops::BITOR, b_bitor);
    reg!(vm, ops::BITXOR, b_bitxor);
    reg!(vm, ops::SHL, b_shl);
    reg!(vm, ops::SHR, b_shr);
    reg!(vm, ops::BITNOT, b_bitnot);
    reg!(vm, ops::SPACESHIP, b_spaceship);
    reg!(vm, ops::DBG_LINE, b_dbg_line);
    reg!(vm, ops::ARR_MUT, b_arr_mut);
    reg!(vm, ops::MKCLOSURE, b_mkclosure);
    reg!(vm, ops::CALL_VALUE, b_call_value);
    reg!(vm, ops::NEW, b_new);
    reg!(vm, ops::PROP_GET, b_prop_get);
    reg!(vm, ops::PROP_SET, b_prop_set);
    reg!(vm, ops::PROP_ENSURE_ARRAY, b_prop_ensure_array);
    reg!(vm, ops::PROP_TOUCH, b_prop_touch);
    reg!(vm, ops::PROP_SET_RW, b_prop_set_rw);
    reg!(vm, ops::PROP_UNSET, b_prop_unset);
    reg!(vm, ops::PROP_ISSET, b_prop_isset);
    reg!(vm, ops::INDEX_ISSET, b_index_isset);
    reg!(vm, ops::DECL_FATAL, b_decl_fatal);
    reg!(vm, ops::DECLARE_FN, b_declare_fn);
    reg!(vm, ops::DECLARE_CLASS, b_declare_class);
    reg!(vm, ops::FINAL_CHECK, b_final_check);
    reg!(vm, ops::DYN_CLASS, b_dyn_class);
    reg!(vm, ops::DYN_CLASS_CONST, b_dyn_class_const);
    reg!(vm, ops::CLONE, b_clone);
    reg!(vm, ops::CLONE_WITH, b_clone_with);
    reg!(vm, ops::GLOBALS_ARRAY, b_globals_array);
    reg!(vm, ops::GLOBALS_GET, b_globals_get);
    reg!(vm, ops::GLOBALS_GET_Q, b_globals_get_q);
    reg!(vm, ops::GLOBALS_BIND, b_globals_bind);
    reg!(vm, ops::GLOBALS_UNSET, b_globals_unset);
    reg!(vm, ops::GLOBALS_ISSET, b_globals_isset);
    reg!(vm, ops::NS_FN_NAME, b_ns_fn_name);
    reg!(vm, ops::CONST_FETCH_NS, b_const_fetch_ns);
    reg!(vm, ops::CLASS_LINK_CHECK, b_class_link_check);
    reg!(vm, ops::REF_SLOT_SPROP, b_ref_slot_sprop);
    reg!(vm, ops::REF_TO_SPROP, b_ref_to_sprop);
    reg!(vm, ops::STATIC_HAS, b_static_has);
    reg!(vm, ops::CONST_DECL, b_const_decl);
    reg!(vm, ops::PROP_GET_EMPTY, b_prop_get_empty);
    reg!(vm, ops::PROP_INCDEC, b_prop_incdec);
    reg!(vm, ops::SUPPRESS_PUSH, b_suppress_push);
    reg!(vm, ops::SUPPRESS_POP, b_suppress_pop);
    reg!(vm, ops::MCALL, b_mcall);
    reg!(vm, ops::MCALL_RECV_CHECK, b_mcall_recv_check);
    reg!(vm, ops::CALL_NAME_CHECK, b_call_name_check);
    reg!(vm, ops::CALL_CLASS_CHECK, b_call_class_check);
    reg!(vm, ops::CALLVALUE_CHECK, b_callvalue_check);
    reg!(vm, ops::SCALL_CALLEE_CHECK, b_scall_callee_check);
    reg!(vm, ops::FCC_CHECK, b_fcc_check);
    reg!(vm, ops::SCALL, b_scall);
    reg!(vm, ops::SCONST, b_sconst);
    reg!(vm, ops::THROW, b_throw);
    reg!(vm, ops::RUN_TRY, b_run_try);
    reg!(vm, ops::SIG_HALT, b_sig_halt);
    reg!(vm, ops::SIG_BREAK, b_sig_break);
    reg!(vm, ops::SIG_CONTINUE, b_sig_continue);
    reg!(vm, ops::SIG_LEVEL, b_sig_level);
    reg!(vm, ops::CONST_FETCH, b_const_fetch);
    reg!(vm, ops::MAGIC_FILE, b_magic_file);
    reg!(vm, ops::MAGIC_DIR, b_magic_dir);
    reg!(vm, ops::MAGIC_CLASS, b_magic_class);
    reg!(vm, ops::SELF_CLASS, b_self_class);
    reg!(vm, ops::PARENT_CLASS, b_parent_class);
    reg!(vm, ops::UNSET_VAR, b_unset_var);
    reg!(vm, ops::UNSET_PATH, b_unset_path);
    reg!(vm, ops::FOREACH_PREP, b_foreach_prep);
    reg!(vm, ops::INSTANCEOF, b_instanceof);
    reg!(vm, ops::REF_BIND, b_ref_bind);
    reg!(vm, ops::REF_CELL, b_ref_cell);
    reg!(vm, ops::REF_SLOT_VAR, b_ref_slot_var);
    reg!(vm, ops::REF_SLOT_ELEM, b_ref_slot_elem);
    reg!(vm, ops::REF_SLOT_PROP, b_ref_slot_prop);
    reg!(vm, ops::REF_TO_VAR, b_ref_to_var);
    reg!(vm, ops::REF_TO_ELEM, b_ref_to_elem);
    reg!(vm, ops::REF_TO_APPEND, b_ref_to_append);
    reg!(vm, ops::REF_TO_PROP, b_ref_to_prop);
    reg!(vm, ops::GETVAR_Q, b_getvar_q);
    reg!(vm, ops::INDEX_GET_Q, b_index_get_q);
    reg!(vm, ops::INDEX_GET_EMPTY, b_index_get_empty);
    reg!(vm, ops::LIST_ELEM_GET, b_list_elem_get);
    reg!(vm, ops::PROP_GET_Q, b_prop_get_q);
    reg!(vm, ops::LSB_CLASS, b_lsb_class);
    reg!(vm, ops::LSB_FORWARD, b_lsb_forward);
    reg!(vm, ops::RET_REF, b_ret_ref);
    reg!(vm, ops::REF_SLOT_RET, b_ref_slot_ret);
    reg!(vm, ops::BYREF_OUT, b_byref_out);
    reg!(vm, ops::BYREF_LIVE, b_byref_live);
    reg!(vm, ops::SPROP_GET, b_sprop_get);
    reg!(vm, ops::SPROP_SET, b_sprop_set);
    reg!(vm, ops::SPROP_INCDEC, b_sprop_incdec);
    reg!(vm, ops::SPROP_GET_Q, b_sprop_get_q);
    reg!(vm, ops::STATIC_BIND, b_static_bind);
    reg!(vm, ops::CALL_NAMED, b_call_named);
    reg!(vm, ops::MCALL_NAMED, b_mcall_named);
    reg!(vm, ops::SCALL_NAMED, b_scall_named);
    reg!(vm, ops::NEW_NAMED, b_new_named);
    reg!(vm, ops::NEW_ALLOC, b_new_alloc);
    reg!(vm, ops::SPROP_ENSURE_ARRAY, b_sprop_ensure_array);
    reg!(vm, ops::NEW_INIT, b_new_init);
    reg!(vm, ops::NEW_INIT_NAMED, b_new_init_named);
    reg!(vm, ops::CALLVALUE_NAMED, b_callvalue_named);
    reg!(vm, ops::YIELD, b_yield);
    reg!(vm, ops::YIELD_KV, b_yield_kv);
    reg!(vm, ops::YIELD_FROM, b_yield_from);
    reg!(vm, ops::IS_GENERATOR, b_is_generator);
    reg!(vm, ops::GEN_REWIND, b_gen_rewind);
    reg!(vm, ops::GEN_RELEASE, b_gen_release);
    reg!(vm, ops::GEN_MARK, b_gen_mark);
    reg!(vm, ops::PROP_FETCH_W, b_prop_fetch_w);
    reg!(vm, ops::BYREF_ARG_DIAG_M, b_byref_arg_diag_m);
    reg!(vm, ops::GEN_VALID, b_gen_valid);
    reg!(vm, ops::GEN_KEY, b_gen_key);
    reg!(vm, ops::GEN_CURRENT, b_gen_current);
    reg!(vm, ops::GEN_NEXT, b_gen_next);
    reg!(vm, ops::FOREACH_ITER, b_foreach_iter);
    reg!(vm, ops::IS_LAZY_ITER, b_is_lazy_iter);
}

// ── generators ───────────────────────────────────────────────────────────────

/// `yield $v` — suspend the running generator; returns the next `->send()` value.
/// An error carrying a now-pending throw halts the body so it unwinds normally.
fn b_yield(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    match host::yield_value(val) {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

/// `yield $k => $v` — suspend with an explicit key. Stack `[value, key]`.
fn b_yield_kv(vm: &mut VM, _: u8) -> Value {
    let key = vm.pop();
    let val = vm.pop();
    match host::yield_kv(key, val) {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

/// `yield from $it` — delegate; leaves the delegate's return value on the stack.
fn b_yield_from(vm: &mut VM, _: u8) -> Value {
    let src = vm.pop();
    match host::yield_from(src) {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

/// A `yield` error is either a real error (yield outside a generator) or the
/// sentinel for an injected/uncaught throw already recorded as pending — in the
/// latter case halt the chunk so the pending exception unwinds the body.
fn yield_err(vm: &mut VM, e: String) -> Value {
    // A generator destroyed while parked at this `yield` leaves its body as a
    // `return;` does: the signal is set, the chunk only has to stop.
    if host::unwinding() || e == host::GEN_DESTROY {
        vm.ip = vm.chunk.ops.len();
        Value::Undef
    } else {
        // A generator method can refuse the call with a real PHP exception —
        // `getReturn()` before the body has returned — so a tagged throw has to
        // become one rather than stopping the run with a scaffold message. An
        // untagged error still falls through to `fail`.
        fail_or_throw(vm, e)
    }
}

fn b_is_generator(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    Value::bool(with_host(|h| h.is_generator_val(&v)))
}

/// A `foreach` step names the `foreach` line in the frames it opens. Only
/// the steps a `foreach` emits carry a line; a step that carries none leaves
/// the frame where it was.
fn mark_foreach_line(vm: &VM) {
    if cur_op_line(vm) > 0 {
        mark_frame_line(vm);
    }
}

fn b_is_lazy_iter(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    Value::bool(host::is_lazy_iter(&v))
}

fn b_foreach_iter(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    mark_foreach_line(vm);
    match host::foreach_iter(v) {
        Ok(it) => bubbled(vm, it),
        Err(e) => fail_or_throw(vm, e),
    }
}

fn b_gen_mark(_: &mut VM, _: u8) -> Value {
    Value::int(host::gen_mark())
}

fn b_gen_release(vm: &mut VM, _: u8) -> Value {
    let mark = vm.pop().to_int();
    let g = vm.pop();
    match host::gen_release(&g, mark) {
        Ok(()) => bubbled(vm, Value::Undef),
        Err(e) => yield_err(vm, e),
    }
}

fn b_gen_rewind(vm: &mut VM, _: u8) -> Value {
    let g = vm.pop();
    mark_foreach_line(vm);
    let r = if with_host(|h| h.is_generator_val(&g)) {
        host::gen_foreach_rewind(&g).map(|()| Value::Undef)
    } else {
        host::iter_call(&g, "rewind").map(|_| Value::Undef)
    };
    match r {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

fn b_gen_valid(vm: &mut VM, _: u8) -> Value {
    let g = vm.pop();
    mark_foreach_line(vm);
    let r = if with_host(|h| h.is_generator_val(&g)) {
        host::gen_valid(&g)
    } else {
        host::iter_call(&g, "valid").map(|v| with_host(|h| h.is_truthy(&v)))
    };
    match r {
        Ok(b) => bubbled(vm, Value::bool(b)),
        Err(e) => yield_err(vm, e),
    }
}

fn b_gen_key(vm: &mut VM, _: u8) -> Value {
    let g = vm.pop();
    mark_foreach_line(vm);
    let r = if with_host(|h| h.is_generator_val(&g)) {
        host::gen_key(&g)
    } else {
        host::iter_call(&g, "key")
    };
    match r {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

fn b_gen_current(vm: &mut VM, _: u8) -> Value {
    let g = vm.pop();
    mark_foreach_line(vm);
    let r = if with_host(|h| h.is_generator_val(&g)) {
        host::gen_current(&g)
    } else {
        host::iter_call(&g, "current")
    };
    match r {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

fn b_gen_next(vm: &mut VM, _: u8) -> Value {
    let g = vm.pop();
    mark_foreach_line(vm);
    let r = if with_host(|h| h.is_generator_val(&g)) {
        host::gen_next(&g)
    } else {
        host::iter_call(&g, "next")
    };
    match r {
        Ok(v) => bubbled(vm, v),
        Err(e) => yield_err(vm, e),
    }
}

/// What [`split_named`] hands back: the positional arguments, then the named
/// ones with the name each was given. Spelled out in the return position it is
/// what `clippy::type_complexity` refuses (`-D warnings` in CI).
type SplitArgs = (Vec<Value>, Vec<(String, Value)>);

/// Split a `(name, value)` argument-pair stream into positional arguments (name is
/// `Undef`) and named arguments (name is a `Str`), preserving source order.
fn split_named(pairs: Vec<Value>) -> Result<SplitArgs, String> {
    let mut positional = Vec::new();
    let mut named = Vec::new();
    let mut it = pairs.into_iter();
    while let (Some(name), Some(val)) = (it.next(), it.next()) {
        match name {
            Value::Str(s) => named.push((s.to_string(), val)),
            // `Bool(true)` in the NAME slot marks a `...$spread` argument (see
            // `Compiler::compile_arg_pairs_for`): the value is flattened into
            // the list here, its string keys becoming named arguments and its
            // integer keys positional ones. A name is otherwise a string or
            // `Undef`, so the marker can never collide with one.
            Value::Bool(true) => {
                for (k, v) in spread_entries(&val).map_err(|(_, e)| e)? {
                    match k {
                        Value::Str(_) => named.push((with_host(|h| h.to_str(&k)), v)),
                        _ => positional.push(v),
                    }
                }
            }
            _ => positional.push(val),
        }
    }
    Ok((positional, named))
}

/// [`split_named`] for a builtin: an operand that cannot be unpacked is the
/// reference's `TypeError` at the call site, which unwinds this chunk.
macro_rules! split_named_or_throw {
    ($vm:expr, $pairs:expr) => {
        match split_named($pairs) {
            Ok(v) => v,
            Err(e) => return throw_php($vm, "TypeError", &e),
        }
    };
}

/// `f(name: v, ...)` — named-argument function call. Stack `[fname, (n,v)...]`.
fn b_call_named(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    let (pos, named) = split_named_or_throw!(vm, pairs);
    // The only call op that did not record its line: `b_call`, `b_mcall`,
    // `b_scall` and both other named variants all do, so an error raised by a
    // named FUNCTION call reported "on line 0" while the same error from every
    // other spelling named the caller's line.
    mark_frame_line(vm);
    match host::call_function_named(&name, pos, named) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail(vm, e),
    }
}

/// `$f(name: v, ...)` — named-argument dynamic call. Stack `[callee, (n,v)...]`.
fn b_callvalue_named(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 1);
    let callee = vm.pop();
    let (pos, named) = split_named_or_throw!(vm, pairs);
    mark_frame_line(vm);
    match host::call_value_named(callee, pos, named) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `$o->m(name: v, ...)` — named-argument method call. Stack `[recv, method, (n,v)...]`.
fn b_mcall_named(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 2);
    let method = pop_name(vm);
    let recv = vm.pop();
    let (pos, named) = split_named_or_throw!(vm, pairs);
    mark_frame_line(vm);
    // Built-in `Closure`/`Generator` methods take positional args (no named form).
    if with_host(|h| h.is_closure(&recv)) {
        return match host::call_closure_method(&recv, &method, pos) {
            Ok(v) => bubbled(vm, v),
            // A `Closure` method can refuse the call with a real PHP exception —
            // an undefined one is a catchable `Error` — so a tagged throw has to
            // become one rather than being printed as a scaffold message.
            Err(e) => fail_or_throw(vm, e),
        };
    }
    if with_host(|h| h.is_generator_val(&recv)) {
        return match host::call_generator_method(&recv, &method, pos) {
            Ok(v) => bubbled(vm, v),
            Err(e) => yield_err(vm, e),
        };
    }
    match with_host(|h| h.object_class(&recv)) {
        Some(c) => {
            let magic = match method_plan(vm, &c, &method, true) {
                Ok(m) => m,
                Err(v) => return v,
            };
            let r = if magic {
                host::call_magic_call_named(&c, &method, Some(recv), pos, named)
            } else {
                host::call_method_named(&c, &method, Some(recv), pos, named)
            };
            match r {
                Ok(v) => bubbled(vm, v),
                Err(e) => fail(vm, e),
            }
        }
        None => {
            let ty = with_host(|h| receiver_type_name(h, &recv));
            throw_php(
                vm,
                "Error",
                &format!("Call to a member function {method}() on {ty}"),
            )
        }
    }
}

/// `C::m(name: v, ...)` — named-argument static call. Stack `[class, method, (n,v)...]`.
fn b_scall_named(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 2);
    let method = pop_name(vm);
    let class = pop_name(vm);
    let (pos, named) = split_named_or_throw!(vm, pairs);
    let this = with_host(|h| {
        let t = h.get_var("this");
        matches!(t, Value::Obj(_)).then_some(t)
    });
    mark_frame_line(vm);
    let magic = match static_method_plan(vm, &class, &method, &this) {
        Ok(m) => m,
        Err(v) => return v,
    };
    let r = if magic {
        host::call_magic_call_named(&class, &method, this, pos, named)
    } else {
        host::call_method_named(&class, &method, this, pos, named)
    };
    match r {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `new C(name: v, ...)` — named-argument constructor. Stack `[class, (n,v)...]`.
/// `new`'s allocation, before its arguments — see `ops::NEW_ALLOC`.
fn b_new_alloc(vm: &mut VM, _: u8) -> Value {
    let class = pop_name(vm);
    mark_frame_line(vm);
    match host::new_alloc(&class) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `new`'s constructor call over the allocated instance — see `ops::NEW_INIT`.
fn b_new_init(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_args(vm, argc as usize);
    let obj = args.remove(0);
    let class = with_host(|h| h.object_class(&obj)).unwrap_or_default();
    mark_frame_line(vm);
    match host::construct_object(&obj, &class, args, Vec::new()) {
        Ok(()) => bubbled(vm, obj),
        Err(e) => fail_or_throw(vm, e),
    }
}

fn b_new_init_named(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 1);
    let obj = vm.pop();
    let (pos, named) = split_named_or_throw!(vm, pairs);
    let class = with_host(|h| h.object_class(&obj)).unwrap_or_default();
    mark_frame_line(vm);
    match host::construct_object(&obj, &class, pos, named) {
        Ok(()) => bubbled(vm, obj),
        Err(e) => fail_or_throw(vm, e),
    }
}

fn b_new_named(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 1);
    let class = pop_name(vm);
    let (pos, named) = split_named_or_throw!(vm, pairs);
    mark_frame_line(vm);
    match host::new_object_named(&class, pos, named) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `Class::$prop` fetched to be written through — `ops::SPROP_ENSURE_ARRAY`.
fn b_sprop_ensure_array(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let class = pop_name(vm);
    mark_warn_site(vm);
    match host::static_prop_ensure_array(&class, &name) {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `ops::PROP_DIM_WRITEBACK`: store a string container back into `$recv->name`.
fn b_prop_dim_writeback(vm: &mut VM, _: u8) -> Value {
    let container = vm.pop();
    let name = pop_name(vm);
    let recv = vm.pop();
    let val = vm.pop();
    if matches!(container, Value::Str(_)) {
        with_host(|h| h.prop_set(&recv, &name, container));
    }
    val
}

/// `ops::SPROP_DIM_WRITEBACK`: store a string container back into `Class::$name`.
fn b_sprop_dim_writeback(vm: &mut VM, _: u8) -> Value {
    let container = vm.pop();
    let name = pop_name(vm);
    let class = pop_name(vm);
    let val = vm.pop();
    if matches!(container, Value::Str(_)) {
        if let Err(e) = host::static_prop_set(&class, &name, container) {
            return fail_or_throw(vm, e);
        }
    }
    val
}

/// `Class::$prop` read. Stack `[class, name]`.
fn b_sprop_get(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let class = pop_name(vm);
    match host::static_prop_get(&class, &name) {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `Class::$prop` read for `isset`/`empty`/`??`. Stack `[class, name]`.
fn b_sprop_get_q(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let class = pop_name(vm);
    match host::static_prop_get_quiet(&class, &name) {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `Class::$prop = val`. Stack `[class, name, val]`; leaves the assigned value.
fn b_sprop_set(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = pop_name(vm);
    let class = pop_name(vm);
    let declared = with_host(|h| {
        h.resolve_static_owner(&class, &name)
            .and_then(|owner| h.prop_type(&owner, &name))
    });
    let val = match declared {
        Some((owner, ty)) => match check_prop_type(vm, &owner, &name, &ty, val) {
            Some(v) => v,
            None => return Value::Undef,
        },
        None => val,
    };
    match host::static_prop_set(&class, &name, val) {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `++`/`--` on `Class::$prop`. Stack `[class, name, code]`; the `code` bits match
/// `b_incdec` (bit0 = increment, bit1 = prefix).
fn b_sprop_incdec(vm: &mut VM, _: u8) -> Value {
    let code = vm.pop().to_int();
    let name = pop_name(vm);
    let class = pop_name(vm);
    let inc = code & 1 != 0;
    let prefix = code & 2 != 0;
    let old = match host::static_prop_get(&class, &name) {
        Ok(v) => v,
        Err(e) => return fail_or_throw(vm, e),
    };
    mark_warn_site(vm);
    if incdec_refused(vm, &old, inc) {
        return Value::Undef;
    }
    let newv = with_host(|h| h.incdec_value(&old, inc));
    if overflowed_to_float(&old, &newv) {
        let declared = with_host(|h| {
            h.resolve_static_owner(&class, &name)
                .and_then(|owner| h.prop_type(&owner, &name))
        });
        if let Some((owner, ty)) = declared {
            if incdec_overflow_refused(vm, &owner, &name, &ty, inc) {
                return Value::Undef;
            }
        }
    }
    if let Err(e) = host::static_prop_set(&class, &name, newv.clone()) {
        return fail_or_throw(vm, e);
    }
    if prefix {
        newv
    } else {
        old
    }
}

/// See `ops::STATIC_HAS`.
fn b_static_has(vm: &mut VM, _: u8) -> Value {
    let key = pop_name(vm);
    Value::bool(with_host(|h| h.static_initialized(&key)))
}

/// `static $var = init;` — alias `$var` to its persistent slot. Stack
/// `[name, slot-key, init]`. The `init` is only used the first time the slot is
/// created; later calls reuse the existing cell.
fn b_static_bind(vm: &mut VM, _: u8) -> Value {
    let init = vm.pop();
    let slot_key = pop_name(vm);
    let name = pop_name(vm);
    with_host(|h| h.bind_static_local(&name, &slot_key, init));
    Value::Undef
}

/// Read the last call's by-reference parameter value at the given position (for
/// the caller's post-call write-back). Stack `[position]`.
fn b_byref_out(vm: &mut VM, _: u8) -> Value {
    let pos = vm.pop().to_int().max(0) as usize;
    with_host(|h| h.byref_out_get(pos))
}

/// Whether the call that just returned took parameter `pos` by reference — the
/// guard a call site emits when its callee is not known until run time.
fn b_byref_live(vm: &mut VM, _: u8) -> Value {
    let pos = vm.pop().to_int().max(0) as usize;
    Value::bool(with_host(|h| h.byref_out_live(pos)))
}

/// `$target = &$source` — bind the two names to a shared cell; leaves the value.
/// `use (&$v)`: the enclosing variable's reference cell, as a handle the
/// closure carries until its frame is built.
fn b_ref_cell(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    with_host(|h| h.ref_cell_of(&name))
}

fn b_ref_bind(vm: &mut VM, _: u8) -> Value {
    let source = pop_name(vm);
    let target = pop_name(vm);
    with_host(|h| {
        h.ref_bind(&target, &source);
        h.get_var(&target)
    })
}

// ── `&` bindings to a container slot ────────────────────────────────────────
//
// The ACQUIRE half (`REF_SLOT_*`) returns the reference cell the right-hand side
// of a `&` denotes, promoting the element/property into a reference if it was a
// plain value; the BIND half (`REF_TO_*`) points the left-hand side at that
// cell. The slot travels between them as an `Int` the compiler never lets reach
// a PHP expression. See `ops::REF_SLOT_VAR`.

/// Stack `[name]` → the reference slot of `$name`.
fn b_ref_slot_var(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    Value::int(with_host(|h| h.elem_ref_slot(&name, &[])) as i64)
}

/// Stack `[name, k1..kN]`, `N = argc-1` → the reference slot of `$name[k1]..[kN]`.
fn b_ref_slot_elem(vm: &mut VM, argc: u8) -> Value {
    let keys = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    if let Some(thrown) =
        guard_array_write(vm, &name, &keys[..keys.len() - 1], host::WriteTail::Ref)
    {
        return thrown;
    }
    Value::int(with_host(|h| h.elem_ref_slot(&name, &keys)) as i64)
}

/// Why a reference to `$recv->prop` cannot be taken or bound: an asymmetric write
/// visibility the calling scope is outside of, or an initialized `readonly`
/// property. Both are `indirectly modify` refusals.
fn indirect_write_refusal(recv: &Value, prop: &str) -> Option<String> {
    with_host(|h| {
        h.set_visibility_error(recv, prop, "indirectly modify")
            .or_else(|| h.readonly_indirect_error(recv, prop))
    })
}

/// Stack `[recv, prop]` → the reference slot of `$recv->prop`.
fn b_ref_slot_prop(vm: &mut VM, _: u8) -> Value {
    let prop = pop_name(vm);
    let recv = vm.pop();
    if let Some(msg) = indirect_write_refusal(&recv, &prop) {
        return throw_php(vm, "Error", &msg);
    }
    Value::int(with_host(|h| h.prop_ref_slot_ensure(&recv, &prop)) as i64)
}

/// Stack `[name, slot]` — bind `$name` to the cell at `slot`.
fn b_ref_to_var(vm: &mut VM, _: u8) -> Value {
    let slot = vm.pop().to_int() as usize;
    let name = pop_name(vm);
    with_host(|h| {
        h.bind_ref_slot(&name, slot);
        h.get_var(&name)
    })
}

/// Stack `[name, k1..kN, slot]`, `N = argc-2` — make `$name[k1]..[kN]` a
/// reference to the cell at `slot`.
fn b_ref_to_elem(vm: &mut VM, argc: u8) -> Value {
    let slot = vm.pop().to_int() as usize;
    let keys = pop_args(vm, argc as usize - 2);
    let name = pop_name(vm);
    with_host(|h| {
        h.bind_elem_to_slot(&name, &keys, slot);
        h.ref_cell_value(slot)
    })
}

/// Stack `[name, k1..kM, slot]`, `M = argc-2` — append a reference to the cell at
/// `slot` to `$name[k1]..[kM]`.
fn b_ref_to_append(vm: &mut VM, argc: u8) -> Value {
    let slot = vm.pop().to_int() as usize;
    let keys = pop_args(vm, argc as usize - 2);
    let name = pop_name(vm);
    if let Some(thrown) = guard_array_write(vm, &name, &keys, host::WriteTail::Append) {
        return thrown;
    }
    match with_host(|h| -> Result<Value, String> {
        h.append_elem_to_slot(&name, &keys, slot)?;
        Ok(h.ref_cell_value(slot))
    }) {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, throws_bare("Error", e)),
    }
}

/// Stack `[recv, prop, slot]` — make `$recv->prop` a reference to `slot`'s cell.
/// See `ops::REF_SLOT_SPROP`.
fn b_ref_slot_sprop(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let class = pop_name(vm);
    match host::static_prop_ref_slot(&class, &name) {
        Ok(slot) => Value::int(slot as i64),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// See `ops::REF_TO_SPROP`.
fn b_ref_to_sprop(vm: &mut VM, _: u8) -> Value {
    let slot = vm.pop().to_int() as usize;
    let name = pop_name(vm);
    let class = pop_name(vm);
    match host::static_prop_bind(&class, &name, slot) {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, e),
    }
}

fn b_ref_to_prop(vm: &mut VM, _: u8) -> Value {
    let slot = vm.pop().to_int() as usize;
    let prop = pop_name(vm);
    let recv = vm.pop();
    if let Some(msg) = indirect_write_refusal(&recv, &prop) {
        return throw_php(vm, "Error", &msg);
    }
    with_host(|h| {
        h.bind_prop_to_slot(&recv, &prop, slot);
        h.ref_cell_value(slot)
    })
}

/// Stack `[slot]` — publish the running by-reference function's returned cell and
/// leave its value (what a plain call of the function sees).
fn b_ret_ref(vm: &mut VM, _: u8) -> Value {
    let slot = vm.pop().to_int() as usize;
    with_host(|h| {
        h.set_ret_ref_slot(slot);
        h.ref_cell_value(slot)
    })
}

/// Stack `[value]` — the cell the last call returned by reference, as an `Int`
/// slot. `value` is the call's result, used as the fallback cell's contents when
/// the callee did not return by reference.
fn b_ref_slot_ret(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    Value::int(with_host(|h| h.take_ret_ref_slot(v)) as i64)
}

/// Stack `[fallback]` — the running frame's late-static-binding class.
fn b_lsb_class(vm: &mut VM, _: u8) -> Value {
    let fallback = pop_name(vm);
    Value::str(with_host(|h| h.lsb_class(&fallback)))
}

/// Mark the next call as forwarding its caller's late-static-binding class.
fn b_lsb_forward(_: &mut VM, _: u8) -> Value {
    with_host(|h| h.lsb_forward());
    Value::Undef
}

/// `$obj instanceof Class` — true if `$obj` is an object whose class is, or
/// descends from / implements, `Class`. Stack `[obj, class-name]`.
fn b_instanceof(vm: &mut VM, _: u8) -> Value {
    let target = pop_name(vm);
    let obj = vm.pop();
    Value::bool(with_host(|h| match h.instance_class(&obj) {
        Some(class) => h.is_a_class(&class, &target),
        None => false,
    }))
}

/// `$expr::` — resolve the value standing left of a `::` to a class name.
///
/// PHP accepts exactly two things here and coerces neither: an object, whose
/// class is used, and a string, which already IS the class name (the lookups
/// downstream are case-insensitive, so it is passed through as written).
/// Everything else — int, float, bool, null, array — is an `Error`, raised
/// before the member is even looked at.
fn b_dyn_class(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    if let Value::Str(s) = &v {
        return Value::str(host::anchored_class(s));
    }
    match with_host(|h| h.object_class(&v)) {
        Some(class) => Value::str(class),
        None => throw_php(vm, "Error", "Class name must be a valid object or a string"),
    }
}

/// `$expr::class` — the class name of an OBJECT.
///
/// Deliberately not `b_dyn_class` plus a read: PHP refuses the class-name
/// string that every other `::` accepts, because `::class` is documented to
/// report the class of a value rather than to echo one back.
fn b_dyn_class_const(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    match with_host(|h| h.instance_class(&v).filter(|_| !h.is_array(&v))) {
        Some(class) => Value::str(class),
        None => {
            let what = with_host(|h| crate::stdlib::types::value_name(h, &v));
            throw_php(
                vm,
                "TypeError",
                &format!("Cannot use \"::class\" on {what}"),
            )
        }
    }
}

/// `clone $o` — see [`host::clone_object`]. The `__clone` hook runs PHP code,
/// so a throw from inside it has to unwind this chunk like any other call.
fn b_clone(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    mark_frame_line(vm);
    match host::clone_object(v) {
        Ok(copy) => bubbled(vm, copy),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `clone($o, [...])` — see `ops::CLONE_WITH`. Stack `[object, properties]`.
///
/// The clone and its `__clone` run first; the entries are then written in
/// order as ordinary assignments in the CALLING scope, so visibility, `__set`
/// and declared types apply as they would to `$copy->name = $value`, with the one
/// difference that a readonly property may be written again.
fn b_clone_with(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    mark_frame_line(vm);
    // Every failure below is raised from inside `clone(...)`, which the
    // reference shows as a frame of its own.
    let line = with_host(|h| h.cur_frame_line());
    let shown = crate::stdlib::common::make_list(args.clone());
    let scoped = with_host(|h| h.enter_clone_frame(line, shown));
    let out = clone_with(vm, args);
    with_host(|h| h.leave_clone_frame(scoped));
    out
}

fn clone_with(vm: &mut VM, args: Vec<Value>) -> Value {
    if args.is_empty() {
        return throw_php(
            vm,
            "ArgumentCountError",
            "clone() expects at least 1 argument, 0 given",
        );
    }
    if args.len() > 2 {
        return throw_php(
            vm,
            "ArgumentCountError",
            &format!("clone() expects at most 2 arguments, {} given", args.len()),
        );
    }
    let (obj, props) = (args[0].clone(), args[1].clone());
    if !with_host(|h| h.is_array(&props)) {
        let given = with_host(|h| h.type_name_for_error(&props));
        return throw_php(
            vm,
            "TypeError",
            &format!("clone(): Argument #2 ($withProperties) must be of type array, {given} given"),
        );
    }
    let copy = match host::clone_object(obj) {
        Ok(copy) => copy,
        Err(e) => return fail_or_throw(vm, e),
    };
    if bubble_throw(vm) {
        return Value::Undef;
    }
    let pairs = with_host(|h| h.array_pairs(&props)).unwrap_or_default();
    for (key, value) in pairs {
        let name = std::sync::Arc::new(with_host(|h| h.to_str(&key)));
        host::in_clone_with(&copy, || prop_assign(vm, copy.clone(), name, value));
        if bubble_throw(vm) {
            return Value::Undef;
        }
    }
    copy
}

// ── $GLOBALS ─────────────────────────────────────────────────────────────────

/// `$GLOBALS` as a value — see `ops::GLOBALS_ARRAY`.
fn b_globals_array(_: &mut VM, _: u8) -> Value {
    with_host(|h| h.globals_array())
}

/// `$GLOBALS[name]` — see `ops::GLOBALS_GET`.
fn b_globals_get(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    mark_frame_line(vm);
    match with_host(|h| h.global_value(&name)) {
        Some(v) => v,
        None => {
            mark_warn_site(vm);
            with_host(|h| h.warn(format!("Undefined global variable ${name}")));
            Value::Undef
        }
    }
}

/// `$GLOBALS[name]` with no diagnostic — see `ops::GLOBALS_GET_Q`.
fn b_globals_get_q(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    with_host(|h| h.global_value(&name)).unwrap_or(Value::Undef)
}

/// Bind a local alias to a global — see `ops::GLOBALS_BIND`. Stack `[local, name]`.
fn b_globals_bind(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let local = pop_name(vm);
    with_host(|h| h.globals_bind(&local, &name));
    Value::Undef
}

/// `unset($GLOBALS[name])` — see `ops::GLOBALS_UNSET`.
fn b_globals_unset(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    with_host(|h| h.globals_unset(&name));
    Value::Undef
}

/// `isset($GLOBALS[name])` — see `ops::GLOBALS_ISSET`.
fn b_globals_isset(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let set = with_host(|h| h.global_value(&name)).is_some_and(|v| !matches!(v, Value::Undef));
    Value::bool(set)
}

/// Normalize a `foreach` subject to an iterable array (objects are iterated).
fn b_foreach_prep(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    match host::foreach_prep(v) {
        Ok(a) => {
            // A throw inside an iterator method must unwind the caller too.
            if bubble_throw(vm) {
                Value::Undef
            } else {
                a
            }
        }
        Err(e) => fail(vm, e),
    }
}

/// Resolve a bare constant reference to its value (or the bare name as a string
/// when undefined, matching PHP 7 leniency).
/// A bare constant reference. Undefined is an `Error` in PHP 8 — the bareword
/// no longer falls back to its own name as a string.
fn b_const_fetch(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    // A deprecated constant's notice reports this op's line, and an error
    // handler that throws from it unwinds the fetch.
    mark_warn_site(vm);
    match with_host(|h| h.const_use(&name)) {
        Some(_) if bubble_throw(vm) => Value::Undef,
        Some(v) => v,
        None => {
            mark_frame_line(vm);
            throw_php(vm, "Error", &undefined_constant(&name))
        }
    }
}

/// See `ops::NS_FN_NAME`.
fn b_ns_fn_name(vm: &mut VM, _: u8) -> Value {
    let site = pop_name(vm).to_string();
    let qualified = pop_name(vm);
    if let Some(name) = with_host(|h| h.ns_call_sites.get(&site).cloned()) {
        return name;
    }
    let global = qualified.rsplit('\\').next().unwrap_or(&qualified);
    let name = if crate::stdlib::callable::dispatches(&qualified) {
        Value::Str(qualified.clone())
    } else if crate::stdlib::callable::dispatches(global) {
        // Reached through the namespace, so never specialised: see
        // `host::Dispatch::CompiledInNamespace`.
        Value::str(format!("\\{global}"))
    } else {
        // Neither exists yet: refused as the namespaced name, and not cached.
        return Value::Str(qualified);
    };
    with_host(|h| h.ns_call_sites.insert(site, name.clone()));
    name
}

/// See `ops::CLASS_LINK_CHECK`.
fn b_class_link_check(vm: &mut VM, _: u8) -> Value {
    let interface = vm.pop().to_int() != 0;
    let name = pop_name(vm);
    match class_or_autoload(vm, &name) {
        Ok(true) => Value::Undef,
        Ok(false) => {
            mark_frame_line(vm);
            let kind = if interface { "Interface" } else { "Class" };
            throw_php(vm, "Error", &format!("{kind} \"{name}\" not found"))
        }
        Err(v) => v,
    }
}

/// See `ops::CONST_FETCH_NS`.
fn b_const_fetch_ns(vm: &mut VM, _: u8) -> Value {
    let qualified = pop_name(vm);
    let global = qualified.rsplit('\\').next().unwrap_or(&qualified);
    mark_warn_site(vm);
    match with_host(|h| h.const_use(&qualified).or_else(|| h.const_use(global))) {
        Some(_) if bubble_throw(vm) => Value::Undef,
        Some(v) => v,
        None => {
            mark_frame_line(vm);
            throw_php(vm, "Error", &undefined_constant(&qualified))
        }
    }
}

/// `__FILE__`, wrapped in the affixes the compiler emitted: empty for `__FILE__`
/// itself, and `{closure:` / `:<line>}` for a closure declared at file scope,
/// whose PHP-given name embeds the script's own.
fn b_magic_file(vm: &mut VM, _: u8) -> Value {
    let suffix = pop_name(vm);
    let prefix = pop_name(vm);
    let file = with_host(|h| h.current_file().to_string());
    Value::str(format!("{prefix}{file}{suffix}"))
}

fn b_magic_dir(vm: &mut VM, _: u8) -> Value {
    let _ = vm;
    Value::str(with_host(|h| h.magic_dir()))
}

/// `__CLASS__` where the parse could not name the class, wrapped in the affixes
/// the compiler emitted — `::q` builds an anonymous class's `__METHOD__` out of
/// the same node.
/// `SELF_CLASS`: the composing class of a trait method. See
/// [`ops::SELF_CLASS`].
fn b_self_class(vm: &mut VM, argc: u8) -> Value {
    let (kw, name_fetch) = scope_operands(vm, argc);
    let class = with_host(|h| h.magic_class());
    if class.is_empty() {
        return no_class_scope(vm, &kw, name_fetch);
    }
    Value::str(class)
}

/// The operands both class-scope ops carry: the keyword, so a failure names
/// the one the program wrote, and — as a second operand — whether the
/// reference is `X::class` (`ZEND_FETCH_CLASS_NAME`), which words its refusals
/// differently from every other fetch. A trait body emits the op without
/// either (a trait method always has a composing class), and `self` is the
/// only spelling that can reach that arm.
fn scope_operands(vm: &mut VM, argc: u8) -> (String, bool) {
    if argc == 0 {
        return ("self".to_string(), false);
    }
    let name_fetch = argc == 2 && vm.pop().is_truthy();
    (with_host(|h| h.to_str(&vm.pop())), name_fetch)
}

/// `self`/`parent`/`static` reached with no class scope at all.
///
/// This is the CLOSURE and top-level case, which the reference answers with a
/// catchable `Error` because a closure may still be bound to a scope. Inside a
/// named function it knows at compile time that no scope can ever be active and
/// refuses the program before it runs; the compiler keeps that path.
///
/// `X::class` is refused by `ZEND_FETCH_CLASS_NAME` as `Cannot use "X" in the
/// global scope`; every other fetch by `zend_fetch_class` as `Cannot access`.
fn no_class_scope(vm: &mut VM, kw: &str, name_fetch: bool) -> Value {
    let msg = if name_fetch {
        format!("Cannot use \"{kw}\" in the global scope")
    } else {
        format!("Cannot access \"{kw}\" when no class scope is active")
    };
    throw_php(vm, "Error", &msg)
}

/// `PARENT_CLASS`: the composing class's parent inside a trait method. A trait
/// used by a class with no parent is the reference's `Cannot use "parent" when
/// current class scope has no parent`, raised where the method RUNS because
/// that is the first point the class is known.
fn b_parent_class(vm: &mut VM, argc: u8) -> Value {
    // A trait body emits this with no operand; a closure (or the top level)
    // emits the keyword. The two say the parentless case differently — `Cannot
    // use` where the scope is known to be a class and `Cannot access` where it
    // is whatever the closure was bound to — so the shape of the emission is
    // what picks the verb. `parent::class` says `Cannot use` either way.
    let from_trait = argc == 0;
    let (kw, name_fetch) = scope_operands(vm, argc);
    let class = with_host(|h| h.magic_class());
    if class.is_empty() {
        return no_class_scope(vm, &kw, name_fetch);
    }
    let parent = with_host(|h| h.magic_parent_class());
    if parent.is_empty() {
        let verb = if from_trait || name_fetch {
            "use"
        } else {
            "access"
        };
        return throw_php(
            vm,
            "Error",
            &format!("Cannot {verb} \"parent\" when current class scope has no parent"),
        );
    }
    Value::str(parent)
}

fn b_magic_class(vm: &mut VM, _: u8) -> Value {
    let suffix = pop_name(vm);
    let prefix = pop_name(vm);
    let class = with_host(|h| h.magic_class());
    Value::str(format!("{prefix}{class}{suffix}"))
}

/// The message PHP raises for a constant that is not defined, shared by the
/// bareword reference and the `constant()` library function so the two cannot
/// drift.
pub(crate) fn undefined_constant(name: &str) -> String {
    format!("Undefined constant \"{name}\"")
}

/// `unset($var)` — remove the scope variable.
fn b_unset_var(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    with_host(|h| h.unset_var(&name));
    Value::Undef
}

/// `unset($name[k1]..[kN])` — remove the deepest array element. Stack:
/// `[name, k1..kN]`, `N = argc-1`.
fn b_unset_path(vm: &mut VM, argc: u8) -> Value {
    let keys = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    mark_warn_site(vm);
    // `unset($o[k])` on an `ArrayAccess` object is `offsetUnset(k)`. Only the
    // single-key form reaches the object; a deeper path indexes whatever
    // `offsetGet` returned, which this scaffold does not model.
    let recv = with_host(|h| h.get_var(&name));
    if keys.len() == 1 {
        if let Some(r) = array_access_call(vm, &recv, "offsetUnset", vec![keys[0].clone()]) {
            return match r {
                Ok(_) => bubbled(vm, Value::Undef),
                Err(e) => fail(vm, e),
            };
        }
    }
    if let Some(issue) = with_host(|h| h.unset_container_issue(&name, &keys)) {
        // `false` is deprecated and left as it is: there is nothing to remove.
        return container_issue(vm, issue).unwrap_or(Value::Undef);
    }
    with_host(|h| h.unset_path(&name, &keys));
    Value::Undef
}

/// Halt the current chunk if an exception is now in flight, so a `throw` raised
/// by a nested call bubbles up through the caller's VM too. Returns `true` when
/// it halted (the caller should return immediately).
fn bubble_throw(vm: &mut VM) -> bool {
    if host::unwinding() {
        vm.ip = vm.chunk.ops.len();
        true
    } else {
        false
    }
}

// ── exceptions / try-catch ───────────────────────────────────────────────────

/// `throw e` — record the exception object as pending and halt this chunk.
fn b_throw(vm: &mut VM, _: u8) -> Value {
    let exc = vm.pop();
    host::set_pending_throw(exc);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// Run a `try`/`catch`/`finally` construct by id; leaves its control status int.
fn b_run_try(vm: &mut VM, _: u8) -> Value {
    let id = vm.pop().to_int();
    match host::run_try_orchestrator(id) {
        Ok(status) => Value::int(status),
        Err(e) => fail(vm, e),
    }
}

/// Halt the current chunk, leaving whatever signal `run_try` already stashed (a
/// pending return or throw) for the enclosing frame to pick up.
fn b_sig_halt(vm: &mut VM, _: u8) -> Value {
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

fn b_sig_break(vm: &mut VM, argc: u8) -> Value {
    let level = sig_level_arg(vm, argc);
    host::set_break(level);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

fn b_sig_continue(vm: &mut VM, argc: u8) -> Value {
    let level = sig_level_arg(vm, argc);
    host::set_continue(level);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// The level operand of a `break`/`continue` signal, defaulting to 1 when the
/// compiler emitted the no-argument form.
fn sig_level_arg(vm: &mut VM, argc: u8) -> u32 {
    if argc == 0 {
        return 1;
    }
    vm.pop().to_int().max(1) as u32
}

/// `SIG_LEVEL` — push the level of the `break`/`continue` that just ended a
/// `try` body, so the dispatch code can pick the loop it was aimed at.
fn b_sig_level(_: &mut VM, _: u8) -> Value {
    Value::int(host::last_break_level() as i64)
}

/// Pop two operands as PHP integers (bitwise ops cast their operands to int).
/// PHP's bitwise operators take two paths. Two *string* operands are combined
/// byte by byte and produce a string — `"5" | "3"` is `"7"` because `0x35|0x33`
/// is `0x37`, not because either side was read as a number. Anything else is
/// numeric and therefore subject to the PHP 8 operand rules, so `"g" | 1` is a
/// `TypeError` while `"5g" | 1` warns and uses `5`.
///
/// `None` means the chunk has been halted with a pending `TypeError`.
fn pop_two_ints(vm: &mut VM, sym: &str) -> Option<(i64, i64)> {
    let b = vm.pop();
    let a = vm.pop();
    int_args(vm, sym, &a, &b)
}

/// [`arith_args`] for the operators that then narrow both operands to `int`.
fn int_args(vm: &mut VM, sym: &str, a: &Value, b: &Value) -> Option<(i64, i64)> {
    mark_warn_site(vm);
    let resolve = || -> Result<(i64, i64), String> {
        Ok((
            int_arith_operand(sym, a, b, true)?,
            int_arith_operand(sym, a, b, false)?,
        ))
    };
    match resolve() {
        Ok(pair) => Some(pair),
        Err(_) => {
            mark_frame_line(vm);
            vm.ip = vm.chunk.ops.len();
            None
        }
    }
}

/// Narrow an already-coerced operand to `int` for the operators that accept
/// nothing else (`% << >> & | ^`, `intdiv`), raising the diagnostics PHP
/// attaches to that narrowing.
///
/// A float that is already integral converts in silence; one with a fraction is
/// deprecated, and one outside `i64` is a warning instead. `orig` is the operand
/// before coercion, because the deprecation quotes the *string* a float-string
/// came from (`float-string ".5g"`) rather than the number it parsed to.
fn int_operand(orig: &Value, coerced: &Value) -> i64 {
    let Value::Float(f) = *coerced else {
        return coerced.to_int();
    };
    let out_of_range = !f.is_finite() || f < i64::MIN as f64 || f > i64::MAX as f64;
    let lossy = out_of_range || f.fract() != 0.0;
    // A float that *came from a string* is always reported as a lost-precision
    // deprecation, even when the loss is an overflow rather than a fraction —
    // but only when the string was written in float form. An integer-format
    // string that merely outgrew `i64` narrows silently.
    if let Value::Str(s) = orig {
        if lossy && host::numeric_prefix_is_float(s) {
            with_host(|h| {
                h.deprecated(format!(
                    "Implicit conversion from float-string \"{s}\" to int loses precision"
                ))
            });
        }
        // Saturating, which is what `as` already does for a finite float.
        return if f.is_finite() { f as i64 } else { 0 };
    }
    if out_of_range {
        let shown = crate::stdlib::types::serialize_float(f);
        with_host(|h| {
            h.warn(format!(
                "The float {shown} is not representable as an int, cast occurred"
            ))
        });
        return 0;
    }
    if f.fract() != 0.0 {
        let shown = crate::stdlib::types::serialize_float(f);
        with_host(|h| {
            h.deprecated(format!(
                "Implicit conversion from float {shown} to int loses precision"
            ))
        });
    }
    f as i64
}

/// Resolve one operand of an int-only operator: the PHP 8 operand rules first,
/// then the narrowing to int.
///
/// Doing both for the left operand before touching the right is observable —
/// `2.5 % "INF"` deprecates the left narrowing and only then throws on the
/// right — so the two steps cannot be batched across operands.
fn int_arith_operand(sym: &str, a: &Value, b: &Value, left: bool) -> Result<i64, String> {
    let n = coerce_arith(sym, a, b, left)?;
    Ok(int_operand(if left { a } else { b }, &n))
}

/// The two operands of a bitwise operator when both are strings, which selects
/// the byte-wise form.
fn pop_two_strs(vm: &mut VM) -> Option<(Vec<u8>, Vec<u8>)> {
    match (vm.stack.iter().nth_back(1), vm.stack.last()) {
        (Some(Value::Str(x)), Some(Value::Str(y))) => {
            let (x, y) = (
                (*crate::bytes::to_bytes(x)).to_vec(),
                (*crate::bytes::to_bytes(y)).to_vec(),
            );
            vm.pop();
            vm.pop();
            Some((x, y))
        }
        _ => None,
    }
}

fn b_bitand(vm: &mut VM, _: u8) -> Value {
    // `&` and `^` truncate to the shorter operand; only `|` pads.
    if let Some((x, y)) = pop_two_strs(vm) {
        return str_bitop(&x, &y, false, |p, q| p & q);
    }
    let Some((a, b)) = pop_two_ints(vm, "&") else {
        return Value::Undef;
    };
    Value::int(a & b)
}
fn b_bitor(vm: &mut VM, _: u8) -> Value {
    if let Some((x, y)) = pop_two_strs(vm) {
        return str_bitop(&x, &y, true, |p, q| p | q);
    }
    let Some((a, b)) = pop_two_ints(vm, "|") else {
        return Value::Undef;
    };
    Value::int(a | b)
}
fn b_bitxor(vm: &mut VM, _: u8) -> Value {
    if let Some((x, y)) = pop_two_strs(vm) {
        return str_bitop(&x, &y, false, |p, q| p ^ q);
    }
    let Some((a, b)) = pop_two_ints(vm, "^") else {
        return Value::Undef;
    };
    Value::int(a ^ b)
}

/// Combine two byte strings. `pad` picks the length rule: `|` runs to the longer
/// operand treating the missing bytes as `\0`, while `&` and `^` stop at the
/// shorter one.
fn str_bitop(x: &[u8], y: &[u8], pad: bool, f: impl Fn(u8, u8) -> u8) -> Value {
    let n = if pad {
        x.len().max(y.len())
    } else {
        x.len().min(y.len())
    };
    let out: Vec<u8> = (0..n)
        .map(|i| {
            f(
                x.get(i).copied().unwrap_or(0),
                y.get(i).copied().unwrap_or(0),
            )
        })
        .collect();
    Value::str(crate::bytes::from_bytes(&out))
}

fn b_shl(vm: &mut VM, _: u8) -> Value {
    let Some((a, b)) = pop_two_ints(vm, "<<") else {
        return Value::Undef;
    };
    // PHP throws a catchable ArithmeticError on a negative shift, not a fatal.
    if b < 0 {
        return throw_php(vm, "ArithmeticError", "Bit shift by negative number");
    }
    // A left shift by >= 64 bits yields 0. Within range PHP wraps on overflow
    // (`1 << 63` = INT_MIN) — `wrapping_shl` matches that where a plain `<<`
    // would panic in a debug build.
    if b >= 64 {
        return Value::int(0);
    }
    Value::int(a.wrapping_shl(b as u32))
}

fn b_shr(vm: &mut VM, _: u8) -> Value {
    let Some((a, b)) = pop_two_ints(vm, ">>") else {
        return Value::Undef;
    };
    if b < 0 {
        return throw_php(vm, "ArithmeticError", "Bit shift by negative number");
    }
    // A right shift by >= 63 is a full arithmetic sign-fill in PHP (0 for
    // non-negative, -1 for negative); Rust's `>>` on i64 is arithmetic, so
    // clamp the shift amount to 63.
    Value::int(a >> b.min(63))
}

fn b_bitnot(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    // `~` on a string flips its bytes and stays a string; on anything but a
    // number it is refused by name rather than by the `Unsupported operand
    // types` wording the binary operators use. A float narrows as
    // `bitwise_not_function` narrows it (see `dval_to_lval_reported`).
    match &v {
        Value::Str(s) => str_bitop(
            &crate::bytes::to_bytes(s),
            &crate::bytes::to_bytes(s),
            false,
            |p, _| !p,
        ),
        Value::Int(n) => Value::int(!n),
        Value::Float(f) => {
            mark_warn_site(vm);
            Value::int(!with_host(|h| h.dval_to_lval_reported(*f)))
        }
        _ => {
            // `zend_zval_value_name`: a bool is named by its value.
            let what = match v {
                Value::Bool(true) => "true".to_string(),
                Value::Bool(false) => "false".to_string(),
                _ => with_host(|h| host::arith_type_name(h, &v)),
            };
            mark_frame_line(vm);
            throw_php(
                vm,
                "TypeError",
                &format!("Cannot perform bitwise not on {what}"),
            )
        }
    }
}

fn b_spaceship(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
    Value::int(with_host(|h| php_compare(h, &a, &b)) as i64)
}

/// Per-statement DAP line marker (emitted only under `php --dap`). Pops the line
/// argument and hands control to the debugger, which pauses here at a breakpoint
/// or step target. A normal (non-`--dap`) build never emits this op, so the hook
/// costs nothing outside the debugger.
fn b_dbg_line(vm: &mut VM, _: u8) -> Value {
    let _line = vm.pop();
    crate::dap::on_debug_line(vm);
    Value::Undef
}

// ── stack helpers ──────────────────────────────────────────────────────────

/// Pop `n` values, restoring source (left-to-right) order.
fn pop_args(vm: &mut VM, n: usize) -> Vec<Value> {
    let mut v = Vec::with_capacity(n);
    for _ in 0..n {
        v.push(vm.pop());
    }
    v.reverse();
    v
}

/// Pop a value used as a name (variable / function name).
/// The name operand of a `$name` op, without copying it.
///
/// The compiler emits the name as a constant, so it arrives as an
/// `Arc<String>` and the clone is a refcount bump. Returning `String` copied
/// the characters on every variable read and every variable write — six times
/// an iteration in a loop like `for ($i = 0; $i < $n; $i++) { $s += $i; }`.
/// Only a variable-variable (`$$x`), whose operand is not already a string,
/// has to allocate.
fn pop_name(vm: &mut VM) -> std::sync::Arc<String> {
    match vm.pop() {
        Value::Str(s) => s,
        other => std::sync::Arc::new(with_host(|h| h.to_str(&other))),
    }
}

/// Record an error and halt the current chunk.
fn fail(vm: &mut VM, msg: impl Into<String>) -> Value {
    with_host(|h| h.set_error(msg));
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// `++`/`--` refuse arrays and objects outright, by name rather than with the
/// `Unsupported operand types` wording the binary operators use.
///
/// `true` means the chunk has been halted with a pending `TypeError`, so the
/// caller must not go on to compute or store a new value.
fn incdec_refused(vm: &mut VM, old: &Value, inc: bool) -> bool {
    if !matches!(old, Value::Obj(_)) {
        return false;
    }
    let what = with_host(|h| host::arith_type_name(h, old));
    let word = if inc { "increment" } else { "decrement" };
    mark_frame_line(vm);
    throw_php(vm, "TypeError", &format!("Cannot {word} {what}"));
    true
}

/// Halt the chunk on an error a host helper returned: as the PHP exception it
/// is tagged as (see [`throws_bare`]), or as a plain scaffold failure when it
/// carries no tag.
///
/// A host helper cannot raise the exception itself — it has no VM to unwind —
/// so it tags the message and the opcode handler that called it converts here.
fn fail_or_throw(vm: &mut VM, e: String) -> Value {
    match untag_bare_throw(&e) {
        Some((class, message)) => {
            let (class, message) = (class.to_string(), message.to_string());
            throw_php(vm, &class, &message)
        }
        None => fail(vm, e),
    }
}

/// Raise a catchable PHP exception from inside a builtin: construct `class` with
/// `message` and record it as the pending throw, then unwind this chunk exactly
/// as the `throw` builtin does, so an enclosing `try`/`catch` can handle it.
///
/// Used by the zero-divisor arithmetic, which PHP 8 reports as a catchable
/// `DivisionByZeroError` rather than a fatal error.
fn throw_php(vm: &mut VM, class: &str, message: &str) -> Value {
    mark_frame_line(vm);
    match pending_php_throw(class, message) {
        Ok(_) => {
            vm.ip = vm.chunk.ops.len();
            Value::Undef
        }
        // The prelude always defines these classes; if construction somehow
        // fails there is no exception to throw, so fall back to a host error.
        Err(e) => fail(vm, e),
    }
}

/// Screen a method call against the class's method table, visibility rules and
/// magic catch-all before it is dispatched.
///
/// `Err(v)` means the chunk has been halted with a thrown `Error` — the two
/// failing arms are both catchable `Error`s in PHP 8, not fatals. `Ok(true)`
/// means the call must be re-dispatched through `__call`/`__callStatic` even
/// though a method of that name may exist: an inaccessible one is the catch-all's
/// business, not an access error.
fn method_plan(vm: &mut VM, class: &str, method: &str, has_this: bool) -> Result<bool, Value> {
    match with_host(|h| h.method_dispatch(class, method, has_this)) {
        host::MethodDispatch::Direct => Ok(false),
        host::MethodDispatch::Magic => Ok(true),
        host::MethodDispatch::Denied(msg) => Err(throw_php(vm, "Error", &msg)),
        host::MethodDispatch::Undefined => Err(throw_php(
            vm,
            "Error",
            &format!(
                "Call to undefined method {}::{method}()",
                host::display_class(class)
            ),
        )),
    }
}

/// [`method_plan`] for the `C::m()` form.
///
/// Three families of static call never reach the class method table and must be
/// let through untouched: `Closure::bind`/`fromCallable`, the synthesized enum
/// helpers `cases`/`from`/`tryFrom`, and a call on a class that was never
/// declared (which reports "class not found", a different diagnostic).
fn static_method_plan(
    vm: &mut VM,
    class: &str,
    method: &str,
    this: &Option<Value>,
) -> Result<bool, Value> {
    // `Closure::bind`/`fromCallable` are synthesized — there is no `Closure`
    // class to find — so they are let through before the existence check.
    if class.eq_ignore_ascii_case("Closure") {
        return Ok(false);
    }
    // A call on a class that was never declared never reaches a method table:
    // the class is what is missing, and PHP says so instead of naming a method
    // that could not have existed either way.
    if !class_or_autoload(vm, class)? {
        return Err(throw_php(
            vm,
            "Error",
            &format!("Class \"{}\" not found", host::display_class(class)),
        ));
    }
    if with_host(|h| h.is_enum_class(class))
        && matches!(
            method.to_ascii_lowercase().as_str(),
            "cases" | "from" | "tryfrom"
        )
    {
        return Ok(false);
    }
    // `__call` handles the static form only when `$this` is set AND is an
    // instance of the named class; otherwise the fallback is `__callStatic`.
    let has_this = this
        .as_ref()
        .and_then(|t| with_host(|h| h.object_class(t)))
        .is_some_and(|c| with_host(|h| h.class_is_a_pub(&c, class)));
    method_plan(vm, class, method, has_this)
}

/// PHP's name for a value's type in the "Call to a member function f() on X"
/// error. Booleans are spelled `true`/`false` there rather than `bool`.
pub(crate) fn receiver_type_name(h: &host::PhpHost, v: &Value) -> &'static str {
    match v {
        Value::Undef => "null",
        Value::Bool(true) => "true",
        Value::Bool(false) => "false",
        Value::Int(_) => "int",
        Value::Float(_) => "float",
        Value::Str(_) => "string",
        Value::Obj(_) if h.is_array(v) => "array",
        _ => "mixed",
    }
}

/// [`throw_php`] for library functions that return `Result` and have no VM
/// handle. Recording the pending throw is enough: the `bubbled` helper on the
/// calling side halts the chunk as soon as it sees one, so the `Ok(Undef)`
/// returned here is never observed as a value.
fn pending_php_throw(class: &str, message: &str) -> Result<Value, String> {
    let exc = host::new_object(class, vec![Value::str(message.to_string())])?;
    host::set_pending_throw(exc);
    Ok(Value::Undef)
}

// ── core builtins ────────────────────────────────────────────────────────────

fn b_echo(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    // The conversion below can warn (`Array to string conversion`, and the NaN
    // one), and the line it belongs to is THIS statement's. It used to arrive
    // here as a side effect of the variable read that fed the operand, which
    // stopped being a builtin once locals moved into frame slots.
    mark_warn_site(vm);
    for a in &args {
        // Conversion first, *outside* the host borrow: an object with
        // `__toString` runs PHP code to produce its string.
        let s = host::to_str_ext(a);
        if host::unwinding() {
            return Value::Undef;
        }
        // `Array to string conversion` reaches a user handler before the text.
        if host::drain_error_handlers() {
            vm.ip = vm.chunk.ops.len();
            return Value::Undef;
        }
        with_host(|h| h.write_out(&s));
        // Each part is its own write: a handler whose chunk it fills runs
        // before the next part is written.
        if crate::stdlib::output::drain_chunks() {
            vm.ip = vm.chunk.ops.len();
            return Value::Undef;
        }
    }
    Value::Undef
}

/// Tell the host which source line a diagnostic raised from here belongs to.
///
/// `VM::ip` has already been advanced past the instruction being dispatched, so
/// the executing op — the `CallBuiltin` that reached this handler — is at
/// `ip - 1`, and the chunk's parallel line table gives its line. Reading it here
/// costs nothing on the paths that never warn.
fn mark_warn_site(vm: &VM) {
    host::set_warn_line(cur_op_line(vm));
}

/// The source line of the op being dispatched. `VM::ip` has already advanced past
/// it, so the executing op is at `ip - 1` in the chunk's parallel line table.
fn cur_op_line(vm: &VM) -> u32 {
    vm.ip
        .checked_sub(1)
        .and_then(|i| vm.chunk.lines.get(i))
        .copied()
        .unwrap_or(0)
}

/// Record the executing op's line as the current call frame's position, so an
/// exception created below here can report its own line and name this frame's
/// call site in its backtrace. Called by the ops that can enter a new frame or
/// raise a throw — nothing else needs it, and reading the line table costs a
/// bounds-checked index.
fn mark_frame_line(vm: &VM) {
    let line = cur_op_line(vm);
    with_host(|h| {
        h.set_cur_line(line);
        // A LIBRARY function warns from inside Rust, with no op of its own to
        // read a line from — `range(): … subsequent bytes are ignored` belongs to
        // the line of the call. Setting the warn site here is what gives every
        // such diagnostic a line at all; a user function that goes on to warn
        // overwrites this from its own ops.
        host::set_warn_line(line);
    });
}

/// `$name` where the compiler resolved `name` to a frame slot: the index is the
/// only operand, so the read skips the superglobal test and the string hash the
/// by-name ops pay on every access.
fn b_getslot(vm: &mut VM, _: u8) -> Value {
    let i = vm.pop().to_int() as u32;
    mark_warn_site(vm);
    with_host(|h| h.slot_get(i))
}

/// Slot read with no `Undefined variable` diagnostic — see `ops::GETSLOT_Q`.
fn b_getslot_q(vm: &mut VM, _: u8) -> Value {
    let i = vm.pop().to_int() as u32;
    with_host(|h| h.slot_get_quiet(i))
}

fn b_setslot(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let i = vm.pop().to_int() as u32;
    with_host(|h| h.slot_set(i, val.clone()));
    val
}

fn b_getvar(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    mark_warn_site(vm);
    if name.as_str() == "this" {
        return read_this(vm);
    }
    with_host(|h| h.get_var_warn(&name))
}

/// `$this` in a value context: `ZEND_FETCH_THIS`, which has no undefined-variable
/// warning to give — with no object bound the read is the `Error` `Using $this
/// when not in object context`.
fn read_this(vm: &mut VM) -> Value {
    let this = with_host(|h| h.get_var("this"));
    if matches!(this, Value::Undef) {
        mark_frame_line(vm);
        return throw_php(vm, "Error", "Using $this when not in object context");
    }
    this
}

/// `$name` read with no `Undefined variable` diagnostic — see `ops::GETVAR_Q`.
fn b_getvar_q(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    with_host(|h| h.get_var(&name))
}

fn b_setvar(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = pop_name(vm);
    with_host(|h| h.set_var(&name, val.clone()));
    val
}

/// The copy an assignment makes. A PHP array is a value, so `$b = $a`,
/// `$o->p = $a` and `$box[k] = $a` each store a copy; an object, a closure and a
/// stream are handles and pass through. The compiler emits this on the
/// right-hand side of a source-level assignment only, so a compiler temporary,
/// a `&` binding and a `foreach` reference keep the handle they were given.
fn b_copy(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    with_host(|h| h.copy_on_assign(val))
}

/// `MATCH_ERROR_MSG`: `[subject] -> string`. See [`ops::MATCH_ERROR_MSG`].
fn b_match_error_msg(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    let msg = with_host(|h| h.match_error_message(&args[0]));
    Value::str(msg)
}

fn b_concat(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    // As in `b_echo`: the conversion warns against the concatenation's own line.
    mark_warn_site(vm);
    concat_values(&a, &b)
}

/// `a . b` with PHP's string conversions.
fn concat_values(a: &Value, b: &Value) -> Value {
    // Two strings need no conversion at all — no `__toString` to run, no
    // `Array to string conversion`, no NaN notice — so they skip both host
    // borrows and the `format!`, and the result is built once at the exact
    // length. This is the shape of most concatenations, including every
    // interpolation whose parts are already strings.
    if let (Value::Str(x), Value::Str(y)) = (a, b) {
        return Value::str(crate::bytes::concat(x, y));
    }
    // Both conversions happen outside the host borrow so an operand with
    // `__toString` can run it. String interpolation lowers to this op too.
    let (a, b) = (host::to_str_ext(a), host::to_str_ext(b));
    if host::unwinding() {
        return Value::Undef;
    }
    Value::str(crate::bytes::concat(&a, &b))
}

/// `$x .= value` for a frame-slot local (`ops::CONCAT_ASSIGN_FSLOT`). The
/// variable is read AFTER the right-hand side, as `ZEND_ASSIGN_OP` reads it,
/// and a string is appended in its own buffer when the slot is the sole owner
/// — the copy every append used to make turned building a string by `.=`
/// into quadratic work.
fn b_concat_assign_fslot(vm: &mut VM, _: u8) -> Value {
    let y = vm.pop();
    let i = vm.pop().to_int() as usize;
    mark_warn_site(vm);
    if let Value::Str(ys) = &y {
        let slot = vm.frames.last_mut().and_then(|f| f.slots.get_mut(i));
        if let Some(Value::Str(s)) = slot {
            crate::bytes::append(std::sync::Arc::make_mut(s), ys);
            return Value::Str(s.clone());
        }
    }
    let r = concat_values(&vm.get_slot(i as u16), &y);
    if !host::unwinding() {
        vm.set_slot(i as u16, r.clone());
    }
    r
}

/// `$x .= value` for a host-slot variable (`ops::CONCAT_ASSIGN_SLOT`); see
/// [`b_concat_assign_fslot`].
fn b_concat_assign_slot(vm: &mut VM, _: u8) -> Value {
    let y = vm.pop();
    let i = vm.pop().to_int() as u32;
    mark_warn_site(vm);
    if let Value::Str(ys) = &y {
        if let Some(v) = with_host(|h| h.slot_append_str(i, ys)) {
            return v;
        }
    }
    let cur = with_host(|h| h.slot_get(i));
    let r = concat_values(&cur, &y);
    if !host::unwinding() {
        with_host(|h| h.slot_set(i, r.clone()));
    }
    r
}

/// `$x .= value` for a variable reached by name (`ops::CONCAT_ASSIGN_VAR`);
/// see [`b_concat_assign_fslot`].
fn b_concat_assign_var(vm: &mut VM, _: u8) -> Value {
    let y = vm.pop();
    let name = pop_name(vm);
    mark_warn_site(vm);
    if let Value::Str(ys) = &y {
        if let Some(v) = with_host(|h| h.var_append_str(&name, ys)) {
            return v;
        }
    }
    let cur = with_host(|h| h.get_var_warn(&name));
    let r = concat_values(&cur, &y);
    if !host::unwinding() {
        with_host(|h| h.set_var(&name, r.clone()));
    }
    r
}

fn b_truthy(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    Value::bool(with_host(|h| h.is_truthy(&v)))
}

fn b_call(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    mark_frame_line(vm);
    match host::call_function(&name, args) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail(vm, e),
    }
}

/// `MINMAX_FLF2`: a direct two-argument `min()`/`max()`. Stack `[name, lhs, rhs]`.
///
/// The reference picks its FRAMELESS implementation for this call shape at
/// compile time, and that implementation disagrees with the variadic one on an
/// unordered pair — so the shape has to survive to here rather than being folded
/// into the ordinary dispatch. A user-declared function of the same name still
/// wins, which is why the name travels with the operands.
fn b_minmax_flf2(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    mark_frame_line(vm);
    if with_host(|h| h.function_defined(&name)) {
        return match host::call_function(&name, args) {
            Ok(v) => bubbled(vm, v),
            Err(e) => fail(vm, e),
        };
    }
    let want_max = name.eq_ignore_ascii_case("max");
    let v = with_host(|h| minmax_frameless(h, &args[0], &args[1], want_max));
    bubbled(vm, v)
}

/// `INCDEC_STEP`: step a value for `++`/`--`. Stack `[old, inc]`.
///
/// Used only by a local held in a fusevm frame slot, which the surrounding ops
/// read and write themselves. The refusal for an array or object operand is the
/// same one the slot and by-name forms make.
fn b_incdec_step(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    let inc = args[1].to_int() != 0;
    let old = args[0].clone();
    // The step warns for a null decrement and for a bool, so it needs the line
    // of the operator — the same site the slot and by-name forms record.
    mark_warn_site(vm);
    if incdec_refused(vm, &old, inc) {
        return Value::Undef;
    }
    with_host(|h| h.incdec_value(&old, inc))
}

/// `GLOBAL_BIND`: `global $name;`. Stack `[name]`.
fn b_global_bind(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    let name = with_host(|h| h.to_str(&args[0]));
    with_host(|h| h.bind_global(&name));
    Value::Undef
}

/// `BYREF_ARG_DIAG`: report an argument that cannot supply a by-reference
/// binding. Stack `[kind, callee, argno, param]`.
///
/// The compiler decides WHICH of the three groups the argument fell into (see
/// [`crate::host::ops::BYREF_ARG_DIAG`]); this only renders the verdict, because
/// only the run has an output stream and an exception to raise.
fn b_byref_arg_diag(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    let (kind, callee, argno, param) = (
        args[0].to_int(),
        with_host(|h| h.to_str(&args[1])),
        args[2].to_int(),
        with_host(|h| h.to_str(&args[3])),
    );
    mark_frame_line(vm);
    if kind == 0 {
        with_host(|h| h.notice("Only variables should be passed by reference"));
        return Value::Undef;
    }
    // A variadic by-reference position has no parameter to name, and the
    // reference leaves the parenthesis out entirely rather than writing `($)`.
    let named = if param.is_empty() {
        String::new()
    } else {
        format!(" (${param})")
    };
    fail_or_throw(
        vm,
        throws_bare(
            "Error",
            format!("{callee}(): Argument #{argno}{named} could not be passed by reference"),
        ),
    )
}

/// `BYREF_ARG_DIAG_M`: [`b_byref_arg_diag`] for a method or static call. Stack
/// `[recv-or-class, method, argno, kind]`.
fn b_byref_arg_diag_m(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize);
    let method = with_host(|h| h.to_str(&args[1]));
    let (argno, kind) = (args[2].to_int(), args[3].to_int());
    let Some((callee, param)) =
        with_host(|h| h.method_byref_param(&args[0], &method, argno as usize))
    else {
        return Value::Undef;
    };
    mark_frame_line(vm);
    if kind == 0 {
        with_host(|h| h.notice("Only variables should be passed by reference"));
        return Value::Undef;
    }
    fail_or_throw(
        vm,
        throws_bare(
            "Error",
            format!("{callee}(): Argument #{argno} (${param}) could not be passed by reference"),
        ),
    )
}

/// Return the call result, or `Undef` if a throw raised inside the callee is now
/// unwinding the caller too (see `bubble_throw`).
fn bubbled(vm: &mut VM, v: Value) -> Value {
    if bubble_throw(vm) {
        Value::Undef
    } else {
        v
    }
}

/// Whether `class` exists once the autoloaders have had their chance at it.
/// `Err` carries what the caller returns instead of its own refusal: the
/// exception a loader threw (already pending, so the chunk just unwinds) or a
/// fatal one raised.
fn class_or_autoload(vm: &mut VM, class: &str) -> Result<bool, Value> {
    match host::class_known(class) {
        Ok(found) if !bubble_throw(vm) => Ok(found),
        Ok(_) => Err(Value::Undef),
        Err(e) => Err(fail(vm, e)),
    }
}

/// A call with `...$arr` argument unpacking. The stack holds the callee name then
/// one `(is_spread, value)` pair per source argument; a spread pair's value is an
/// array whose elements are flattened, in order, into the positional arguments.
/// A Generator or `Traversable` operand is driven for its values, and one that
/// is neither raises the reference's `TypeError`. A spread's INTEGER keys are
/// positional and its STRING keys are named arguments — `f(...["b" => 2,
/// "a" => 1])` binds by name, so the two are bound to `$a` and `$b` rather than
/// in the order the array happened to list them.
fn b_call_spread(vm: &mut VM, argc: u8) -> Value {
    let pairs = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    let mut args = Vec::with_capacity(pairs.len() / 2);
    let mut named: Vec<(String, Value)> = Vec::new();
    let mut it = pairs.into_iter();
    while let (Some(flag), Some(val)) = (it.next(), it.next()) {
        if !with_host(|h| h.is_truthy(&flag)) {
            args.push(val);
            continue;
        }
        // Outside a `with_host` borrow: unpacking a Generator runs its body.
        match spread_entries(&val) {
            Ok(entries) => {
                for (k, v) in entries {
                    // A STRING key names a parameter; an integer key is
                    // positional. The key is what decides, not the position it
                    // happened to sit at in the array.
                    match k {
                        Value::Str(_) => named.push((with_host(|h| h.to_str(&k)), v)),
                        _ => args.push(v),
                    }
                }
            }
            // An argument list raises `TypeError` whatever the operand was.
            Err((_, e)) => return throw_php(vm, "TypeError", &e),
        }
    }
    mark_frame_line(vm);
    let out = if named.is_empty() {
        host::call_function(&name, args)
    } else {
        host::call_function_named(&name, args, named)
    };
    match out {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail(vm, e),
    }
}

/// Create a closure: the first argument is the synthetic definition name, the
/// rest are `(capture-name, captured-value)` pairs read from the current scope.
fn b_mkclosure(vm: &mut VM, argc: u8) -> Value {
    let raw = pop_args(vm, argc as usize);
    let mut it = raw.into_iter();
    let def_name = match it.next() {
        Some(v) => with_host(|h| h.to_str(&v)),
        None => return Value::Undef,
    };
    let mut captured = Vec::new();
    while let Some(k) = it.next() {
        let Some(v) = it.next() else { break };
        let name = with_host(|h| h.to_str(&k));
        // An arrow function's implicit capture (NUL-prefixed by the compiler)
        // binds only a variable the enclosing scope has bound, silently.
        if let Some(bare) = name.strip_prefix('\0') {
            if with_host(|h| h.var_defined(bare)) {
                captured.push((bare.to_string(), v));
            }
            continue;
        }
        captured.push((name, v));
    }
    with_host(|h| h.make_closure(&def_name, captured))
}

/// Call a callable value (`$f(...)`): the callee is under its arguments.
fn b_call_value(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc as usize - 1);
    let callee = vm.pop();
    mark_frame_line(vm);
    match host::call_value(callee, args) {
        Ok(v) => bubbled(vm, v),
        // `fail_or_throw`, not `fail`: "not callable" is a catchable `Error` in
        // the reference, and a scaffold failure here would be invisible to
        // `try`/`catch`.
        Err(e) => fail_or_throw(vm, e),
    }
}

/// The entries a `...` spread contributes, in order.
///
/// An array yields its own; a Generator or a `Traversable` object is
/// materialized the way `foreach` takes it. Anything else — a scalar, `null`, a
/// plain object — is the reference's "Only arrays and Traversables can be
/// unpacked" error.
///
/// The message is one; the CLASS is not. In an array literal an object operand
/// raises `TypeError` and a scalar or `null` raises `Error`; in an argument list
/// every operand raises `TypeError`. The distinction travels with the value, so
/// it is decided here and the argument-list caller overrides it.
fn spread_entries(v: &Value) -> Result<Vec<(Value, Value)>, (&'static str, String)> {
    if !host::is_unpackable(v) {
        let what = with_host(|h| h.type_name_for_error(v));
        let class = if with_host(|h| matches!(v, Value::Obj(_)) && !h.is_array(v)) {
            "TypeError"
        } else {
            "Error"
        };
        return Err((
            class,
            format!("Only arrays and Traversables can be unpacked, {what} given"),
        ));
    }
    if let Some(pairs) = with_host(|h| h.array_pairs(v)) {
        return Ok(pairs);
    }
    // A Generator or Traversable: driving it is what produces the entries, and
    // it CONSUMES the generator, exactly as the reference does.
    let arr = host::foreach_prep(v.clone()).map_err(|e| ("Error", e))?;
    Ok(with_host(|h| h.array_pairs(&arr)).unwrap_or_default())
}

fn b_mkarray(vm: &mut VM, argc: u8) -> Value {
    let raw = pop_args(vm, argc as usize);
    mark_warn_site(vm);
    let arr = with_host(|h| h.new_array());
    match fill_array_spreading(&arr, raw.into_iter()) {
        Ok(()) => arr,
        Err((class, e)) => throw_php(vm, class, &e),
    }
}

/// `MKARRAY_ADD`: the continuation chunks of a literal too long for one
/// `MKARRAY` (see [`host::MKARRAY_CHUNK_PAIRS`]). The first operand is the
/// array built so far; the rest are more `key => value` pairs.
fn b_mkarray_add(vm: &mut VM, argc: u8) -> Value {
    let raw = pop_args(vm, argc as usize);
    mark_warn_site(vm);
    let mut it = raw.into_iter();
    let Some(arr) = it.next() else {
        return Value::Undef;
    };
    match fill_array_spreading(&arr, it) {
        Ok(()) => arr,
        Err((class, e)) => throw_php(vm, class, &e),
    }
}

/// Write a flat `key, value, key, value, …` operand run into `arr`.
///
/// A key equal to [`host::AUTO_INDEX`] means the element was written WITHOUT a
/// key and takes the next integer index. `Value::Undef` is a real PHP `null`
/// key here, which becomes the empty-string key — it is not a "no key" marker.
fn fill_array(
    h: &mut host::PhpHost,
    arr: &Value,
    mut it: impl Iterator<Item = Value>,
) -> Option<Value> {
    while let Some(k) = it.next() {
        let Some(v) = it.next() else { break };
        if host::is_spread_key(&k) {
            // Deferred: unpacking drives user code (a Generator body, an
            // `Iterator::current`), which re-enters the host, so it cannot run
            // under this borrow. The operand is handed back for the caller to
            // unpack a level up.
            return Some(v);
        }
        if host::is_auto_index(&k) {
            h.arr_push_auto(arr, v);
        } else {
            h.arr_set_key(arr, &k, v);
        }
    }
    None
}

/// Write a literal's operand run into `arr`, unpacking any `...` element.
///
/// An integer key from a spread is RENUMBERED — `[...[5 => "a"]]` is
/// `[0 => "a"]` — while a string key is kept and a later one overwrites an
/// earlier, which is what `[...["x" => 1], ...["x" => 2]]` being `["x" => 2]`
/// means. Returns the error text when an operand cannot be unpacked.
fn fill_array_spreading(
    arr: &Value,
    mut it: impl Iterator<Item = Value>,
) -> Result<(), (&'static str, String)> {
    loop {
        // `fill_array` consumes operands until it meets a spread, then hands it
        // back so the unpacking happens outside the host borrow.
        let Some(spread) = with_host(|h| fill_array(h, arr, &mut it)) else {
            return Ok(());
        };
        for (k, v) in spread_entries(&spread)? {
            with_host(|h| match k {
                Value::Int(_) => h.arr_push_auto(arr, v),
                other => h.arr_set_key(arr, &other, v),
            });
        }
    }
}

/// Route `$o[k]` through an `ArrayAccess` object's `offsetX` method, if that is
/// what the receiver is. `None` means the receiver is an ordinary array, string
/// or scalar and the caller's own path applies.
fn array_access_call(
    vm: &mut VM,
    recv: &Value,
    method: &str,
    args: Vec<Value>,
) -> Option<Result<Value, String>> {
    let class = with_host(|h| h.array_access_class(recv))?;
    mark_frame_line(vm);
    Some(host::call_method(&class, method, Some(recv.clone()), args))
}

/// The result of an `offsetX` dispatch, with a failure turned into a halted
/// chunk the same way every other method call is.
fn array_access_result(vm: &mut VM, r: Result<Value, String>) -> Value {
    match r {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail(vm, e),
    }
}

/// The `TypeError` the reference raises for an offset that is an array or an
/// object, or `None` for a key it accepts.
///
/// `tail` is what the message ends with: a value-context read says
/// `on array`, while `isset()`/`empty()` say `in isset or empty`. An
/// `ArrayAccess` object is exempt — `offsetGet` takes any key at all — and so is
/// a string receiver, which has its own diagnostic.
fn bad_offset_type(recv: &Value, key: &Value, tail: &str) -> Option<String> {
    if matches!(recv, Value::Str(_)) {
        return None;
    }
    let name = with_host(|h| {
        if h.array_access_class(recv).is_some() {
            None
        } else {
            h.bad_offset_type(key)
        }
    })?;
    Some(throws_bare(
        "TypeError",
        format!("Cannot access offset of type {name} {tail}"),
    ))
}

fn b_index_get(vm: &mut VM, _: u8) -> Value {
    let key = vm.pop();
    let recv = vm.pop();
    if let Some(r) = array_access_call(vm, &recv, "offsetGet", vec![key.clone()]) {
        return array_access_result(vm, r);
    }
    if let Some(e) = bad_offset_type(&recv, &key, "on array") {
        return fail_or_throw(vm, e);
    }
    // A subscript no string offset can be is a TypeError in a VALUE context —
    // `"abc"["x"]` throws rather than reading byte 0, which is what reading the
    // key through `Value::to_int` used to do. `isset()` and `??` stay quiet, so
    // the check belongs here and not in the host's read.
    if let Some(e) = bad_string_offset(&recv, &key) {
        return fail_or_throw(vm, e);
    }
    mark_warn_site(vm);
    with_host(|h| h.index_get_warn(&recv, &key))
}

/// The `TypeError` PHP throws when `key` cannot name an offset of the string
/// `recv`, or `None` when it can (or `recv` is not a string).
fn bad_string_offset(recv: &Value, key: &Value) -> Option<String> {
    if !matches!(recv, Value::Str(_)) {
        return None;
    }
    if !matches!(host::classify_string_offset(key), host::StrOffset::Bad) {
        return None;
    }
    let t = with_host(|h| h.type_name_for_error(key));
    Some(throws_bare(
        "TypeError",
        format!("Cannot access offset of type {t} on string"),
    ))
}

/// `$a[k]` read with no missing-key diagnostic — see `ops::INDEX_GET_Q`.
fn b_index_get_q(vm: &mut VM, argc: u8) -> Value {
    index_get_quiet(vm, argc, "on array")
}

/// `empty($a[k])` — [`b_index_get_q`] with the wording `empty()` uses.
fn b_index_get_empty(vm: &mut VM, argc: u8) -> Value {
    index_get_quiet(vm, argc, "in isset or empty")
}

fn index_get_quiet(vm: &mut VM, _: u8, tail: &str) -> Value {
    let key = vm.pop();
    let recv = vm.pop();
    // `$o[k] ?? d` on an `ArrayAccess` asks `offsetExists` first and only reads
    // through `offsetGet` once that says yes — the same two-step `??` uses for a
    // magic property.
    if with_host(|h| h.array_access_class(&recv)).is_some() {
        let present = match array_access_call(vm, &recv, "offsetExists", vec![key.clone()]) {
            Some(Ok(v)) => with_host(|h| h.is_truthy(&v)),
            Some(Err(e)) => return fail(vm, e),
            None => false,
        };
        if !present {
            return Value::Undef;
        }
        let r = array_access_call(vm, &recv, "offsetGet", vec![key]);
        return match r {
            Some(r) => array_access_result(vm, r),
            None => Value::Undef,
        };
    }
    // Quiet about a MISSING element, not about a lossy OFFSET: `$a[1.7] ?? $d`
    // and `empty($a[1.7])` both report the narrowing, exactly as a plain read
    // does.
    if let Some(e) = bad_offset_type(&recv, &key, tail) {
        return fail_or_throw(vm, e);
    }
    mark_warn_site(vm);
    with_host(|h| {
        h.diagnose_quiet_offset(&recv, &key);
        h.index_get(&recv, &key)
    })
}

/// One element of a destructuring assignment — see `ops::LIST_ELEM_GET`.
///
/// A list read is not an index read. PHP refuses to walk into anything that is
/// not an array here, so the string case in particular differs sharply:
/// `"ab"[0]` is `'a'`, while `[$x] = "ab"` warns and assigns null. Only the
/// array case reaches the ordinary keyed read, which is what still supplies the
/// `Undefined array key N` warning for a too-short element.
fn b_list_elem_get(vm: &mut VM, _: u8) -> Value {
    let key = vm.pop();
    let recv = vm.pop();
    // An object is a hard error, not a warning — including ArrayAccess, which
    // PHP does not consult for destructuring.
    let is_obj = with_host(|h| matches!(recv, Value::Obj(_)) && !h.is_array(&recv));
    if is_obj {
        let cls = with_host(|h| h.object_class(&recv).unwrap_or_else(|| "object".into()));
        return throw_php(
            vm,
            "Error",
            &format!("Cannot use object of type {cls} as array"),
        );
    }
    if with_host(|h| h.is_array(&recv)) {
        mark_warn_site(vm);
        return with_host(|h| h.index_get_warn(&recv, &key));
    }
    // `null` destructures to null in silence — it is the one non-array subject
    // PHP does not complain about.
    if matches!(recv, Value::Undef) {
        return Value::Undef;
    }
    let ty = match recv {
        Value::Bool(_) => "bool",
        Value::Int(_) => "int",
        Value::Float(_) => "float",
        Value::Str(_) => "string",
        _ => "mixed",
    };
    mark_warn_site(vm);
    with_host(|h| h.warn(format_args!("Cannot use {ty} as array")));
    Value::Undef
}

/// `const NAME = expr;` — see `ops::CONST_DECL`. The declaration writes the same
/// table `define()` writes, and a redefinition warns there rather than here, so
/// the two spellings cannot drift apart.
fn b_const_decl(vm: &mut VM, _: u8) -> Value {
    let value = vm.pop();
    let name = pop_name(vm);
    // A redefinition warns, and the warning carries a line — which has to be
    // taken from the op before the write, since nothing else sets it on this
    // path and it would otherwise report line 0.
    let line = cur_op_line(vm);
    with_host(|h| {
        host::set_warn_line(line);
        h.const_define(&name, value)
    });
    Value::Undef
}

/// `ops::DECLARE_FN`: bind a function declared inside a block, now that its
/// statement runs.
fn b_declare_fn(vm: &mut VM, _: u8) -> Value {
    let ns = with_host(|h| h.to_str(&vm.pop()));
    let name = with_host(|h| h.to_str(&vm.pop()));
    let key = with_host(|h| h.to_str(&vm.pop()));
    let line = cur_op_line(vm);
    match with_host(|h| h.declare_fn_at(&key, &name, &ns, line)) {
        Ok(()) => Value::Undef,
        Err(msg) => runtime_decl_fatal(vm, &msg),
    }
}

/// `ops::DECLARE_CLASS`: [`b_declare_fn`] for a type.
fn b_declare_class(vm: &mut VM, _: u8) -> Value {
    let ns = with_host(|h| h.to_str(&vm.pop()));
    let key = with_host(|h| h.to_str(&vm.pop()));
    let line = cur_op_line(vm);
    match with_host(|h| h.declare_class_at(&key, &ns, line)) {
        Ok(()) => Value::Undef,
        Err(msg) => runtime_decl_fatal(vm, &msg),
    }
}

/// A declaration the reference refuses to link — see `ops::DECL_FATAL`.
///
/// Displayed like an uncaught error (message, then a stack trace) but *not*
/// thrown: PHP raises these below the exception machinery, so no `try`/`catch`
/// can see one and the program always stops here.
fn b_decl_fatal(vm: &mut VM, _: u8) -> Value {
    let msg = with_host(|h| h.to_str(&vm.pop()));
    runtime_decl_fatal(vm, &msg)
}

/// `ops::FINAL_CHECK`: a declaration that breaks a `final` rule of what it
/// inherits is a [`b_decl_fatal`], reported at the overriding method when the
/// rule is about a method.
fn b_final_check(vm: &mut VM, _: u8) -> Value {
    let class = with_host(|h| h.to_str(&vm.pop()));
    match with_host(|h| h.final_check(&class)) {
        None => Value::Undef,
        Some((msg, line)) => {
            let line = line.unwrap_or_else(|| cur_op_line(vm));
            runtime_decl_fatal_at(vm, &msg, line)
        }
    }
}

/// Display `msg` as the declaration fatal [`b_decl_fatal`] describes, at the
/// running op's line, and stop the program.
fn runtime_decl_fatal(vm: &mut VM, msg: &str) -> Value {
    let line = cur_op_line(vm);
    runtime_decl_fatal_at(vm, msg, line)
}

/// [`runtime_decl_fatal`] reported at `line`.
fn runtime_decl_fatal_at(vm: &mut VM, msg: &str, line: u32) -> Value {
    let body = with_host(|h| {
        let trace = h.backtrace();
        format!(
            "{msg} in {} on line {line}\nStack trace:\n{trace}",
            h.current_file()
        )
    });
    with_host(|h| h.fatal("Fatal error", &body));
    fail(vm, format!("Fatal error:  {body}"))
}

/// `isset($a[k])` — see `ops::INDEX_ISSET`.
fn b_index_isset(vm: &mut VM, _: u8) -> Value {
    let key = vm.pop();
    let recv = vm.pop();
    if let Some(r) = array_access_call(vm, &recv, "offsetExists", vec![key.clone()]) {
        return match r {
            Ok(v) => {
                let b = with_host(|h| h.is_truthy(&v));
                bubbled(vm, Value::bool(b))
            }
            Err(e) => fail(vm, e),
        };
    }
    if let Some(e) = bad_offset_type(&recv, &key, "in isset or empty") {
        return fail_or_throw(vm, e);
    }
    // Everything else: set means "reads as something other than null".
    //
    // `isset()` is quiet about a MISSING element but not about a lossy OFFSET:
    // the reference reports `isset()` exactly as it reports the read.
    mark_warn_site(vm);
    with_host(|h| {
        h.diagnose_quiet_offset(&recv, &key);
        Value::bool(!matches!(h.index_get(&recv, &key), Value::Undef))
    })
}

/// Refuse an array write whose target container holds a scalar, as the reference
/// does: `Error: Cannot use a scalar value as an array` for an int, float or
/// `true`, and a deprecation (the write then proceeds) for `false`; a string
/// container refuses what `tail` does to it (see `host::WriteTail`). `keys` are
/// the keys leading to the container being written into. `Some` is the value
/// the calling op returns after the throw.
fn guard_array_write(
    vm: &mut VM,
    name: &str,
    keys: &[Value],
    tail: host::WriteTail,
) -> Option<Value> {
    let issue = with_host(|h| h.write_container_issue(name, keys, tail))?;
    container_issue(vm, issue)
}

/// Raise `issue`: the `Error` it names, or the false-to-array deprecation after
/// which the operation proceeds (`None`).
fn container_issue(vm: &mut VM, issue: host::ContainerIssue) -> Option<Value> {
    match issue {
        host::ContainerIssue::Refused(msg) => Some(throw_php(vm, "Error", &msg)),
        host::ContainerIssue::Scalar => Some(throw_php(
            vm,
            "Error",
            "Cannot use a scalar value as an array",
        )),
        host::ContainerIssue::FalseToArray => {
            mark_warn_site(vm);
            with_host(|h| {
                h.deprecated("Automatic conversion of false to array is deprecated");
            });
            None
        }
    }
}

fn b_index_set(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let key = vm.pop();
    let name = pop_name(vm);
    // Writing through an `ArrayAccess` object must NOT replace it with an array.
    let recv = with_host(|h| h.get_var(&name));
    if let Some(r) = array_access_call(vm, &recv, "offsetSet", vec![key.clone(), val.clone()]) {
        if let Err(e) = r {
            return fail(vm, e);
        }
        return bubbled(vm, val);
    }
    if let Some(e) = bad_offset_type(&recv, &key, "on array") {
        return fail_or_throw(vm, e);
    }
    if let Some(thrown) = guard_array_write(vm, &name, &[], host::WriteTail::Set) {
        return thrown;
    }
    // The write can warn (`String offset cast occurred`) or throw, and both name
    // this line, so the current op's line has to be recorded first.
    let line = cur_op_line(vm);
    mark_frame_line(vm);
    if let Err(e) = with_host(|h| {
        host::set_warn_line(line);
        h.index_set_var(&name, &key, val.clone())
    }) {
        return fail_or_throw(vm, e);
    }
    val
}

fn b_arr_append(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = pop_name(vm);
    // `$o[] = v` is `offsetSet(null, v)` — the null offset is how the object
    // learns the write had no key.
    let recv = with_host(|h| h.get_var(&name));
    if let Some(r) = array_access_call(vm, &recv, "offsetSet", vec![Value::Undef, val.clone()]) {
        if let Err(e) = r {
            return fail(vm, e);
        }
        return bubbled(vm, val);
    }
    if let Some(thrown) = guard_array_write(vm, &name, &[], host::WriteTail::Append) {
        return thrown;
    }
    if let Err(e) = with_host(|h| h.append_var(&name, val.clone())) {
        return fail_or_throw(vm, throws_bare("Error", e));
    }
    val
}

/// `$a[k1]..[kN] = val` — stack `[name, k1..kN, val]`, `N = argc-2 >= 1`.
fn b_set_path(vm: &mut VM, argc: u8) -> Value {
    let val = vm.pop();
    let keys = pop_args(vm, argc as usize - 2);
    let name = pop_name(vm);
    dim_op(vm, &name, &keys, DimOp::Set, val)
}

/// `$a[k1]..[kM][] = val` — stack `[name, k1..kM, val]`, `M = argc-2 >= 0`.
fn b_append_path(vm: &mut VM, argc: u8) -> Value {
    let val = vm.pop();
    let keys = pop_args(vm, argc as usize - 2);
    let name = pop_name(vm);
    dim_op(vm, &name, &keys, DimOp::Append, val)
}

/// Read `$a[k1]..[kN]` — stack `[name, k1..kN]`, `N = argc-1`. Used for the read
/// half of a compound assignment (`$a[k] += ...`).
fn b_get_path(vm: &mut VM, argc: u8) -> Value {
    let keys = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    dim_op(vm, &name, &keys, DimOp::Read, Value::Undef)
}

/// `++`/`--` on `$a[k1]..[kN]` — stack `[name, k1..kN, code]`, `N = argc-2`. The
/// `code` bits match `b_incdec` (bit0 = increment, bit1 = prefix). Decrement of an
/// unset/null element yields -1 here (consistent with `b_incdec` on a plain
/// `$var`); real PHP leaves it null — a documented scaffold deviation.
fn b_incdec_path(vm: &mut VM, argc: u8) -> Value {
    let code = vm.pop().to_int();
    let keys = pop_args(vm, argc as usize - 2);
    let name = pop_name(vm);
    let op = DimOp::IncDec {
        inc: code & 1 != 0,
        prefix: code & 2 != 0,
    };
    dim_op(vm, &name, &keys, op, Value::Undef)
}

/// What a write-mode dimension path does at its end. `keys` passed alongside
/// one are every dimension of the path; for `Append` the trailing `[]` is not
/// among them.
#[derive(Clone, Copy)]
enum DimOp {
    /// `$a[..][k] = v`.
    Set,
    /// `$a[..][] = v`.
    Append,
    /// The read half of `$a[..][k] op= v`, fetched in write mode.
    Read,
    /// `$a[..][k]++` and the like.
    IncDec { inc: bool, prefix: bool },
}

impl DimOp {
    /// How many of the path's keys lead to the container the operation acts on.
    fn container_depth(self, keys: &[Value]) -> usize {
        match self {
            DimOp::Append => keys.len(),
            _ => keys.len() - 1,
        }
    }

    fn tail(self) -> host::WriteTail {
        match self {
            DimOp::Set => host::WriteTail::Set,
            DimOp::Append => host::WriteTail::Append,
            DimOp::Read => host::WriteTail::AssignOp,
            DimOp::IncDec { .. } => host::WriteTail::IncDec,
        }
    }
}

/// Run `op` along `$name[keys..]`: refuse a container that cannot take it,
/// hand the rest of the path to the first `ArrayAccess` object met, and
/// otherwise write (vivifying) through arrays.
fn dim_op(vm: &mut VM, name: &str, keys: &[Value], op: DimOp, val: Value) -> Value {
    let depth = op.container_depth(keys);
    match with_host(|h| h.write_container_issue(name, &keys[..depth], op.tail())) {
        // The read half leaves the false-to-array deprecation to the write.
        Some(host::ContainerIssue::FalseToArray) if matches!(op, DimOp::Read) => {}
        Some(issue) => {
            if let Some(thrown) = container_issue(vm, issue) {
                return thrown;
            }
        }
        None => {}
    }
    if let Some((at, obj)) = array_access_container(name, &keys[..depth]) {
        return array_access_dim(vm, &obj, &keys[at..], op, val);
    }
    match op {
        DimOp::Set => {
            // A string as the last container warns or throws naming this line.
            let line = cur_op_line(vm);
            mark_frame_line(vm);
            if let Err(e) = with_host(|h| {
                host::set_warn_line(line);
                h.index_set_path(name, keys, val.clone())
            }) {
                return fail_or_throw(vm, e);
            }
            val
        }
        DimOp::Append => {
            with_host(|h| h.append_path(name, keys, val.clone()));
            val
        }
        DimOp::Read => {
            mark_warn_site(vm);
            with_host(|h| h.index_get_path_warn(name, keys))
        }
        DimOp::IncDec { inc, prefix } => {
            mark_warn_site(vm);
            let old = with_host(|h| h.index_get_path_warn(name, keys));
            if incdec_refused(vm, &old, inc) {
                return Value::Undef;
            }
            with_host(|h| {
                let newv = h.incdec_value(&old, inc);
                // The string-container case was refused above, so the write
                // cannot fail.
                let _ = h.index_set_path(name, keys, newv.clone());
                if prefix {
                    newv
                } else {
                    old
                }
            })
        }
    }
}

/// The first `ArrayAccess` object among the containers of `$name[keys..]` —
/// the variable, then each prefix of `keys` — with the number of keys that
/// lead to it. Only arrays are walked through.
fn array_access_container(name: &str, keys: &[Value]) -> Option<(usize, Value)> {
    with_host(|h| {
        let mut cur = h.get_var(name);
        for i in 0..=keys.len() {
            if h.array_access_class(&cur).is_some() {
                return Some((i, cur));
            }
            if !h.is_array(&cur) {
                return None;
            }
            cur = h.index_get(&cur, keys.get(i)?);
        }
        None
    })
}

/// The hidden variable the rest of a dimension path is re-rooted on once an
/// `ArrayAccess` object has handed out storage to write into, so the ordinary
/// path machinery performs the write.
const DIM_ROOT: &str = "@dim";

/// Re-root the rest of a dimension path on `DIM_ROOT`: holding `storage` (an
/// array handle, so writes land in it), or bound to the reference cell `slot`
/// (so writes land in the cell, a string offset and a vivified array
/// included). The old binding is dropped first, so a cell bound earlier is
/// not written through.
fn reroot_dim(storage: Option<Value>, slot: Option<usize>) {
    with_host(|h| {
        h.unset_var(DIM_ROOT);
        match (storage, slot) {
            (_, Some(slot)) => h.bind_ref_slot(DIM_ROOT, slot),
            (Some(v), None) => h.set_var(DIM_ROOT, v),
            (None, None) => {}
        }
    });
}

/// `dim_op` on the path re-rooted by [`reroot_dim`], dropping the binding
/// afterwards so the hidden variable does not keep a cell alive.
fn rerooted_dim_op(vm: &mut VM, keys: &[Value], op: DimOp, val: Value) -> Value {
    let r = dim_op(vm, DIM_ROOT, keys, op, val);
    with_host(|h| h.unset_var(DIM_ROOT));
    r
}

/// Finish `op` on the `ArrayAccess` object `obj`, `keys` being the dimensions
/// after it, as `zend_fetch_dimension_address` and the `*_obj_dim` handlers do:
/// the last dimension is `offsetSet` (`null` key for `[]`) or `offsetGet`; an
/// earlier one is fetched with `offsetGet` and the path continues into what it
/// returned. What `function &offsetGet()` returns is the storage itself, and
/// the write lands in it; any other non-object cannot be written through, so
/// the reference reports `Indirect modification of overloaded element` and
/// the write goes nowhere. An `ArrayObject` whose `offsetGet` is the
/// prelude's writes into its storage, as `spl_array_get_dimension_ptr` does.
fn array_access_dim(vm: &mut VM, obj: &Value, keys: &[Value], op: DimOp, val: Value) -> Value {
    let class = with_host(|h| h.array_access_class(obj)).unwrap_or_default();
    let last = match op {
        DimOp::Append => keys.is_empty(),
        _ => keys.len() == 1,
    };
    let through_storage = !last || matches!(op, DimOp::IncDec { .. });
    if through_storage {
        if let Some(storage) = with_host(|h| h.spl_native_storage(obj)) {
            reroot_dim(Some(storage), None);
            return rerooted_dim_op(vm, keys, op, val);
        }
    }
    // The cell a by-reference `offsetGet` publishes, `None` for a by-value one.
    let call = |vm: &mut VM, method: &str, args: Vec<Value>| -> Option<(Value, Option<usize>)> {
        with_host(|h| h.take_published_ret_ref());
        match array_access_call(vm, obj, method, args)? {
            Ok(v) if !bubble_throw(vm) => Some((v, with_host(|h| h.take_published_ret_ref()))),
            Ok(_) => None,
            Err(e) => {
                fail(vm, e);
                None
            }
        }
    };
    let indirect = |vm: &mut VM| {
        mark_warn_site(vm);
        with_host(|h| {
            h.notice(format!(
                "Indirect modification of overloaded element of {} has no effect",
                host::display_class(&class)
            ))
        });
    };
    if last {
        return match op {
            DimOp::Set => call(vm, "offsetSet", vec![keys[0].clone(), val.clone()]).map(|_| val),
            DimOp::Append => call(vm, "offsetSet", vec![Value::Undef, val.clone()]).map(|_| val),
            DimOp::Read => call(vm, "offsetGet", vec![keys[0].clone()]).map(|(v, _)| v),
            DimOp::IncDec { inc, prefix } => {
                call(vm, "offsetGet", vec![keys[0].clone()]).map(|(old, slot)| {
                    let newv = with_host(|h| h.incdec_value(&old, inc));
                    match slot {
                        Some(slot) => {
                            reroot_dim(None, Some(slot));
                            with_host(|h| {
                                h.set_var(DIM_ROOT, newv.clone());
                                h.unset_var(DIM_ROOT);
                            });
                        }
                        None => indirect(vm),
                    }
                    if prefix {
                        newv
                    } else {
                        old
                    }
                })
            }
        }
        .unwrap_or(Value::Undef);
    }
    let Some((child, slot)) = call(vm, "offsetGet", vec![keys[0].clone()]) else {
        return Value::Undef;
    };
    if let Some(slot) = slot {
        reroot_dim(None, Some(slot));
        return rerooted_dim_op(vm, &keys[1..], op, val);
    }
    if with_host(|h| h.is_object_value(&child)) {
        if with_host(|h| h.array_access_class(&child)).is_some() {
            return array_access_dim(vm, &child, &keys[1..], op, val);
        }
        let issue = with_host(|h| h.object_as_array_refusal(&child));
        return container_issue(vm, issue).unwrap_or(Value::Undef);
    }
    indirect(vm);
    match op {
        DimOp::Read => with_host(|h| keys[1..].iter().fold(child, |cur, k| h.index_get(&cur, k))),
        DimOp::IncDec { .. } => Value::Undef,
        DimOp::Set | DimOp::Append => val,
    }
}

/// Append a fresh child array to `$a[k1]..[kN]` and leave its handle on the stack
/// — stack `[name, k1..kN]`, `N = argc-1`. Lets the compiler pivot a mid-path
/// append (`$a[][k] = v`) onto the new child.
fn b_path_append_child(vm: &mut VM, argc: u8) -> Value {
    let keys = pop_args(vm, argc as usize - 1);
    let name = pop_name(vm);
    if let Some(thrown) = guard_array_write(vm, &name, &keys, host::WriteTail::Append) {
        return thrown;
    }
    with_host(|h| h.path_append_child(&name, &keys))
}

fn b_sig_return(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    host::set_return(v);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

fn b_incdec(vm: &mut VM, _: u8) -> Value {
    let code = vm.pop().to_int();
    let name = pop_name(vm);
    let inc = code & 1 != 0;
    let prefix = code & 2 != 0;
    mark_warn_site(vm);
    if name.as_str() == "this" {
        // With no object bound `$this` is not even read; with one it is an
        // object, which `++`/`--` refuse (`Cannot increment A`).
        let this = read_this(vm);
        if !host::unwinding() {
            incdec_refused(vm, &this, inc);
        }
        return Value::Undef;
    }
    // `$x++` on an unset variable reports it, exactly as reading it would.
    let old = with_host(|h| h.get_var_warn(&name));
    if incdec_refused(vm, &old, inc) {
        return Value::Undef;
    }
    with_host(|h| {
        let newv = h.incdec_value(&old, inc);
        h.set_var(&name, newv.clone());
        if prefix {
            newv
        } else {
            old
        }
    })
}

/// `++$x` / `$x--` where the compiler resolved `x` to a frame slot: the same
/// read-modify-write as `b_incdec`, addressing the slot directly so neither half
/// re-resolves the name.
fn b_incdec_slot(vm: &mut VM, _: u8) -> Value {
    let code = vm.pop().to_int();
    let i = vm.pop().to_int() as u32;
    let inc = code & 1 != 0;
    let prefix = code & 2 != 0;
    mark_warn_site(vm);
    // `$x++` on an unset variable reports it, exactly as reading it would.
    let old = with_host(|h| h.slot_get(i));
    if incdec_refused(vm, &old, inc) {
        return Value::Undef;
    }
    with_host(|h| {
        let newv = h.incdec_value(&old, inc);
        h.slot_set(i, newv.clone());
        if prefix {
            newv
        } else {
            old
        }
    })
}

fn b_arraykeys(vm: &mut VM, _: u8) -> Value {
    let recv = vm.pop();
    with_host(|h| h.array_keys(&recv))
}

/// See `ops::IS_PLAIN_OBJECT`.
fn b_is_plain_object(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    Value::bool(with_host(|h| h.is_plain_foreach_object(&v)))
}

/// See `ops::FOREACH_KEYS`.
fn b_foreach_keys(vm: &mut VM, _: u8) -> Value {
    let arr = vm.pop();
    let subj = vm.pop();
    host::foreach_keys(&subj, &arr)
}

fn b_arraylen(vm: &mut VM, _: u8) -> Value {
    let recv = vm.pop();
    Value::int(with_host(|h| h.array_len(&recv)))
}

/// The by-reference array mutators (`array_push`/`array_pop`/`array_shift`/
/// `array_unshift`/`array_splice`). The compiler lowers a call whose first
/// argument is a plain `$var` to `[name, subop, args...]` so the host can rewrite
/// the bound array in place (PHP passes the array by reference here).
fn b_arr_mut(vm: &mut VM, argc: u8) -> Value {
    use host::arrmut;
    let mut args = pop_args(vm, argc as usize);
    // args[0] = variable name, args[1] = sub-op; args[2..] = the call arguments.
    let name = with_host(|h| h.to_str(&args[0]));
    let sub = args[1].to_int();
    let extra: Vec<Value> = args.split_off(2);
    // The array is taken by reference to be mutated, so it is type-checked like
    // any other argument: an unset variable binds as null, and null — like any
    // other non-array — is the `TypeError`, with the call's frame in its trace.
    let target = with_host(|h| h.get_var(&name));
    if !with_host(|h| h.is_array(&target)) {
        let func = match sub {
            arrmut::PUSH => "array_push",
            arrmut::POP => "array_pop",
            arrmut::SHIFT => "array_shift",
            arrmut::UNSHIFT => "array_unshift",
            _ => "array_splice",
        };
        let given = with_host(|h| h.type_name_for_error(&target));
        let mut shown = vec![target];
        shown.extend(extra);
        mark_frame_line(vm);
        return match host::throw_from_internal(
            func,
            &shown,
            "TypeError",
            &format!("{func}(): Argument #1 ($array) must be of type array, {given} given"),
        ) {
            Ok(v) => bubbled(vm, v),
            Err(e) => fail(vm, e),
        };
    }
    let r = with_host(|h| match sub {
        arrmut::PUSH => h.arr_push_var(&name, extra),
        arrmut::POP => Ok(h.arr_pop_var(&name)),
        arrmut::SHIFT => Ok(h.arr_shift_var(&name)),
        arrmut::UNSHIFT => Ok(h.arr_unshift_var(&name, extra)),
        arrmut::SPLICE => Ok(h.arr_splice_var(&name, &extra)),
        _ => Ok(Value::Undef),
    });
    match r {
        Ok(v) => v,
        Err(e) => fail_or_throw(vm, throws_bare("Error", e)),
    }
}

// ── object builtins (classes / OOP) ──────────────────────────────────────────

fn b_new(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_args(vm, argc as usize);
    let class = with_host(|h| h.to_str(&args.remove(0)));
    mark_frame_line(vm);
    match host::new_object(&class, args) {
        Ok(v) => bubbled(vm, v),
        // "Cannot instantiate …" and "Class … not found" are catchable `Error`s.
        Err(e) => fail_or_throw(vm, e),
    }
}

/// Run a magic property method (`__get`, `__set`, `__isset`, `__unset`) with the
/// recursion guard held, so an access to the SAME property from inside its own
/// magic method does not re-enter it. The guard is released on every path,
/// including the one where the method throws.
fn call_magic(recv: &Value, name: &str, magic: &'static str, args: Vec<Value>) -> Value {
    let Some(class) = with_host(|h| h.object_class(recv)) else {
        return Value::Undef;
    };
    with_host(|h| h.magic_enter(recv, name, magic));
    let out = host::call_method(&class, magic, Some(recv.clone()), args);
    with_host(|h| h.magic_leave());
    out.unwrap_or(Value::Undef)
}

/// The receiver and property for a property opcode, plus the plan
/// [`host::PhpHost::prop_access`] produced for `magic`. Every property opcode
/// opens the same way, and the `Denied` arm has to reach `throw_php`, which needs
/// the VM — so the shared part stops just short of acting on the plan.
macro_rules! prop_plan {
    ($vm:expr, $recv:expr, $name:expr, $magic:expr) => {{
        mark_frame_line($vm);
        with_host(|h| h.prop_access(&$recv, &$name, $magic))
    }};
}

fn b_prop_get(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    match prop_plan!(vm, recv, name, "__get") {
        PropAccess::Direct | PropAccess::Absent => plain_prop_read(vm, &recv, &name),
        PropAccess::Magic => {
            if let Some(msg) = with_host(|h| h.uninit_magic_blocked(&recv, &name)) {
                return throw_php(vm, "Error", &msg);
            }
            let v = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
            bubbled(vm, v)
        }
        PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
    }
}

/// The plain `$o->p` read: an uninitialized typed property is an `Error`, any
/// other missing property the "Undefined property" warning and null.
fn plain_prop_read(vm: &mut VM, recv: &Value, name: &str) -> Value {
    if let Some(msg) = with_host(|h| h.uninit_read_error(recv, name)) {
        return throw_php(vm, "Error", &msg);
    }
    mark_warn_site(vm);
    with_host(|h| h.prop_get_warn(recv, name))
}

/// `$o->p` read with no missing-property diagnostic — see `ops::PROP_GET_Q`.
///
/// This is the read `empty()` and `??` compile to. The reference does NOT raise
/// an access error here — an unreachable property is simply "not set" — and it
/// consults the magic methods in a specific order, all three arms of which were
/// read back off it:
///
/// * `__isset` first, when the class has one. A false answer ends the read at
///   null; `__get` is never called, so `$o->p ?? 'd'` on a class whose `__isset`
///   says no is `'d'` without `__get` ever seeing the property.
/// * `__get` for the value, after `__isset` allowed it — or straight away when
///   the class has no `__isset` at all.
/// * A class with `__isset` but no `__get` reads as null even when `__isset`
///   returned true. `isset()` still says true, which is why that question has its
///   own opcode (`ops::PROP_ISSET`) instead of testing this value against null.
fn b_prop_get_q(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    prop_quiet_read(vm, &recv, &name, true)
}

/// The read inside `empty($o->p)` — see `ops::PROP_GET_EMPTY`.
fn b_prop_get_empty(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    prop_quiet_read(vm, &recv, &name, false)
}

/// The shared body of the two isset-mode property reads. `get_without_isset`
/// is the single arm they differ on: whether a class that has `__get` but no
/// `__isset` may be read through `__get` anyway. `??` says yes, `empty()` says no.
fn prop_quiet_read(vm: &mut VM, recv: &Value, name: &str, get_without_isset: bool) -> Value {
    let recv = recv.clone();
    let name = name.to_string();
    if let PropAccess::Direct = prop_plan!(vm, recv, name, "__isset") {
        return with_host(|h| h.prop_get(&recv, &name));
    }
    // `__isset` gates the read, when there is one to ask.
    let has_isset = matches!(prop_plan!(vm, recv, name, "__isset"), PropAccess::Magic);
    if has_isset {
        let present = call_magic(&recv, &name, "__isset", vec![Value::str(name.clone())]);
        if bubble_throw(vm) {
            return Value::Undef;
        }
        if !with_host(|h| h.is_truthy(&present)) {
            return Value::Undef;
        }
    } else if !get_without_isset {
        return Value::Undef;
    }
    match prop_plan!(vm, recv, name, "__get") {
        PropAccess::Magic => {
            let v = call_magic(&recv, &name, "__get", vec![Value::str(name.clone())]);
            bubbled(vm, v)
        }
        PropAccess::Direct => with_host(|h| h.prop_get(&recv, &name)),
        PropAccess::Denied(_) | PropAccess::Absent => Value::Undef,
    }
}

fn b_prop_set(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = pop_name(vm);
    let recv = vm.pop();
    prop_assign(vm, recv, name, val)
}

/// `$recv->name = val` from PHP source: visibility, `__set`, the readonly rule and
/// the declared type, as the assignment opcode applies them. Returns the assigned
/// value, or `Undef` once the chunk has been halted with the error it raised.
fn prop_assign(vm: &mut VM, recv: Value, name: std::sync::Arc<String>, val: Value) -> Value {
    if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "assign")) {
        return throw_php(vm, "Error", &msg);
    }
    match prop_plan!(vm, recv, name, "__set") {
        PropAccess::Direct | PropAccess::Absent => {
            if readonly_refused(vm, &recv, &name) {
                return Value::Undef;
            }
            mark_warn_site(vm);
            let Some(val) = typed_prop_value(vm, &recv, &name, val) else {
                return Value::Undef;
            };
            with_host(|h| h.prop_set_checked(&recv, &name, val.clone()));
            val
        }
        PropAccess::Magic => {
            call_magic(
                &recv,
                &name,
                "__set",
                vec![Value::Str(name.clone()), val.clone()],
            );
            bubbled(vm, val)
        }
        PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
    }
}

/// Screen a source-level write to `$recv->name` against the asymmetric write
/// visibility and the readonly rule.
///
/// `true` means the chunk has been halted with the `Error` PHP raises and the
/// caller must not write. `false` means the write may go ahead — and, for the
/// one write a readonly property is allowed, that it has now been taken, which
/// is why this must be called by the writer and not by a read path.
fn readonly_refused(vm: &mut VM, recv: &Value, name: &str) -> bool {
    if let Some(msg) = with_host(|h| h.set_visibility_error(recv, name, "modify")) {
        throw_php(vm, "Error", &msg);
        return true;
    }
    match with_host(|h| h.readonly_write_error(recv, name)) {
        Some(msg) => {
            throw_php(vm, "Error", &msg);
            true
        }
        None => {
            with_host(|h| h.readonly_note_init(recv, name));
            false
        }
    }
}

/// `$o->name = val` for the write half of a compound assignment — see
/// `ops::PROP_SET_RW`. Stack `[recv, name, val]`.
fn b_prop_set_rw(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = pop_name(vm);
    let recv = vm.pop();
    // `__set` runs here only when `__get` supplied the value that was modified.
    // A class with `__set` and NO `__get` does not use it for a read-modify-write
    // at all: the reference reads the property directly (warning that it is
    // undefined) and writes it directly, creating a real one. `__set` is part of
    // the magic PAIR, and half a pair is not enough to divert the write.
    let has_get = with_host(|h| {
        h.object_class(&recv)
            .is_some_and(|c| h.class_has_method(&c, "__get"))
    });
    match prop_plan!(vm, recv, name, "__set") {
        PropAccess::Magic if has_get => {
            call_magic(
                &recv,
                &name,
                "__set",
                vec![Value::Str(name.clone()), val.clone()],
            );
            bubbled(vm, val)
        }
        PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
        // Writing the slot itself — but only ONE of the two paths here announces
        // a dynamic property, because only one of them is the first to know.
        //
        // With `__get` the `PROP_TOUCH` that opened this read-modify-write stayed
        // silent (the read went to `__get`, creating nothing), so this write is
        // what creates the property and the deprecation belongs here — after
        // `__get` has printed, which is the order the reference uses.
        //
        // Without `__get` that touch already announced it, and announcing it a
        // second time would print the deprecation twice.
        _ if has_get => {
            if readonly_refused(vm, &recv, &name) {
                return Value::Undef;
            }
            mark_warn_site(vm);
            let Some(val) = typed_prop_value(vm, &recv, &name, val) else {
                return Value::Undef;
            };
            with_host(|h| h.prop_set_checked(&recv, &name, val.clone()));
            val
        }
        _ => {
            if readonly_refused(vm, &recv, &name) {
                return Value::Undef;
            }
            mark_warn_site(vm);
            let Some(val) = typed_prop_value(vm, &recv, &name, val) else {
                return Value::Undef;
            };
            with_host(|h| h.prop_set(&recv, &name, val.clone()));
            val
        }
    }
}

/// `isset($o->name)` — see `ops::PROP_ISSET`. Stack `[recv, name]`.
///
/// Asks `__isset` and nothing else. An unreachable property is `false` rather
/// than an error: `isset()` is allowed to ask about anything.
fn b_prop_isset(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    match prop_plan!(vm, recv, name, "__isset") {
        PropAccess::Direct => {
            let v = with_host(|h| h.prop_get(&recv, &name));
            Value::bool(!matches!(v, Value::Undef))
        }
        PropAccess::Magic => {
            let present = call_magic(&recv, &name, "__isset", vec![Value::Str(name.clone())]);
            if bubble_throw(vm) {
                return Value::Undef;
            }
            Value::bool(with_host(|h| h.is_truthy(&present)))
        }
        PropAccess::Denied(_) | PropAccess::Absent => Value::bool(false),
    }
}

/// `unset($o->name)` — see `ops::PROP_UNSET`. Stack `[recv, name]`.
fn b_prop_unset(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    match prop_plan!(vm, recv, name, "__unset") {
        PropAccess::Direct => {
            if let Some(msg) = with_host(|h| h.set_visibility_error(&recv, &name, "unset")) {
                return throw_php(vm, "Error", &msg);
            }
            if let Some(msg) = with_host(|h| h.readonly_unset_error(&recv, &name)) {
                return throw_php(vm, "Error", &msg);
            }
            with_host(|h| h.prop_remove(&recv, &name));
            Value::Undef
        }
        PropAccess::Magic => {
            call_magic(&recv, &name, "__unset", vec![Value::Str(name.clone())]);
            bubbled(vm, Value::Undef)
        }
        PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
        // Unsetting a property that is not there is not an error, but an
        // uninitialized typed one now answers through `__get`.
        PropAccess::Absent => {
            with_host(|h| h.note_unset(&recv, &name));
            Value::Undef
        }
    }
}

/// `$o->name` fetched for writing — see `ops::PROP_TOUCH`. Raises the
/// dynamic-property deprecation and leaves the receiver on the stack for the
/// read that follows. Stack `[recv, name]` -> `[recv]`.
fn b_prop_touch(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    // A compound assignment on something that cannot hold a property stops
    // here, before its read half warns about the property it cannot read.
    if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "assign")) {
        return throw_php(vm, "Error", &msg);
    }
    // A class with `__get` does not get a slot here: the read half will call
    // `__get`, and nothing is created until the write half decides what to do.
    // So the deprecation must not fire yet — and when the write does create a
    // property, it fires AFTER `__get` has run, which is the order the reference
    // prints (`[Gq]` then `Creation of dynamic property`).
    if let PropAccess::Magic = prop_plan!(vm, recv, name, "__get") {
        return recv;
    }
    mark_warn_site(vm);
    with_host(|h| h.warn_dynamic_prop(&recv, &name));
    recv
}

/// `$recv->name` fetched for writing — see `ops::PROP_FETCH_W`. Stack
/// `[recv, name, rw]`.
fn b_prop_fetch_w(vm: &mut VM, _: u8) -> Value {
    let rw = vm.pop().to_int() != 0;
    let name = pop_name(vm);
    let recv = vm.pop();
    if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "modify")) {
        return throw_php(vm, "Error", &msg);
    }
    match prop_plan!(vm, recv, name, "__get") {
        PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
        // `__get` hands back a VALUE: a write into it reaches the object only
        // when that value is itself an object, and the reference says so when
        // it is not.
        PropAccess::Magic => {
            let v = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
            if bubble_throw(vm) {
                return Value::Undef;
            }
            // A `function &__get()` returned a reference: writes through it
            // reach the storage it names, so nothing is lost.
            if let Some(slot) = with_host(|h| h.take_published_ret_ref()) {
                return with_host(|h| h.ref_cell_value(slot));
            }
            let lost = with_host(|h| h.object_class(&v).is_none());
            if lost {
                mark_warn_site(vm);
                with_host(|h| {
                    let class = h.object_class(&recv).unwrap_or_default();
                    h.notice(format!(
                        "Indirect modification of overloaded property {class}::${name} has no effect"
                    ))
                });
            }
            v
        }
        PropAccess::Direct | PropAccess::Absent => {
            // An uninitialized typed property is fetched as the null it is not
            // yet, and left uninitialized: the write after it then fails on null.
            if with_host(|h| h.uninit_read_error(&recv, &name)).is_some() {
                return Value::Undef;
            }
            mark_warn_site(vm);
            with_host(|h| {
                if h.obj_has_prop(&recv, &name) {
                    h.prop_get(&recv, &name)
                } else {
                    h.warn_dynamic_prop(&recv, &name);
                    // A read-and-write fetch still reads: it warns, after the
                    // deprecation, and creates the property all the same.
                    if rw {
                        h.prop_get_warn(&recv, &name);
                    }
                    h.prop_set(&recv, &name, Value::Undef);
                    Value::Undef
                }
            })
        }
    }
}

/// Vivify `$o->name` into an array and leave its handle on the stack — the pivot
/// for indexing/appending into an array-valued property. Stack `[recv, name]`.
fn b_prop_ensure_array(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let recv = vm.pop();
    if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "modify")) {
        return throw_php(vm, "Error", &msg);
    }
    // A property out of reach still errors before anything is vivified; the
    // other outcomes all end in a write, which is what this op is for.
    match prop_plan!(vm, recv, name, "__get") {
        PropAccess::Denied(msg) => return throw_php(vm, "Error", &msg),
        PropAccess::Magic => return prop_ensure_array_magic(vm, &recv, &name),
        PropAccess::Direct | PropAccess::Absent => {}
    }
    if let Some(msg) = with_host(|h| h.set_visibility_error(&recv, &name, "indirectly modify")) {
        return throw_php(vm, "Error", &msg);
    }
    // `$o->tags[] = x` never writes the property itself, so it is not the
    // readonly WRITE rule that stops it — PHP refuses to hand out a modifiable
    // reference into a readonly property at all, with its own wording.
    if let Some(msg) = with_host(|h| h.readonly_indirect_error(&recv, &name)) {
        return throw_php(vm, "Error", &msg);
    }
    mark_warn_site(vm);
    with_host(|h| {
        // `$o->missing[] = 1` vivifies the property, so it too creates a dynamic
        // one when the class never declared it.
        h.warn_dynamic_prop(&recv, &name);
        h.prop_ensure_array(&recv, &name)
    })
}

/// `$o->p[] = v` / `$o->p[k] = v` where `p` resolves to `__get`
/// (`zend_std_get_property_ptr_ptr` falling back to `read_property` with
/// `BP_VAR_W`). A `function &__get()` hands back a reference, and the write lands
/// in the storage it names, vivifying `null` to an array. A by-value `__get`
/// hands back a temporary: an object answers the dimension write itself
/// (`ArrayAccess`), anything else raises the reference's `Indirect modification`
/// notice and the write goes into a copy no one sees.
/// An ARRAY_AS_PROPS `ArrayObject` writes into its storage instead
/// ([`host::PhpHost::spl_array_dim_for_write`]).
fn prop_ensure_array_magic(vm: &mut VM, recv: &Value, name: &str) -> Value {
    if let Some(dim) = with_host(|h| h.spl_array_dim_for_write(recv, name)) {
        return dim;
    }
    let v = call_magic(recv, name, "__get", vec![Value::str(name)]);
    if bubble_throw(vm) {
        return Value::Undef;
    }
    if let Some(slot) = with_host(|h| h.take_published_ret_ref()) {
        return with_host(|h| h.ref_cell_ensure_array(slot));
    }
    if with_host(|h| h.object_class(&v).is_some()) {
        return v;
    }
    mark_warn_site(vm);
    with_host(|h| {
        let class = h.object_class(recv).unwrap_or_default();
        h.notice(format!(
            "Indirect modification of overloaded property {class}::${name} has no effect"
        ));
        if h.is_array(&v) {
            h.copy_on_assign(v)
        } else {
            h.new_array()
        }
    })
}

/// Open an `@expr` suppression region — see `ops::SUPPRESS_PUSH`.
fn b_suppress_push(_: &mut VM, _: u8) -> Value {
    with_host(|h| h.suppress_push());
    Value::Undef
}

/// Close an `@expr` suppression region, passing the operand's value through —
/// see `ops::SUPPRESS_POP`.
fn b_suppress_pop(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| h.suppress_pop());
    v
}

/// `++`/`--` on `$o->name` — stack `[recv, name, code]`. The `code` bits match
/// `b_incdec` (bit0 = increment, bit1 = prefix).
fn b_prop_incdec(vm: &mut VM, _: u8) -> Value {
    let code = vm.pop().to_int();
    let name = pop_name(vm);
    let recv = vm.pop();
    if let Some(msg) = with_host(|h| h.prop_write_refusal(&recv, &name, "increment/decrement")) {
        return throw_php(vm, "Error", &msg);
    }
    let inc = code & 1 != 0;
    let prefix = code & 2 != 0;
    let magic_blocked = with_host(|h| h.uninit_magic_blocked(&recv, &name));
    let uninit = with_host(|h| h.uninit_read_error(&recv, &name));
    match prop_plan!(vm, recv, name, "__get") {
        PropAccess::Denied(msg) => throw_php(vm, "Error", &msg),
        PropAccess::Magic if magic_blocked.is_some() => {
            throw_php(vm, "Error", &magic_blocked.unwrap_or_default())
        }
        PropAccess::Direct | PropAccess::Absent if uninit.is_some() => {
            throw_php(vm, "Error", &uninit.unwrap_or_default())
        }
        // Same read-modify-write shape as `$o->p += 1`: `__get` supplies the old
        // value, and `__set` takes the new one back only if the class has both.
        PropAccess::Magic => {
            let old = call_magic(&recv, &name, "__get", vec![Value::Str(name.clone())]);
            if bubble_throw(vm) {
                return Value::Undef;
            }
            if incdec_refused(vm, &old, inc) {
                return Value::Undef;
            }
            let newv = with_host(|h| h.incdec_value(&old, inc));
            let has_set = with_host(|h| {
                h.object_class(&recv)
                    .is_some_and(|c| h.class_has_method(&c, "__set"))
            });
            if has_set {
                call_magic(
                    &recv,
                    &name,
                    "__set",
                    vec![Value::Str(name.clone()), newv.clone()],
                );
            } else {
                if readonly_refused(vm, &recv, &name) {
                    return Value::Undef;
                }
                mark_warn_site(vm);
                with_host(|h| h.prop_set_checked(&recv, &name, newv.clone()));
            }
            bubbled(vm, if prefix { newv } else { old })
        }
        _ => {
            mark_warn_site(vm);
            // PHP raises the dynamic-property deprecation BEFORE the
            // undefined-property warning here: the slot is created, then read.
            let old = with_host(|h| {
                h.warn_dynamic_prop(&recv, &name);
                h.prop_get_warn(&recv, &name)
            });
            if incdec_refused(vm, &old, inc) {
                return Value::Undef;
            }
            if readonly_refused(vm, &recv, &name) {
                return Value::Undef;
            }
            let newv = with_host(|h| h.incdec_value(&old, inc));
            if overflowed_to_float(&old, &newv) {
                let declared =
                    with_host(|h| h.object_class(&recv).and_then(|c| h.prop_type(&c, &name)));
                if let Some((owner, ty)) = declared {
                    if incdec_overflow_refused(vm, &owner, &name, &ty, inc) {
                        return Value::Undef;
                    }
                }
            }
            with_host(|h| {
                h.prop_set(&recv, &name, newv.clone());
                if prefix {
                    newv
                } else {
                    old
                }
            })
        }
    }
}

/// `[recv, method] -> recv` — the receiver half of a method call's dispatch,
/// run BEFORE the arguments are evaluated.
///
/// PHP decides that a receiver cannot take a method call before it evaluates a
/// single argument, so `$null->m(f())` prints nothing that `f` would have
/// printed. This op raises exactly that error and hands the receiver back for
/// the real `MCALL` to use.
///
/// The method table is consulted too, so `$o->nope(f())` and a call to a method
/// that is out of reach both stop without running `f` — the reference settles
/// the whole callee, not just the receiver, before the first argument.
///
/// That screening is [`method_plan`], the same predicate `MCALL` itself uses a
/// moment later, so this op can only refuse a call that was going to be refused.
/// It is affordable because `PhpHost::method_declared` answers the existence
/// half with a `contains_key` per class in the chain: no `FuncDef` — and so no
/// method body — is copied to decide it. A `Closure` or `Generator` receiver has
/// no PHP class to screen against and is handed straight back, exactly as
/// `MCALL` dispatches it before the class-method path.
fn b_mcall_recv_check(vm: &mut VM, _: u8) -> Value {
    let method = pop_name(vm);
    let recv = vm.pop();
    if with_host(|h| h.is_object_value(&recv)) {
        if let Some(e) = host::engine_method_refusal(&recv, &method) {
            mark_frame_line(vm);
            return fail_or_throw(vm, e);
        }
        if with_host(|h| h.is_closure(&recv) || h.is_generator_val(&recv)) {
            return recv;
        }
        let Some(class) = with_host(|h| h.object_class(&recv)) else {
            return recv;
        };
        mark_frame_line(vm);
        return match method_plan(vm, &class, &method, true) {
            Ok(_) => recv,
            Err(v) => v,
        };
    }
    mark_frame_line(vm);
    let ty = with_host(|h| receiver_type_name(h, &recv));
    throw_php(
        vm,
        "Error",
        &format!("Call to a member function {method}() on {ty}"),
    )
}

/// `[class, method] -> class` — the whole callee decision of `C::m(...)`, run
/// BEFORE the arguments and leaving the class name for the call itself.
///
/// [`static_method_plan`] is the same predicate `SCALL` runs a moment later, and
/// it is pure — no PHP body executes inside it — so asking it twice can change
/// nothing but the point at which the program stops. It subsumes
/// [`ops::CALL_CLASS_CHECK`] here: "class not found" is its first arm.
/// `[callable, is_instance_form] -> callable` — the callee decision of
/// `callee(...)`, made where the syntax is written and leaving the callable for
/// the closure that wraps it.
fn b_fcc_check(vm: &mut VM, _: u8) -> Value {
    let instance = matches!(vm.pop(), Value::Bool(true));
    let callable = vm.pop();
    match host::fcc_refusal(&callable, instance) {
        None => callable,
        Some(e) => {
            mark_frame_line(vm);
            fail_or_throw(vm, e)
        }
    }
}

fn b_scall_callee_check(vm: &mut VM, _: u8) -> Value {
    let method = pop_name(vm);
    let class = pop_name(vm);
    // `SCALL` reads `$this` the same way, and no argument can rebind it, so the
    // magic fallback this picks is the one the call will pick.
    let this = with_host(|h| {
        let t = h.get_var("this");
        matches!(t, Value::Obj(_)).then_some(t)
    });
    mark_frame_line(vm);
    match static_method_plan(vm, &class, &method, &this) {
        Ok(_) => Value::Str(class),
        Err(v) => v,
    }
}

/// `[name] -> name` — reject a call to a function that does not exist BEFORE its
/// arguments run, leaving the name for the call itself.
///
/// The authority is `function_resolves`, the same predicate `function_exists`
/// answers from, so this can only ever refuse a call that was going to be
/// refused anyway — it moves the diagnostic earlier, it does not add one.
fn b_call_name_check(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    if crate::stdlib::callable::dispatches(&name) {
        return Value::Str(name);
    }
    mark_frame_line(vm);
    // No function to enter, so the reference's trace starts at the caller.
    fail_or_throw(
        vm,
        throws_bare("Error", format!("Call to undefined function {name}()")),
    )
}

/// `[class] -> class` — reject `new X(...)` / `X::m(...)` for an undeclared `X`
/// before the arguments run, leaving the class name for the call itself.
fn b_call_class_check(vm: &mut VM, _: u8) -> Value {
    let class = pop_name(vm);
    // `Closure` is synthesized rather than declared, exactly as
    // `static_method_plan` lets it through ahead of its own existence check.
    if class.eq_ignore_ascii_case("Closure") {
        return Value::Str(class);
    }
    match class_or_autoload(vm, &class) {
        Ok(true) => return Value::Str(class),
        Ok(false) => {}
        Err(v) => return v,
    }
    mark_frame_line(vm);
    throw_php(
        vm,
        "Error",
        &format!("Class \"{}\" not found", host::display_class(&class)),
    )
}

/// `[callee] -> callee` — reject an uncallable value before its arguments run,
/// leaving the callee for the call itself.
fn b_callvalue_check(vm: &mut VM, _: u8) -> Value {
    let callee = vm.pop();
    match host::callvalue_refusal(&callee) {
        None => callee,
        Some(e) => {
            mark_frame_line(vm);
            fail_or_throw(vm, e)
        }
    }
}

fn b_mcall(vm: &mut VM, argc: u8) -> Value {
    // Popped in stack order — `[recv, method, args…]` — rather than taken as one
    // block and shifted twice. `pop_name` also hands back the method's existing
    // `Arc<String>` from the constant pool, where `to_str` allocated a fresh
    // `String` for the name of EVERY method call. `b_mcall_named` below already
    // does it this way; this is the same shape.
    let args = pop_args(vm, argc as usize - 2);
    let method = pop_name(vm);
    let recv = vm.pop();
    mark_frame_line(vm);
    // `Closure` and `Generator` are built-in objects with no PHP class; dispatch
    // their methods before the ordinary class-method resolution.
    if with_host(|h| h.is_closure(&recv)) {
        return match host::call_closure_method(&recv, &method, args) {
            Ok(v) => bubbled(vm, v),
            Err(e) => fail_or_throw(vm, e),
        };
    }
    if with_host(|h| h.is_generator_val(&recv)) {
        return match host::call_generator_method(&recv, &method, args) {
            Ok(v) => bubbled(vm, v),
            Err(e) => yield_err(vm, e),
        };
    }
    let class = with_host(|h| h.object_class(&recv));
    match class {
        Some(c) => {
            let magic = match method_plan(vm, &c, &method, true) {
                Ok(m) => m,
                Err(v) => return v,
            };
            let r = if magic {
                host::call_magic_call(&c, &method, Some(recv), args)
            } else {
                host::call_method(&c, &method, Some(recv), args)
            };
            match r {
                Ok(v) => bubbled(vm, v),
                Err(e) => fail(vm, e),
            }
        }
        None => {
            let ty = with_host(|h| receiver_type_name(h, &recv));
            throw_php(
                vm,
                "Error",
                &format!("Call to a member function {method}() on {ty}"),
            )
        }
    }
}

fn b_scall(vm: &mut VM, argc: u8) -> Value {
    // As in `b_mcall`: pop in stack order and keep the constant pool's own
    // `Arc<String>` for both names, instead of shifting the argument vector
    // twice and allocating a `String` for each of them on every static call.
    let args = pop_args(vm, argc as usize - 2);
    let method = pop_name(vm);
    let class = pop_name(vm);
    // Forward `$this` when the call is made from an object context (so
    // `parent::m()` / `self::m()` inside a method keep the current instance).
    let this = with_host(|h| {
        let t = h.get_var("this");
        matches!(t, Value::Obj(_)).then_some(t)
    });
    mark_frame_line(vm);
    let magic = match static_method_plan(vm, &class, &method, &this) {
        Ok(m) => m,
        Err(v) => return v,
    };
    let r = if magic {
        host::call_magic_call(&class, &method, this, args)
    } else {
        host::call_method(&class, &method, this, args)
    };
    match r {
        Ok(v) => bubbled(vm, v),
        // `Enum::from()` raises a catchable ValueError through this path.
        Err(e) => fail_or_throw(vm, e),
    }
}

fn b_sconst(vm: &mut VM, _: u8) -> Value {
    let name = pop_name(vm);
    let class = pop_name(vm);
    // A `#[\Deprecated]` constant's notice reports this op's line, and a
    // handler that throws from it unwinds the fetch.
    mark_warn_site(vm);
    match host::class_const(&class, &name) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

// ── arithmetic builtins (PHP semantics) ──────────────────────────────────────

/// Resolve both operands of an operator compiled as a builtin, halting the chunk
/// with a pending `TypeError` when one has no numeric reading.
///
/// The operand rules run *before* the operator's own checks, which is
/// observable: `"g" / 0` is a `TypeError`, not a `DivisionByZeroError`.
fn arith_args(vm: &mut VM, sym: &str, a: &Value, b: &Value) -> Option<(Value, Value)> {
    mark_warn_site(vm);
    match coerce_arith_pair(sym, a, b) {
        Ok(pair) => Some(pair),
        Err(_) => {
            mark_frame_line(vm);
            vm.ip = vm.chunk.ops.len();
            None
        }
    }
}

fn b_div(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let Some((an, bn)) = arith_args(vm, "/", &a, &b) else {
        return Value::Undef;
    };
    if bn.to_float() == 0.0 {
        return throw_php(vm, "DivisionByZeroError", "Division by zero");
    }
    match (an, bn) {
        // `PHP_INT_MIN / -1` is the one integer division whose exact quotient is
        // not representable, so it leaves the integer path and answers a float —
        // and `x % y` would itself overflow on the way to deciding that, which is
        // why the pair is excluded before the remainder is taken rather than
        // inside the guard.
        (Value::Int(i64::MIN), Value::Int(-1)) => Value::float(-(i64::MIN as f64)),
        (Value::Int(x), Value::Int(y)) if x % y == 0 => Value::int(x / y),
        (an, bn) => Value::float(an.to_float() / bn.to_float()),
    }
}

fn b_mod(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let Some((x, y)) = int_args(vm, "%", &a, &b) else {
        return Value::Undef;
    };
    if y == 0 {
        return throw_php(vm, "DivisionByZeroError", "Modulo by zero");
    }
    // `PHP_INT_MIN % -1` is mathematically 0, but the two's-complement remainder
    // overflows because the QUOTIENT is unrepresentable. PHP answers 0; a plain
    // `x % y` panics in debug Rust, so the remainder is taken wrapping.
    Value::int(x.wrapping_rem(y))
}

/// PHP 8.4 deprecated a zero base raised to a negative exponent; the result is
/// still `INF` (or `-INF`, from a `-0.0` base and an odd exponent), which
/// `powf` already gives, so only the diagnostic is added.
///
/// The test is on the COERCED operands, which is why `"0" ** -1` and
/// `false ** -1` fire too. It is `< 0.0` rather than `<= 0.0` because a negative
/// ZERO exponent is not negative: `0 ** -0.0` is 1.0 and says nothing. `NAN`
/// fails the same comparison, and `0 ** NAN` is likewise silent.
///
/// Both call sites of a PHP power reach this: the `**` operator (and `**=`,
/// which compiles to the same opcode) and the `pow()` library function.
fn deprecate_zero_base_negative_exponent(an: &Value, bn: &Value) {
    if an.to_float() == 0.0 && bn.to_float() < 0.0 {
        with_host(|h| h.deprecated("Power of base 0 and negative exponent is deprecated"));
    }
}

fn b_pow(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let Some((an, bn)) = arith_args(vm, "**", &a, &b) else {
        return Value::Undef;
    };
    deprecate_zero_base_negative_exponent(&an, &bn);
    match (an, bn) {
        (Value::Int(x), Value::Int(y)) if y >= 0 => {
            if let Some(v) = checked_ipow(x, y as u32) {
                Value::int(v)
            } else {
                Value::float((x as f64).powf(y as f64))
            }
        }
        (an, bn) => Value::float(an.to_float().powf(bn.to_float())),
    }
}

fn checked_ipow(mut base: i64, mut exp: u32) -> Option<i64> {
    let mut acc: i64 = 1;
    while exp > 0 {
        if exp & 1 == 1 {
            acc = acc.checked_mul(base)?;
        }
        exp >>= 1;
        if exp > 0 {
            base = base.checked_mul(base)?;
        }
    }
    Some(acc)
}

// ── comparison builtins ──────────────────────────────────────────────────────

/// An object whose class declares `__toString`, which is the only object the
/// reference's comparison casts.
fn is_stringable_object(h: &host::PhpHost, v: &Value) -> bool {
    matches!(v, Value::Obj(_))
        && !h.is_array(v)
        && h.object_class(v)
            .is_some_and(|c| h.class_has_method(&c, "__tostring"))
}

/// Cast an object with a `__toString` to its string when it is compared with a
/// STRING, as `zend_compare` does before comparing the two as strings.
///
/// Without it every `$obj == "s"` was false, `$obj < "t"` answered by the
/// object-vs-scalar rule, and `$obj <=> "s"` was 1 for a `__toString` that
/// returns exactly `"s"`. Only the object/string pair casts: object vs object
/// compares by class and properties, and object vs int is a different rule with
/// a notice of its own.
///
/// Called OUTSIDE the host borrow — the cast runs user code.
fn cast_for_compare(a: &Value, b: &Value) -> Option<(Value, Value)> {
    // Only an object/string PAIR can cast, and that shape is decidable from the
    // two discriminants. Checked before anything else so the host is not
    // borrowed for the scalar pairs that are almost every comparison a program
    // makes — this sits on the `==` builtin and on the numeric hook every
    // relational operator falls into.
    if !matches!(
        (a, b),
        (Value::Obj(_), Value::Str(_)) | (Value::Str(_), Value::Obj(_))
    ) {
        return None;
    }
    let (a_obj, b_obj) = with_host(|h| (is_stringable_object(h, a), is_stringable_object(h, b)));
    match (a_obj, b_obj) {
        (true, false) if matches!(b, Value::Str(_)) => {
            Some((Value::str(host::to_str_ext(a)), b.clone()))
        }
        (false, true) if matches!(a, Value::Str(_)) => {
            Some((a.clone(), Value::str(host::to_str_ext(b))))
        }
        _ => None,
    }
}

/// Whether a loose `in_array` / `array_search` / `array_keys($a, $v)` call
/// may compare an object with a `__toString` against a string: the needle
/// is an object, or a string searched for among elements that include one.
fn needs_stringable_search(lname: &str, args: &[Value]) -> bool {
    let (needle, hay, strict) = match lname {
        "array_keys" if args.len() >= 2 => (arg(args, 1), arg(args, 0), arg(args, 2)),
        "array_keys" => return false,
        _ => (arg(args, 0), arg(args, 1), arg(args, 2)),
    };
    with_host(|h| {
        if h.is_truthy(&strict) {
            return false;
        }
        let objects = |v: &Value| is_stringable_object(h, v);
        match needle {
            Value::Obj(_) if objects(&needle) => true,
            Value::Str(_) => h
                .array_pairs(&hay)
                .unwrap_or_default()
                .iter()
                .any(|(_, v)| objects(v)),
            _ => false,
        }
    })
}

/// The keys whose element loosely equals `needle`, each object/string pair
/// cast through `__toString` as [`cast_for_compare`] casts it; only the first
/// when `first_only`. Called outside the host borrow.
fn loose_search_hits(needle: &Value, hay: &Value, first_only: bool) -> Vec<Value> {
    let pairs = with_host(|h| h.array_pairs(hay)).unwrap_or_default();
    let mut hits = Vec::new();
    for (k, v) in pairs {
        let (a, b) = cast_for_compare(needle, &v).unwrap_or_else(|| (needle.clone(), v));
        if with_host(|h| loose_eq(h, &a, &b)) {
            hits.push(k);
            if first_only {
                break;
            }
        }
    }
    hits
}

fn b_loose_eq(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
    Value::bool(with_host(|h| loose_eq(h, &a, &b)))
}

fn b_loose_ne(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
    Value::bool(with_host(|h| !loose_eq(h, &a, &b)))
}

fn b_strict_eq(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    Value::bool(with_host(|h| strict_eq(h, &a, &b)))
}

fn b_strict_ne(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    Value::bool(with_host(|h| !strict_eq(h, &a, &b)))
}

fn b_lt(vm: &mut VM, _: u8) -> Value {
    cmp_bool(vm, false, |o| o < 0)
}
fn b_gt(vm: &mut VM, _: u8) -> Value {
    cmp_bool(vm, true, |o| o < 0)
}
fn b_le(vm: &mut VM, _: u8) -> Value {
    cmp_bool(vm, false, |o| o <= 0)
}
fn b_ge(vm: &mut VM, _: u8) -> Value {
    cmp_bool(vm, true, |o| o <= 0)
}

/// A relational operator over `zend_compare`. `swap` is how the reference
/// compiles `>` and `>=`: as `<` and `<=` with the operands exchanged
/// (`zend_compile_greater`), which is not the same as testing `> 0` — an
/// UNCOMPARABLE pair reports 1 in both orders, so `$a > $b` and `$b > $a` are
/// both false for two objects of different classes.
fn cmp_bool(vm: &mut VM, swap: bool, f: impl Fn(i32) -> bool) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let (a, b) = cast_for_compare(&a, &b).unwrap_or((a, b));
    if is_unordered(&a, &b) {
        return Value::bool(false);
    }
    let (a, b) = if swap { (b, a) } else { (a, b) };
    Value::bool(f(with_host(|h| php_compare(h, &a, &b))))
}

/// A comparison with a resource on either side compares its NUMBER: `zend_compare`
/// has no resource arm, so a resource reaches the scalar fallback and converts to
/// its id there. `None` when neither operand is a resource.
fn resources_as_ids(h: &host::PhpHost, a: &Value, b: &Value) -> Option<(Value, Value)> {
    let id = |v: &Value| h.resource_info(v).map(|(id, _)| Value::int(id));
    match (id(a), id(b)) {
        (None, None) => None,
        (x, y) => Some((
            x.unwrap_or_else(|| a.clone()),
            y.unwrap_or_else(|| b.clone()),
        )),
    }
}

/// PHP loose equality (`==`) over the scaffold's value set.
fn loose_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
    use Value::*;
    if let Some((a, b)) = resources_as_ids(h, a, b) {
        return loose_eq(h, &a, &b);
    }
    match (a, b) {
        // A bool operand compares by truthiness.
        (Bool(_), _) | (_, Bool(_)) => h.is_truthy(a) == h.is_truthy(b),
        // null/undef converts based on the other operand's type.
        (Undef, x) | (x, Undef) => match x {
            Int(n) => *n == 0,
            Float(f) => *f == 0.0,
            Str(s) => s.is_empty(),
            Obj(_) => h.array_len(x) == 0,
            Undef => true,
            _ => false,
        },
        (Str(x), Str(y)) => {
            if host::is_numeric_string(x) && host::is_numeric_string(y) {
                // The PARSED numbers, not the raw strings: `num_eq` falls back
                // to `Value::to_float`, whose reading of `" 1"` is `0.0`.
                num_eq(&as_php_number(h, a), &as_php_number(h, b))
            } else {
                x == y
            }
        }
        (Obj(_), Obj(_)) => match crate::stdlib::datefn::compare_dates(h, a, b) {
            Some(ord) => ord == 0,
            None => arrays_loose_eq(h, a, b),
        },
        (Obj(_), _) | (_, Obj(_)) => false,
        // `==` is `zend_compare(...) == 0` (`Zend/zend_operators.c:2524`), and a
        // NaN double against a string is answered 1 there before the string is
        // read at all (`:2359`, `:2366`). So `NAN == "NAN"` is FALSE, even
        // though the two render as the same text and the string comparison the
        // arm below would fall into makes them equal.
        (Float(f), Str(_)) | (Str(_), Float(f)) if f.is_nan() => false,
        // number vs number, or number vs string.
        _ => {
            // A non-numeric string vs a number compares as strings in PHP 8.
            if let Str(s) = a {
                if !host::is_numeric_string(s) {
                    return h.to_str(a) == h.to_str(b);
                }
            }
            if let Str(s) = b {
                if !host::is_numeric_string(s) {
                    return h.to_str(a) == h.to_str(b);
                }
            }
            num_eq(&h.to_number(a), &h.to_number(b))
        }
    }
}

fn num_eq(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x == y,
        _ => a.to_float() == b.to_float(),
    }
}

fn arrays_loose_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
    // Two objects are `==` when they are of the SAME class and every property is
    // loose-equal — a different pair of instances can compare equal, which is
    // exactly what separates `==` from `===` on objects. An array is never `==`
    // an object, so the mixed pair is rejected before the element walk.
    if h.is_object_value(a) || h.is_object_value(b) {
        let (Some(ca), Some(cb)) = (h.instance_class(a), h.instance_class(b)) else {
            return false;
        };
        if !ca.eq_ignore_ascii_case(&cb) {
            return false;
        }
        // `Closure` is the one class the reference gives a compare handler that
        // answers "not equal" to everything but itself: two closures built from
        // the SAME literal are `==` false, and so is a rebound copy of one.
        // Every other object — a `Generator` included, which has no visible
        // properties and so is `==` every other generator — takes the walk.
        if h.is_closure(a) {
            return matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y);
        }
        let (pa, pb) = (h.object_props(a), h.object_props(b));
        return pa.len() == pb.len()
            && pa
                .iter()
                .all(|(name, va)| pb.iter().any(|(n, vb)| n == name && loose_eq(h, va, vb)));
    }
    let (Some(pa), Some(pb)) = (h.array_pairs(a), h.array_pairs(b)) else {
        return false;
    };
    if pa.len() != pb.len() {
        return false;
    }
    // `==` on arrays: same key/value pairs, order-independent, values loose-equal.
    pa.iter().all(|(ka, va)| {
        pb.iter()
            .any(|(kb, vb)| strict_eq(h, ka, kb) && loose_eq(h, va, vb))
    })
}

/// PHP strict equality (`===`).
fn strict_eq(h: &host::PhpHost, a: &Value, b: &Value) -> bool {
    use Value::*;
    match (a, b) {
        (Int(x), Int(y)) => x == y,
        (Float(x), Float(y)) => x == y,
        (Str(x), Str(y)) => x == y,
        (Bool(x), Bool(y)) => x == y,
        (Undef, Undef) => true,
        (Obj(x), Obj(y)) => {
            // The same heap handle is always identical (same array or object
            // instance) — this also gives enum-case singletons `===` identity.
            if x == y {
                return true;
            }
            // Two distinct array handles are `===` when their keys/values match in
            // order and type; two distinct object handles are never identical.
            let (Some(pa), Some(pb)) = (h.array_pairs(a), h.array_pairs(b)) else {
                return false;
            };
            pa.len() == pb.len()
                && pa
                    .iter()
                    .zip(pb.iter())
                    .all(|((ka, va), (kb, vb))| strict_eq(h, ka, kb) && strict_eq(h, va, vb))
        }
        _ => false,
    }
}

/// PHP ordering: -1 / 0 / 1, following `zend_compare`'s operand-type table.
///
/// The table is applied in this order, which is what the reference interpreter
/// does and is load-bearing — swapping any two arms changes results:
/// 1. `null` vs string — `null` becomes `""` and the two compare as strings
///    (so `null < "0"`, which the bool rule below would call equal).
/// 2. `bool` or `null` on either side — both operands convert to bool
///    (so `null < -1`, because `false < true`).
/// 3. array vs array — fewer elements is smaller, otherwise element-wise over
///    the left operand's keys; a key missing on the right is "uncomparable"
///    and reports greater, matching `zend_hash_compare`.
/// 4. array vs anything else — the array is always greater.
/// 5. everything else — numeric unless both operands are non-numeric strings
///    (then byte comparison).
fn php_compare(h: &host::PhpHost, a: &Value, b: &Value) -> i32 {
    use Value::*;
    if let Some((a, b)) = resources_as_ids(h, a, b) {
        return php_compare(h, &a, &b);
    }
    match (a, b) {
        // 1. null vs string compares as "" vs the string.
        (Undef, Str(y)) => strcmp_i32("", y),
        (Str(x), Undef) => strcmp_i32(x, ""),
        // 2. A bool or null operand drags both sides down to bool.
        (Bool(_) | Undef, _) | (_, Bool(_) | Undef) => {
            i32::from(h.is_truthy(a)) - i32::from(h.is_truthy(b))
        }
        // 3. Two arrays compare by size, then element-wise; two objects by
        //    class, then property by property. An object against an array is
        //    the greater: `zend_std_compare_objects` cannot cast it to array.
        (Obj(_), Obj(_)) => {
            crate::stdlib::datefn::compare_dates(h, a, b).unwrap_or_else(|| {
                match (h.is_object_value(a), h.is_object_value(b)) {
                    (true, true) => compare_objects(h, a, b),
                    (true, false) => 1,
                    (false, true) => -1,
                    (false, false) => compare_arrays(h, a, b),
                }
            })
        }
        // 4. An array outranks every non-array, non-bool, non-null operand.
        (Obj(_), _) => 1,
        (_, Obj(_)) => -1,
        // A NaN double against a STRING is unordered, and `zend_compare` answers
        // 1 whichever side it is on — the test is made before the string is read
        // as a number, so `NAN <=> "1"` is 1 too, not the numeric -1
        // (`Zend/zend_operators.c:2359` and `:2366`; the numeric path itself
        // asserts the double is not a NaN at `:2288`).
        (Float(f), Str(_)) | (Str(_), Float(f)) if f.is_nan() => 1,
        (Str(x), Str(y)) => {
            if host::is_numeric_string(x) && host::is_numeric_string(y) {
                cmp_php_num(&as_php_number(h, a), &as_php_number(h, b))
            } else {
                strcmp_i32(x, y)
            }
        }
        // PHP 8: number vs string compares numerically only when the string is
        // numeric; otherwise the number is cast to a string and compared as text
        // (`"abc" <= 10` is false because "abc" > "10" lexically).
        (Str(x), Int(_) | Float(_)) => {
            if host::is_numeric_string(x) {
                cmp_php_num(&as_php_number(h, a), &as_php_number(h, b))
            } else {
                strcmp_i32(x, &h.to_str(b))
            }
        }
        (Int(_) | Float(_), Str(y)) => {
            if host::is_numeric_string(y) {
                cmp_php_num(&as_php_number(h, a), &as_php_number(h, b))
            } else {
                strcmp_i32(&h.to_str(a), y)
            }
        }
        _ => cmp_php_num(&h.to_number(a), &h.to_number(b)),
    }
}

/// Order two arrays the way `zend_hash_compare` does: the array with fewer
/// elements is smaller; at equal size, walk the left operand's keys in order and
/// compare the values. A key absent from the right operand makes the pair
/// uncomparable, which the engine reports as "left is greater"
/// (`['a'=>1] <=> ['b'=>1]` is `1`).
fn compare_arrays(h: &host::PhpHost, a: &Value, b: &Value) -> i32 {
    let (Some(pa), Some(pb)) = (h.array_pairs(a), h.array_pairs(b)) else {
        return 0;
    };
    compare_tables(h, &pa, &pb, |ka, kb| strict_eq(h, ka, kb))
}

/// `zend_hash_compare(ht1, ht2, …, ordered = 0)` over two key/value tables:
/// the body [`compare_arrays`] and the property-table path of
/// [`compare_objects`] share.
fn compare_tables<K>(
    h: &host::PhpHost,
    pa: &[(K, Value)],
    pb: &[(K, Value)],
    same_key: impl Fn(&K, &K) -> bool,
) -> i32 {
    if pa.len() != pb.len() {
        return if pa.len() < pb.len() { -1 } else { 1 };
    }
    for (ka, va) in pa {
        let Some((_, vb)) = pb.iter().find(|(kb, _)| same_key(ka, kb)) else {
            return 1;
        };
        let ord = php_compare(h, va, vb);
        if ord != 0 {
            return ord;
        }
    }
    0
}

/// `zend_std_compare_objects` (`Zend/zend_object_handlers.c`) for two objects:
/// the same instance is equal; instances of different classes are
/// UNCOMPARABLE, which the engine reports as 1 whichever side is asked. Two
/// instances of one class compare their declared properties in slot order (an
/// unset or uninitialized slot on one side only is uncomparable) unless either
/// holds a dynamic property, when the two property tables compare as arrays do.
///
/// A closure has its own handler, `zend_closure_compare`: only two
/// first-class-callable closures can be equal. An enum case has
/// `zend_objects_not_comparable`.
fn compare_objects(h: &host::PhpHost, a: &Value, b: &Value) -> i32 {
    const UNCOMPARABLE: i32 = 1;
    if matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y) {
        return 0;
    }
    let (Some(ca), Some(cb)) = (h.instance_class(a), h.instance_class(b)) else {
        return UNCOMPARABLE;
    };
    if !ca.eq_ignore_ascii_case(&cb) {
        return UNCOMPARABLE;
    }
    if h.is_closure(a) {
        let both_fake = h.closure_is_fake(a) && h.closure_is_fake(b);
        return if both_fake { 0 } else { UNCOMPARABLE };
    }
    if h.is_enum_class(&ca) {
        return UNCOMPARABLE;
    }
    let (pa, pb) = (h.object_props(a), h.object_props(b));
    if pa
        .iter()
        .chain(&pb)
        .any(|(name, _)| !h.prop_is_declared(&ca, name))
    {
        return compare_tables(h, &pa, &pb, |x, y| x == y);
    }
    // The slot order: the declarations with an initializer, then the promoted
    // constructor parameters, which `declared_prop_order` does not list.
    let mut declared = h.declared_prop_order(&ca);
    for (name, _) in pa.iter().chain(&pb) {
        if !declared.contains(name) {
            declared.push(name.clone());
        }
    }
    let slot = |p: &[(String, Value)], name: &str| {
        p.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone())
    };
    for name in &declared {
        match (slot(&pa, name), slot(&pb, name)) {
            (Some(va), Some(vb)) => {
                let ord = php_compare(h, &va, &vb);
                if ord != 0 {
                    return ord;
                }
            }
            (None, None) => {}
            _ => return UNCOMPARABLE,
        }
    }
    0
}

fn strcmp_i32(x: &str, y: &str) -> i32 {
    // Stored text orders as its bytes; an escaped byte does not (`"\xC3"` is
    // stored above `"é"` but is a prefix of it), so those compare as bytes.
    let order = if crate::bytes::has_raw(x) || crate::bytes::has_raw(y) {
        crate::bytes::to_bytes(x).cmp(&crate::bytes::to_bytes(y))
    } else {
        x.cmp(y)
    };
    match order {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// `ZEND_THREEWAY_COMPARE`: equal is 0, less is -1, and everything else — which
/// includes an UNORDERED pair, where one side is NaN — is 1.
///
/// Reporting 0 for unordered (what this used to do) made `NAN <=> NAN` answer 0
/// and, through `cmp_bool`, made `NAN <= NAN` true.
fn cmp_f64(x: f64, y: f64) -> i32 {
    if x == y {
        0
    } else if x < y {
        -1
    } else {
        1
    }
}

/// Whether `<`/`>`/`<=`/`>=` must answer `false` outright for this operand pair.
///
/// The relational operators compare the two doubles directly rather than
/// testing `zend_compare`'s result, so a NaN operand makes all four false —
/// `NAN >= NAN` included, which the 3-way answer of 1 would otherwise make
/// true. A bool, null, or array operand is decided before any of that (`NAN >
/// false` is true, `NAN < []` is true), so those pairs are never unordered.
///
/// Ordered by how often each test decides it: every comparison in a program
/// runs this, and almost none of them has a float operand at all, so the NaN
/// test comes first and rejects the whole thing in one match per operand.
#[inline]
fn is_unordered(a: &Value, b: &Value) -> bool {
    #[inline]
    fn is_nan(v: &Value) -> bool {
        matches!(v, Value::Float(f) if f.is_nan())
    }
    if !is_nan(a) && !is_nan(b) {
        return false;
    }
    #[inline]
    fn decided_by_type(v: &Value) -> bool {
        matches!(v, Value::Bool(_) | Value::Undef | Value::Obj(_))
    }
    !decided_by_type(a) && !decided_by_type(b)
}

/// A comparison operand read as a NUMBER, using PHP's numeric-string grammar.
///
/// `Value::to_float` parses a string with Rust's rules, which reject the
/// surrounding whitespace PHP 8 accepts and answer `0.0` instead of failing.
/// That silent zero is what made `" 1" == "0"` true and `" 1" == "1"` false.
/// A string with no complete numeric reading falls back to the host's
/// leading-prefix conversion, which is what the non-numeric arms already use.
fn as_php_number(h: &host::PhpHost, v: &Value) -> Value {
    match v {
        Value::Str(s) => host::parse_php_number_full(s).unwrap_or_else(|| h.to_number(v)),
        _ => h.to_number(v),
    }
}

/// Order two numeric operands the way `zend_compare` does.
///
/// Two integers compare AS integers. Widening them to `f64` first drops the low
/// bits of anything past 2^53, so `PHP_INT_MAX <=> PHP_INT_MAX - 1` answered 0
/// and `sort()` over large integers came back in an arbitrary order.
fn cmp_php_num(a: &Value, b: &Value) -> i32 {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => match x.cmp(y) {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        },
        _ => cmp_f64(a.to_float(), b.to_float()),
    }
}

// ── the strict numeric hook ──────────────────────────────────────────────────

/// The operator PHP names in `Unsupported operand types: X <sym> Y`.
///
/// `Neg` reports `*` because the reference lowers unary minus to a
/// multiplication by `-1`: `-"g"` says `string * int`, not `string - int`.
fn op_symbol(op: NumOp) -> &'static str {
    match op {
        NumOp::Add => "+",
        NumOp::Sub => "-",
        NumOp::Mul | NumOp::Neg => "*",
        NumOp::Div => "/",
        NumOp::Mod => "%",
        NumOp::Pow => "**",
        _ => "?",
    }
}

/// Record a `TypeError` for `a <sym> b` and return the message to stop the VM.
///
/// The pending exception is the real signal — `run_chunk_on` turns this stop
/// into the clean halt that `catch` can see — so the returned string is only
/// ever the text of a fatal that nothing caught.
pub(crate) fn unsupported_operands(sym: &str, a: &Value, b: &Value) -> String {
    let msg = with_host(|h| {
        format!(
            "Unsupported operand types: {} {sym} {}",
            host::arith_type_name(h, a),
            host::arith_type_name(h, b)
        )
    });
    let _ = pending_php_throw("TypeError", &msg);
    msg
}

/// Coerce one operand of `a <sym> b` under PHP 8's rules, raising the
/// reference's diagnostics on the way.
///
/// Callers must resolve the left operand before the right, because the order is
/// observable: `"5g" + "g"` warns once and *then* throws, while `"g" + "5g"`
/// throws without warning at all.
pub(crate) fn coerce_arith(sym: &str, a: &Value, b: &Value, left: bool) -> Result<Value, String> {
    let v = if left { a } else { b };
    match host::classify_arith(v) {
        host::ArithOperand::Numeric(n) => Ok(n),
        host::ArithOperand::Leading(n) => {
            with_host(|h| h.warn("A non-numeric value encountered"));
            Ok(n)
        }
        host::ArithOperand::Unsupported => Err(unsupported_operands(sym, a, b)),
    }
}

/// Both operands of a binary arithmetic operator, left resolved first.
pub(crate) fn coerce_arith_pair(sym: &str, a: &Value, b: &Value) -> Result<(Value, Value), String> {
    let an = coerce_arith(sym, a, b, true)?;
    let bn = coerce_arith(sym, a, b, false)?;
    Ok((an, bn))
}

/// Supplies PHP arithmetic for the native `Add`/`Sub`/`Mul`/`Negate` ops when an
/// operand is non-numeric (string/array/bool/null) or an `i64` op overflows.
///
/// `lines` is the running chunk's line table, captured per VM so a warning
/// raised here reports the operator's own line; `ip` indexes it directly.
pub fn numeric_hook_sited(call: NumericCall<'_>, lines: &[u32]) -> Result<Value, String> {
    let (op, a, b) = (call.op, call.a, call.b);
    // `[..] + [..]` is array union, not arithmetic, and must not reach the
    // operand rules below — the reference keeps the left operand's entries and
    // adds only the right's keys that are missing.
    if op == NumOp::Add && with_host(|h| h.is_array(a) && h.is_array(b)) {
        return Ok(array_union(a, b));
    }
    let line = lines.get(call.ip).copied().unwrap_or(0);
    host::set_warn_line(line);
    // The frame line too: an operand the operator refuses is a `TypeError`,
    // and an exception takes its line from the frame, which no call op may
    // have stamped yet — `function f() { return 1 + []; }` would say line 0.
    if line != 0 {
        with_host(|h| h.set_cur_line(line));
    }
    // A relational operator is NOT arithmetic: PHP orders strings as strings,
    // arrays by size then element-wise, and a bool against anything by
    // truthiness. fusevm only asks about the pairs it will not answer itself —
    // an `Int`/`Int` pair never reaches here — so this is PHP's own comparison
    // over exactly the operands the native path declined.
    if let Some((swap, want)) = relational(op) {
        // An object with `__toString` compared against a string is cast first,
        // as `zend_compare` does — the same rule `b_loose_eq` and `b_spaceship`
        // apply, and the four relational operators reach it through here rather
        // than through `cmp_bool` because they are lowered natively.
        let cast = cast_for_compare(a, b);
        let (a, b) = match &cast {
            Some((x, y)) => (x, y),
            None => (a, b),
        };
        // An UNORDERED pair answers false to all four, which is not the same as
        // the three-way comparison's answer: `NAN <=> 1` is 1, while `NAN > 1`
        // is false. This is the guard `cmp_bool` makes for the same reason.
        if is_unordered(a, b) {
            return Ok(Value::bool(false));
        }
        let (a, b) = if swap { (b, a) } else { (a, b) };
        let ord = with_host(|h| php_compare(h, a, b));
        return Ok(Value::bool(want(ord)));
    }
    let sym = op_symbol(op);
    if op == NumOp::Neg {
        // Unary minus is `$x * -1`, so the reported right-hand type is `int`.
        let an = coerce_arith(sym, a, &Value::Int(-1), true)?;
        return Ok(match an {
            Value::Int(n) => n
                .checked_neg()
                .map(Value::int)
                .unwrap_or(Value::float(-(n as f64))),
            Value::Float(f) => Value::float(-f),
            _ => Value::int(0),
        });
    }
    let (an, bn) = coerce_arith_pair(sym, a, b)?;
    Ok(arith(op, an, bn))
}

/// Whether the operands are swapped, and the test applied to the three-way comparison.
type Relation = (bool, fn(i32) -> bool);

/// Whether a relational [`NumOp`] exchanges its operands, and the test it then
/// applies to the three-way comparison; `None` for an op that is arithmetic
/// rather than relational. `>` and `>=` are `<` and `<=` swapped, as
/// [`cmp_bool`] explains.
fn relational(op: NumOp) -> Option<Relation> {
    Some(match op {
        NumOp::Lt => (false, |o: i32| o < 0),
        NumOp::Gt => (true, |o: i32| o < 0),
        NumOp::Le => (false, |o: i32| o <= 0),
        NumOp::Ge => (true, |o: i32| o <= 0),
        _ => return None,
    })
}

/// PHP's `+` on two arrays: the left operand's entries win, and the right
/// contributes only the keys the left does not already have.
fn array_union(a: &Value, b: &Value) -> Value {
    with_host(|h| {
        let pa = h.array_pairs(a).unwrap_or_default();
        let pb = h.array_pairs(b).unwrap_or_default();
        let out = h.new_array();
        for (k, v) in &pa {
            h.arr_set_key(&out, k, v.clone());
        }
        for (k, v) in &pb {
            if !pa.iter().any(|(ka, _)| same_key(ka, k)) {
                h.arr_set_key(&out, k, v.clone());
            }
        }
        out
    })
}

/// Array keys are already normalized to `Int`/`Str`, so identity is a plain
/// comparison of those two shapes.
fn same_key(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => x == y,
        (Value::Str(x), Value::Str(y)) => x == y,
        _ => false,
    }
}

fn arith(op: NumOp, an: Value, bn: Value) -> Value {
    if let (Value::Int(x), Value::Int(y)) = (&an, &bn) {
        let r = match op {
            NumOp::Add => x.checked_add(*y),
            NumOp::Sub => x.checked_sub(*y),
            NumOp::Mul => x.checked_mul(*y),
            _ => None,
        };
        if let Some(v) = r {
            return Value::int(v);
        }
    }
    let (x, y) = (an.to_float(), bn.to_float());
    Value::float(match op {
        NumOp::Add => x + y,
        NumOp::Sub => x - y,
        NumOp::Mul => x * y,
        NumOp::Div => x / y,
        NumOp::Mod => x % y,
        NumOp::Pow => x.powf(y),
        _ => 0.0,
    })
}

// ── PHP standard library (reached through CALL) ──────────────────────────────

pub(crate) fn arg(args: &[Value], i: usize) -> Value {
    args.get(i).cloned().unwrap_or(Value::Undef)
}

/// Library functions whose parameters PHP declares as `string`, so an object
/// argument with a `__toString` method is converted before the call — PHP does
/// this from the function's arginfo, and this list is that arginfo.
///
/// It is an allow-list on purpose. The complement — listing the functions that
/// legitimately *take* an object (`get_class`, `var_dump`, `json_encode`, every
/// callable-taking function, …) — would turn one forgotten entry into an object
/// silently flattened to a string. Here a forgotten entry only means
/// `__toString` is not applied to that function's arguments yet, which shows up
/// as a visible difference rather than a wrong answer.
const STRING_PARAM_BUILTINS: &[&str] = &[
    "addslashes",
    "base64_decode",
    "base64_encode",
    "bin2hex",
    "chunk_split",
    "crc32",
    // `exit`'s `$status` is `string|int`, so a Stringable object satisfies it by
    // converting — `exit($obj)` prints what `__toString` returns.
    "exit",
    "explode",
    "hex2bin",
    "html_entity_decode",
    "htmlentities",
    "htmlspecialchars",
    "htmlspecialchars_decode",
    "lcfirst",
    "levenshtein",
    "ltrim",
    "md5",
    "metaphone",
    "nl2br",
    "ord",
    "preg_quote",
    "printf",
    "quotemeta",
    "rawurldecode",
    "rawurlencode",
    "rtrim",
    "sha1",
    "similar_text",
    "soundex",
    "sprintf",
    "str_contains",
    "str_ends_with",
    "str_pad",
    "str_repeat",
    "str_shuffle",
    "str_split",
    "str_starts_with",
    "str_word_count",
    "strcasecmp",
    "strcmp",
    "stripos",
    "stripslashes",
    "stristr",
    "strlen",
    "strnatcasecmp",
    "strnatcmp",
    "strncasecmp",
    "strncmp",
    "strpbrk",
    "strpos",
    "strrchr",
    "strrev",
    "strripos",
    "strrpos",
    "strstr",
    "strtolower",
    "strtoupper",
    "strtr",
    "substr",
    "substr_count",
    "substr_replace",
    "trim",
    "ucfirst",
    "ucwords",
    "urldecode",
    "urlencode",
    "vprintf",
    "vsprintf",
    "wordwrap",
];

/// Apply `__toString` to the arguments of a string-parameter library function.
///
/// Runs before any host borrow is taken: converting calls the object's method,
/// which re-enters the host. Costs one list lookup unless an object argument is
/// actually present.
fn coerce_stringable_args(lname: &str, args: &[Value]) -> Option<Vec<Value>> {
    if !args.iter().any(|a| matches!(a, Value::Obj(_))) || !STRING_PARAM_BUILTINS.contains(&lname) {
        return None;
    }
    Some(
        args.iter()
            .map(|a| {
                let stringable = with_host(|h| {
                    h.object_class(a)
                        .is_some_and(|c| h.class_has_method(&c, "__tostring"))
                });
                if stringable {
                    Value::str(host::to_str_ext(a))
                } else {
                    a.clone()
                }
            })
            .collect(),
    )
}

/// Separates the exception class from the message inside a tagged library error.
/// U+0001 cannot occur in a PHP diagnostic, so a plain error message can never be
/// mistaken for a tagged one.
const THROW_TAG: &str = "\u{1}throw\u{1}";

/// Report a library argument error as the PHP exception it really is.
///
/// A standard-library function that rejects its arguments does not abort the
/// process in PHP — it THROWS, catchably, and the throw carries a stack trace
/// whose `#0` frame is the library call itself. Library functions here return
/// `Result<Value, String>` and have no VM handle, so the class travels back in
/// the error string under `THROW_TAG` and [`call_library`] turns it into a real
/// throw at the one place that still knows the function name and its arguments —
/// the two things the trace frame needs.
///
/// ```ignore
/// return Err(throws("ValueError", "range(): Argument #3 ($step) must be …"));
/// ```
pub fn throws(class: &str, message: impl std::fmt::Display) -> String {
    format!("{THROW_TAG}{class}{THROW_TAG}{message}")
}

/// Split a tagged library error back into `(class, message)`; `None` for an
/// ordinary error string, which stays a scaffold-level failure.
pub fn untag_throw(e: &str) -> Option<(&str, &str)> {
    e.strip_prefix(THROW_TAG)?.split_once(THROW_TAG)
}

/// Marker for a throw that carries a `getCode()` as well as a message — see
/// [`throws_code`].
const CODE_THROW_TAG: &str = "\u{1}cthrow\u{1}";

/// [`throws`] for an exception whose `getCode()` is meaningful. `JsonException`
/// is the case that forces it: its code is the `JSON_ERROR_*` constant, and a
/// caller distinguishes a syntax error from a depth error by reading it.
pub fn throws_code(class: &str, code: i64, message: impl std::fmt::Display) -> String {
    format!("{CODE_THROW_TAG}{class}{CODE_THROW_TAG}{code}{CODE_THROW_TAG}{message}")
}

/// Split a [`throws_code`] error back into `(class, code, message)`.
pub fn untag_throw_code(e: &str) -> Option<(&str, i64, &str)> {
    let rest = e.strip_prefix(CODE_THROW_TAG)?;
    let (class, rest) = rest.split_once(CODE_THROW_TAG)?;
    let (code, message) = rest.split_once(CODE_THROW_TAG)?;
    Some((class, code.parse().ok()?, message))
}

/// Marker for a library failure the reference reports BELOW the exception
/// machinery — see [`fatals`].
const FATAL_TAG: &str = "\u{1}lfatal\u{1}";

/// Tag a library failure as an uncatchable `Fatal error` rather than a throw.
///
/// A handful of engine failures are not Throwables at all: an allocation whose
/// size arithmetic overflows is reported straight to the output and stops the
/// program, so no `try`/`catch` can intercept it. Rendering one as a
/// `ValueError` would let user code swallow something the reference never lets
/// it swallow.
pub fn fatals(message: impl std::fmt::Display) -> String {
    format!("{FATAL_TAG}{message}")
}

/// Split a [`fatals`] error back into its message.
pub fn untag_fatal(e: &str) -> Option<&str> {
    e.strip_prefix(FATAL_TAG)
}

/// Marker for a throw raised *at* the call site rather than inside the callee —
/// see [`throws_bare`].
const BARE_THROW_TAG: &str = "\u{1}bthrow\u{1}";

/// [`throws`] for a failure the engine reports from the CALLING frame, with no
/// trace entry for the function named in the message.
///
/// "Call to undefined function f()" is the case: there is no `f` to enter, so
/// PHP's trace starts at the caller. Routing it through [`throws`] would invent
/// a `#0 f()` frame the reference does not print.
pub fn throws_bare(class: &str, message: impl std::fmt::Display) -> String {
    format!("{BARE_THROW_TAG}{class}{BARE_THROW_TAG}{message}")
}

/// Split a [`throws_bare`] error back into `(class, message)`.
pub fn untag_bare_throw(e: &str) -> Option<(&str, &str)> {
    e.strip_prefix(BARE_THROW_TAG)?.split_once(BARE_THROW_TAG)
}

/// Dispatch a PHP library function by (case-insensitive) name.
///
/// An argument error comes back as a [`throws`]-tagged `Err`, which
/// `host::call_function` turns into a real, catchable exception thrown from a
/// frame naming this call; every other `Err` is a scaffold-level failure with no
/// PHP equivalent. The decoding deliberately lives in the CALLER, which still
/// owns the argument list the trace frame has to print.
pub fn call_library(name: &str, args: &[Value]) -> Result<Value, String> {
    // Borrowed rather than allocated when the name is already lower case, which
    // is how a PHP program spells one essentially always.
    let lname = crate::argsig::lower_name(name);
    let coerced = coerce_stringable_args(&lname, args);
    let args: &[Value] = coerced.as_deref().unwrap_or(args);
    // A builtin with a by-reference OUT parameter publishes its value for the
    // call site to write back (see `BYREF_BUILTINS`); clearing first means a
    // call that writes none cannot be read as having written the last one's.
    with_host(|h| h.byref_out_clear());
    let v = match lname.as_ref() {
        // `exit` / `die` — end the request. PHP 8.4 turned both into real
        // functions (`function_exists("exit")` answers true), and the scanner
        // folds `die` onto `exit`, so both spellings arrive here under the one
        // name and every diagnostic quotes `exit()`.
        //
        // `$status` is declared `string|int`: an int becomes the process status,
        // a STRING is printed and the status is 0, a bool and a float narrow to
        // int (a float with a fraction raising the same lost-precision
        // deprecation any other int-only position raises), an explicit null is
        // deprecated and reads as 0, and anything else is a `TypeError`.
        //
        // Nothing is torn down here. Recording the status and unwinding is what
        // the reference does too — an open `ob_start` buffer still flushes on
        // the way out, and only then does the CLI wrapper take the status as the
        // process exit code.
        "exit" | "die" => {
            let status = match args.first() {
                None => 0,
                Some(Value::Undef) => {
                    with_host(|h| {
                        h.deprecated(
                            "exit(): Passing null to parameter #1 ($status) of type string|int \
                             is deprecated",
                        )
                    });
                    0
                }
                Some(Value::Str(s)) => {
                    with_host(|h| h.write_out(s));
                    0
                }
                Some(v @ (Value::Int(_) | Value::Bool(_) | Value::Float(_))) => int_operand(v, v),
                Some(other) => {
                    let t = with_host(|h| crate::stdlib::types::debug_type(h, other));
                    return Err(throws(
                        "TypeError",
                        format!(
                            "exit(): Argument #1 ($status) must be of type string|int, {t} given"
                        ),
                    ));
                }
            };
            // Only the low byte reaches the shell, and that is the reference's
            // arithmetic too: `exit(300)` leaves 44 and `exit(256)` leaves 0.
            host::set_pending_exit((status & 0xFF) as i32);
            Value::Undef
        }
        "strlen" => Value::int(with_host(|h| {
            crate::bytes::byte_len(&h.to_str(&arg(args, 0))) as i64
        })),
        // `count` accepts an array or a `Countable`, and NOTHING else: PHP 8
        // rejects a scalar with a TypeError rather than answering 1.
        "count" | "sizeof" => {
            let a = arg(args, 0);
            // `$mode` is COUNT_NORMAL (0) or COUNT_RECURSIVE (1) and nothing
            // else — any other value is a ValueError, checked before the
            // subject so `count(1, 99)` reports the mode.
            let mode = args.get(1).map(crate::host::long_of).unwrap_or(0);
            if mode != 0 && mode != 1 {
                return Err(throws(
                    "ValueError",
                    format!(
                        "{name}(): Argument #2 ($mode) must be either COUNT_NORMAL or COUNT_RECURSIVE"
                    ),
                ));
            }
            if with_host(|h| h.is_array(&a)) {
                Value::int(with_host(|h| {
                    if mode == 1 {
                        count_recursive(h, &a)
                    } else {
                        h.array_len(&a)
                    }
                }))
            } else if let Some(class) = with_host(|h| {
                h.object_class(&a)
                    .filter(|c| h.class_is_a_pub(c, "Countable"))
            }) {
                let n = host::call_method(&class, "count", Some(a), Vec::new())?;
                Value::int(n.to_int())
            } else {
                // `type_name_for_error`, not `debug_type`: a diagnostic names a
                // boolean by its VALUE, so `count(true)` reports `true given`.
                let t = with_host(|h| h.type_name_for_error(&a));
                return Err(throws(
                    "TypeError",
                    format!(
                        "{name}(): Argument #1 ($value) must be of type Countable|array, {t} given"
                    ),
                ));
            }
        }
        "strtoupper" => with_host(|h| Value::str(ascii_upper(&h.to_str(&arg(args, 0))))),
        "strtolower" => with_host(|h| Value::str(ascii_lower(&h.to_str(&arg(args, 0))))),
        "ucfirst" => with_host(|h| Value::str(ucfirst(&h.to_str(&arg(args, 0))))),
        "trim" => with_host(|h| php_trim(h, args, true, true)),
        "ltrim" => with_host(|h| php_trim(h, args, true, false)),
        "rtrim" | "chop" => with_host(|h| php_trim(h, args, false, true)),
        "str_repeat" => {
            let n = host::long_of(&arg(args, 1));
            if n < 0 {
                return Err(throws(
                    "ValueError",
                    "str_repeat(): Argument #2 ($times) must be greater than or equal to 0",
                ));
            }
            // `zend_string_safe_alloc(len, times, 0, 0)` sizes the result as
            // `len * times + 32` (the 32 is the interned-string header). When
            // that arithmetic overflows `size_t` the engine stops with a fatal
            // naming the three operands — not a ValueError, and not catchable.
            let src = with_host(|h| h.to_str(&arg(args, 0)));
            let len = src.len();
            if len
                .checked_mul(n as usize)
                .and_then(|p| p.checked_add(32))
                .is_none()
            {
                return Err(fatals(format!(
                    "Possible integer overflow in memory allocation ({len} * {n} + 32)"
                )));
            }
            Value::str(src.repeat(n as usize))
        }
        "strrev" => with_host(|h| {
            let mut b = crate::bytes::to_bytes(&h.to_str(&arg(args, 0))).into_owned();
            b.reverse();
            Value::str(crate::bytes::from_bytes(&b))
        }),
        "wordwrap" => with_host(|h| php_wordwrap(h, args))?,
        "substr" => with_host(|h| Value::str(php_substr(&h.to_str(&arg(args, 0)), args))),
        "strpos" => with_host(|h| php_strpos(h, args))?,
        "str_replace" => with_host(|h| php_str_replace(h, args, false))?,
        "str_ireplace" => with_host(|h| php_str_replace(h, args, true))?,
        // The `(array)` / `(object)` casts, which have no PHP-callable spelling.
        "__cast_array" => with_host(|h| php_cast_array(h, &arg(args, 0))),
        "__cast_object" => php_cast_object(&arg(args, 0))?,
        // `abs(PHP_INT_MIN)` has no integer answer — its magnitude is one past
        // `PHP_INT_MAX` — so it widens to a float, the same way `-PHP_INT_MIN`
        // does. `n.abs()` alone panics on it in debug Rust.
        "abs" => with_host(|h| match h.to_number(&arg(args, 0)) {
            Value::Int(i64::MIN) => Value::float(-(i64::MIN as f64)),
            Value::Int(n) => Value::int(n.abs()),
            Value::Float(f) => Value::float(f.abs()),
            other => other,
        }),
        "floor" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().floor())),
        "ceil" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().ceil())),
        "sqrt" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().sqrt())),
        "round" => with_host(|h| {
            let x = h.to_number(&arg(args, 0)).to_float();
            // `ZEND_LONG_INT_OVFL`/`UDFL`: a `$precision` outside the int range
            // SATURATES rather than wrapping, so `round(1.5, 2147483648)` is
            // `round(1.5, INT_MAX)` and not `round(1.5, INT_MIN)`.
            let p = args.get(1).map(crate::host::long_of).unwrap_or(0);
            let places = p.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32;
            let mode = args.get(2).map(crate::host::long_of).unwrap_or(1);
            Value::float(php_round(x, places, mode))
        }),
        "intval" => with_host(|h| {
            let v = arg(args, 0);
            match args.get(1) {
                // A base only applies to strings, and base 10 keeps the ordinary
                // numeric-string reading so `intval("1e3", 10)` is still 1000.
                Some(b)
                    if !matches!(b, Value::Undef)
                        && matches!(v, Value::Str(_))
                        && b.to_int() != 10 =>
                {
                    Value::int(intval_base(&h.to_str(&v), b.to_int()))
                }
                _ => Value::int(h.to_int_cast(&v)),
            }
        }),
        "floatval" | "doubleval" => {
            with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float()))
        }
        // `(string)$x` desugars to `strval($x)`, so this is the explicit cast too.
        "strval" => Value::str(host::to_str_ext(&arg(args, 0))),
        "max" => with_host(|h| fold_cmp(h, args, true))?,
        "min" => with_host(|h| fold_cmp(h, args, false))?,
        "gettype" => with_host(|h| Value::str(h.type_name(&arg(args, 0)).to_string())),
        // `settype($var, $type)` converts IN PLACE through its by-reference first
        // parameter (published for the call site to write back) and returns true.
        "settype" => php_settype(args)?,
        "is_array" => with_host(|h| Value::bool(h.is_array(&arg(args, 0)))),
        "is_int" | "is_integer" | "is_long" => Value::bool(matches!(arg(args, 0), Value::Int(_))),
        "is_float" | "is_double" => Value::bool(matches!(arg(args, 0), Value::Float(_))),
        "is_string" => Value::bool(matches!(arg(args, 0), Value::Str(_))),
        "is_bool" => Value::bool(matches!(arg(args, 0), Value::Bool(_))),
        "is_null" => Value::bool(matches!(arg(args, 0), Value::Undef)),
        "is_numeric" => Value::bool(match arg(args, 0) {
            Value::Int(_) | Value::Float(_) => true,
            Value::Str(s) => host::is_numeric_string(&s),
            _ => false,
        }),
        "implode" | "join" => php_implode(&lname, args)?,
        "explode" => with_host(|h| php_explode(h, args))?,
        // A loose search that may meet an object/string pair casts it through
        // `__toString` first, which runs user code outside the host borrow.
        "in_array" | "array_search" | "array_keys" if needs_stringable_search(&lname, args) => {
            let (needle, hay) = if lname == "array_keys" {
                (arg(args, 1), arg(args, 0))
            } else {
                (arg(args, 0), arg(args, 1))
            };
            let hits = loose_search_hits(&needle, &hay, lname != "array_keys");
            match &*lname {
                "in_array" => Value::bool(!hits.is_empty()),
                "array_search" => hits.into_iter().next().unwrap_or(Value::bool(false)),
                _ => with_host(|h| {
                    let out = h.new_array();
                    for k in hits {
                        h.arr_push_auto(&out, k);
                    }
                    out
                }),
            }
        }
        "in_array" => with_host(|h| php_in_array(h, args)),
        // With a filter value, only the keys whose value equals it — loosely,
        // or strictly when `$strict` is true.
        "array_keys" if args.len() >= 2 => with_host(|h| {
            let needle = arg(args, 1);
            let strict = h.is_truthy(&arg(args, 2));
            let keys: Vec<Value> = h
                .array_pairs(&arg(args, 0))
                .unwrap_or_default()
                .into_iter()
                .filter(|(_, v)| {
                    if strict {
                        strict_eq(h, v, &needle)
                    } else {
                        loose_eq(h, v, &needle)
                    }
                })
                .map(|(k, _)| k)
                .collect();
            let out = h.new_array();
            for k in keys {
                h.arr_push_auto(&out, k);
            }
            out
        }),
        "array_keys" => with_host(|h| h.array_keys(&arg(args, 0))),
        "array_values" => with_host(|h| php_array_values(h, &arg(args, 0))),
        "array_push" => with_host(|h| php_array_push(h, args))?,
        "range" => with_host(|h| php_range(h, args))?,
        "sprintf" => with_host(|h| php_sprintf(h, args, false)).map(Value::str)?,
        "printf" => {
            let s = with_host(|h| php_sprintf(h, args, false))?;
            with_host(|h| h.write_out(&s));
            Value::int(s.len() as i64)
        }
        "print_r" => with_debug_info(&args[..args.len().min(1)], |h| {
            let s = php_print_r(h, &arg(args, 0), 0, &mut host::Visiting::default());
            if args.get(1).map(|v| h.is_truthy(v)).unwrap_or(false) {
                Value::str(s)
            } else {
                h.write_out(&s);
                Value::bool(true)
            }
        })
        .unwrap_or(Value::Undef),
        "var_dump" => with_debug_info(args, |h| {
            for a in args {
                let s = php_var_dump(h, a, 0);
                h.write_out(&s);
            }
            Value::Undef
        })
        .unwrap_or(Value::Undef),

        // ── strings ──────────────────────────────────────────────────────
        "str_split" => with_host(|h| php_str_split(h, args))?,
        "str_pad" => with_host(|h| php_str_pad(h, args)).map(Value::str)?,
        // Byte comparisons: `"\xA9"` is inside `"é"` and ends it.
        "str_contains" => {
            let (hay, needle) = (bytes_arg(args, 0), bytes_arg(args, 1));
            Value::bool(crate::bytes::find(&hay, &needle).is_some())
        }
        "str_starts_with" => Value::bool(bytes_arg(args, 0).starts_with(&bytes_arg(args, 1))),
        "str_ends_with" => Value::bool(bytes_arg(args, 0).ends_with(&bytes_arg(args, 1))),
        "ucwords" => with_host(|h| {
            let seps = match args.get(1) {
                Some(v) if !matches!(v, Value::Undef) => h.to_str(v),
                _ => " \t\r\n\x0c\x0b".to_string(),
            };
            Value::str(ucwords(&h.to_str(&arg(args, 0)), &seps))
        }),
        "lcfirst" => with_host(|h| Value::str(lcfirst(&h.to_str(&arg(args, 0))))),
        "number_format" => with_host(|h| Value::str(php_number_format(h, args))),
        // Same escaper; `htmlentities` additionally maps every named entity of
        // the document type, which is the ONLY difference between the two.
        "htmlspecialchars" | "htmlentities" => with_host(|h| {
            let s = h.to_str(&arg(args, 0));
            let flags = match args.get(1) {
                Some(v) if !matches!(v, Value::Undef) => h.to_number(v).to_int(),
                _ => crate::stdlib::textx::ENT_DEFAULT,
            };
            crate::stdlib::textx::check_html_charset(h, &lname, args.get(2));
            let named = lname == "htmlentities";
            // An invalid UTF-8 unit (as `php_next_utf8_char` groups them):
            // U+FFFD under ENT_SUBSTITUTE (the default), dropped under
            // ENT_IGNORE, and otherwise the whole result is the empty string.
            // The encoder works on decoded text, so the result is stored back
            // as text (a character in the escape range stays four bytes).
            let s = if crate::bytes::has_raw(&s) {
                let units = crate::bytes::php_utf8_units(&s);
                if flags & 8 != 0 {
                    units.into_iter().map(|u| u.unwrap_or('\u{FFFD}')).collect()
                } else if flags & 4 != 0 || units.iter().all(Option::is_some) {
                    units.into_iter().flatten().collect()
                } else {
                    return Value::str(String::new());
                }
            } else {
                s
            };
            let encoded = crate::stdlib::textx::html_encode(&s, flags, named);
            Value::str(crate::bytes::from_text(&encoded).into_owned())
        }),
        "strcmp" => with_host(|h| {
            let (a, b) = (h.to_str(&arg(args, 0)), h.to_str(&arg(args, 1)));
            Value::int(binary_strcmp(
                &crate::bytes::to_bytes(&a),
                &crate::bytes::to_bytes(&b),
            ))
        }),
        "strcasecmp" => with_host(|h| {
            let a = ascii_lower(&h.to_str(&arg(args, 0)));
            let b = ascii_lower(&h.to_str(&arg(args, 1)));
            Value::int(binary_strcmp(
                &crate::bytes::to_bytes(&a),
                &crate::bytes::to_bytes(&b),
            ))
        }),
        "strncmp" => with_host(|h| {
            let a = h.to_str(&arg(args, 0));
            let b = h.to_str(&arg(args, 1));
            let n = host::long_of(&arg(args, 2)).max(0) as usize;
            let (ab, bb) = (
                (&*crate::bytes::to_bytes(&a)),
                (&*crate::bytes::to_bytes(&b)),
            );
            Value::int(binary_strcmp(
                &ab[..n.min(ab.len())],
                &bb[..n.min(bb.len())],
            ))
        }),
        "substr_compare" => return with_host(|h| php_substr_compare(h, args)),
        // `str_word_count` is served by `stdlib::misc`, which implements the
        // `$format`/`$characters` arguments; it is intentionally not handled here
        // so the full version wins (this core arm was a count-only stub).
        "chr" => with_host(|h| {
            let raw = h.to_number(&arg(args, 0)).to_int();
            // The wrap still happens — the reference only DEPRECATES relying on
            // it, it does not refuse the call.
            if !(0..=255).contains(&raw) {
                h.deprecated(
                    "chr(): Providing a value not in-between 0 and 255 is deprecated, this \
                     is because a byte value must be in the [0, 255] interval. The value \
                     used will be constrained using % 256",
                );
            }
            let n = raw.rem_euclid(256) as u8;
            Value::str(crate::bytes::from_bytes(&[n]))
        }),
        "ord" => with_host(|h| {
            let s = h.to_str(&arg(args, 0));
            if s.is_empty() {
                h.deprecated("ord(): Providing an empty string is deprecated");
            }
            Value::int(crate::bytes::to_bytes(&s).first().copied().unwrap_or(0) as i64)
        }),
        "dechex" => with_host(|h| Value::str(format!("{:x}", h.to_number(&arg(args, 0)).to_int()))),
        "bin2hex" => with_host(|h| {
            let s = h.to_str(&arg(args, 0));
            Value::str(
                crate::bytes::to_bytes(&s)
                    .iter()
                    .map(|b| format!("{b:02x}"))
                    .collect::<String>(),
            )
        }),

        // ── math ─────────────────────────────────────────────────────────
        "pow" => php_pow(args),
        "intdiv" => return php_intdiv(args),
        "fmod" => with_host(|h| {
            Value::float(
                h.to_number(&arg(args, 0)).to_float() % h.to_number(&arg(args, 1)).to_float(),
            )
        }),
        "sin" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().sin())),
        "cos" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().cos())),
        "tan" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().tan())),
        "exp" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().exp())),
        "log" => with_host(|h| {
            let x = h.to_number(&arg(args, 0)).to_float();
            match args.get(1) {
                Some(b) if !matches!(b, Value::Undef) => {
                    Value::float(x.log(h.to_number(b).to_float()))
                }
                _ => Value::float(x.ln()),
            }
        }),
        "log10" => with_host(|h| Value::float(h.to_number(&arg(args, 0)).to_float().log10())),
        "pi" => Value::float(std::f64::consts::PI),

        // ── arrays ───────────────────────────────────────────────────────
        "array_merge" => with_host(|h| php_array_merge(h, args)),
        "array_map" => return php_array_map(args),
        "array_filter" => return php_array_filter(args),
        "array_reduce" => return php_array_reduce(args),
        "array_slice" => with_host(|h| php_array_slice(h, args)),
        "array_reverse" => with_host(|h| php_array_reverse(h, args)),
        "array_sum" => with_host(|h| php_array_fold(h, &arg(args, 0), false)),
        "array_product" => with_host(|h| php_array_fold(h, &arg(args, 0), true)),
        "array_flip" => with_host(|h| php_array_flip(h, &arg(args, 0))),
        // SORT_STRING over an object with `__toString` compares what it
        // returns, which is user code: the strings are taken outside the borrow.
        "array_unique" if unique_needs_tostring(args) => {
            let pairs = with_host(|h| h.array_pairs(&arg(args, 0))).unwrap_or_default();
            let strs: Vec<String> = pairs.iter().map(|(_, v)| host::to_str_ext(v)).collect();
            with_host(|h| {
                let out = h.new_array();
                let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
                for ((k, v), s) in pairs.into_iter().zip(strs) {
                    if seen.insert(s) {
                        h.arr_set_key(&out, &k, v);
                    }
                }
                out
            })
        }
        "array_unique" => with_host(|h| php_array_unique(h, args)),
        "array_key_exists" | "key_exists" => with_host(|h| php_array_key_exists(h, args))?,
        "array_search" => with_host(|h| php_array_search(h, args)),
        // The sort family takes an optional `SORT_*` flags argument in position 1.
        "sort" => with_host(|h| php_sort(h, &arg(args, 0), false, sort_flags(args))),
        "rsort" => with_host(|h| php_sort(h, &arg(args, 0), true, sort_flags(args))),
        "asort" => with_host(|h| php_asort(h, &arg(args, 0), false, sort_flags(args))),
        "arsort" => with_host(|h| php_asort(h, &arg(args, 0), true, sort_flags(args))),
        "ksort" => with_host(|h| php_ksort(h, &arg(args, 0), false, sort_flags(args))),
        "krsort" => with_host(|h| php_ksort(h, &arg(args, 0), true, sort_flags(args))),
        "array_fill" => with_host(|h| php_array_fill(h, args))?,
        "array_combine" => with_host(|h| php_array_combine(h, args))?,
        "array_diff" => with_host(|h| php_array_diff(h, args, false)),
        "array_intersect" => with_host(|h| php_array_diff(h, args, true)),

        // ── type / util ──────────────────────────────────────────────────
        "boolval" => with_host(|h| Value::bool(h.is_truthy(&arg(args, 0)))),
        "var_export" => with_host(|h| {
            let s = php_var_export(h, &arg(args, 0), 0, &mut host::Visiting::default());
            if args.get(1).map(|v| h.is_truthy(v)).unwrap_or(false) {
                Value::str(s)
            } else {
                h.write_out(&s);
                Value::Undef
            }
        }),
        "json_encode" => {
            // Objects are resolved to plain data FIRST, outside the host borrow:
            // `jsonSerialize()` is PHP code and cannot run while the host is
            // borrowed. See `json_prepare`.
            let flags = host::long_of(&arg(args, 1));
            let partial = flags & JSON_PARTIAL_OUTPUT_ON_ERROR != 0;
            let (prepared, partial_error) = json_prepare(&arg(args, 0), partial);
            if let (true, Ok(doc)) = (partial, &prepared) {
                // Nothing fails and nothing throws, `JSON_THROW_ON_ERROR`
                // included: the substituted document is the result, and the
                // last error substituted is what `json_last_error()` reports.
                let bad_utf8 = flags & (JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE)
                    == 0
                    && with_host(|h| has_invalid_utf8(h, doc));
                let code = if partial_error == 0 && bad_utf8 {
                    5
                } else {
                    partial_error
                };
                crate::stdlib::json::set_last_error(code);
                return Ok(with_host(|h| json_text(php_json_encode(h, doc, flags, 0))));
            }
            let prepared = match prepared {
                Ok(v) => v,
                Err(code) => {
                    return match crate::stdlib::json::fail(code, flags) {
                        Some(e) => Err(e),
                        None => Ok(Value::bool(false)),
                    }
                }
            };
            // JSON has no NAN/INF literal, so the encoder bails out entirely and
            // reports JSON_ERROR_INF_OR_NAN rather than emitting invalid JSON.
            if with_host(|h| has_nonfinite_float(h, &prepared)) {
                return match crate::stdlib::json::fail(
                    crate::stdlib::json::JSON_ERROR_INF_OR_NAN,
                    flags,
                ) {
                    Some(e) => Err(e),
                    None => Ok(Value::bool(false)),
                };
            }
            // A string that is not valid UTF-8 has no JSON spelling unless the
            // flags say what to do with its bad bytes; with partial output it
            // becomes `null` and the error is still recorded.
            let tolerant = flags & (JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE) != 0;
            let mut code = 0;
            if !tolerant && with_host(|h| has_invalid_utf8(h, &prepared)) {
                if flags & JSON_PARTIAL_OUTPUT_ON_ERROR == 0 {
                    return match crate::stdlib::json::fail(5, flags) {
                        Some(e) => Err(e),
                        None => Ok(Value::bool(false)),
                    };
                }
                code = 5;
            }
            crate::stdlib::json::set_last_error(code);
            with_host(|h| json_text(php_json_encode(h, &prepared, flags, 0)))
        }

        // Extended standard library lives in `src/stdlib/*`, one module per
        // category, consulted only for names this core match does not handle.
        _ => {
            return crate::stdlib::dispatch(&lname, args).unwrap_or_else(|| {
                Err(throws_bare(
                    "Error",
                    format!("Call to undefined function {name}()"),
                ))
            })
        }
    };
    Ok(v)
}

/// PHP's case functions are byte-wise and ASCII-only — they never touch a
/// multibyte sequence, so `strtoupper("héllo")` is `"HéLLO"`, not `"HÉLLO"`.
/// (The Unicode-aware behaviour lives in `mb_strtoupper`.)
fn ascii_upper(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_ascii() {
                c.to_ascii_uppercase()
            } else {
                c
            }
        })
        .collect()
}

/// ASCII-only lowercase; see [`ascii_upper`].
fn ascii_lower(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_ascii() {
                c.to_ascii_lowercase()
            } else {
                c
            }
        })
        .collect()
}

fn ucfirst(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        // ASCII-only, so `ucfirst("élan")` leaves the "é" alone.
        Some(first) if first.is_ascii() => std::iter::once(first.to_ascii_uppercase())
            .chain(c)
            .collect(),
        _ => s.to_string(),
    }
}

/// `zend_dval_to_lval_silent((double) n) == n` — whether an integer survives a
/// round trip through a double.
///
/// `min`/`max` use this to decide whether an int operand may be compared as a
/// double instead of going to the generic three-way comparison
/// (`ext/standard/array.c:1238`, `:1258`, `:1296`, `:1309`). The predicate is
/// `ZEND_DOUBLE_FITS_LONG` (`Zend/zend_operators.h:115`, the 64-bit arm:
/// `!((d) >= (double)ZEND_LONG_MAX || (d) < (double)ZEND_LONG_MIN)`) followed by
/// the plain cast in `zend_dval_to_lval_silent` (`Zend/zend_operators.h:138`).
///
/// Rust's `as` saturates where C's cast is undefined, so the range test cannot
/// be folded into the round trip: `i64::MAX as f64 as i64` saturates back to
/// `i64::MAX` and would claim it fits, while the reference's `>= (double)
/// ZEND_LONG_MAX` rejects it.
fn long_fits_double(n: i64) -> bool {
    let d = n as f64;
    // 2^63 exactly — `(double)ZEND_LONG_MAX` and `-(double)ZEND_LONG_MIN`.
    const TWO_POW_63: f64 = 9_223_372_036_854_775_808.0;
    (-TWO_POW_63..TWO_POW_63).contains(&d) && d as i64 == n
}

/// `min`/`max` for a DIRECT two-argument call —
/// `ZEND_FRAMELESS_FUNCTION(min, 2)` at `ext/standard/array.c:1282` and
/// `(max, 2)` at `:1410`.
///
/// This is a genuinely different algorithm from the variadic function, not an
/// unrolling of it, and the difference is visible: it compares the two operands
/// ONCE and keeps the left only when that single test says so. `1.0 < NAN` is
/// false, so `min(1, NAN)` answers NAN here (`:1308`) while the variadic form
/// answers 1.
///
/// The tie rule differs between the two by design: `min` keeps the RIGHT operand
/// on a tie (`lhs < rhs ? lhs : rhs`, `:1295`) and `max` keeps the LEFT
/// (`lhs >= rhs ? lhs : rhs`, `:1423`), which is how `min(1, 1.0)` is a float and
/// `max(1, 1.0)` an int.
pub(crate) fn minmax_frameless(
    h: &host::PhpHost,
    lhs: &Value,
    rhs: &Value,
    want_max: bool,
) -> Value {
    // `RETURN_COPY_VALUE(<test> ? lhs : rhs)` — the shared tail of every arm.
    let pick = |keep_lhs: bool| if keep_lhs { lhs.clone() } else { rhs.clone() };
    // `lhs <op> rhs` with the operator each function uses: `<` for min, `>=`
    // for max.
    let keep = |a: f64, b: f64| if want_max { a >= b } else { a < b };
    match (lhs, rhs) {
        // array.c:1295 / :1423 — both operands are integers.
        (Value::Int(l), Value::Int(r)) => {
            return pick(if want_max { l >= r } else { l < r });
        }
        // array.c:1296 / :1424 — int against double, only when the int is
        // exactly representable; otherwise fall through to generic_compare.
        (Value::Int(l), Value::Float(r)) if long_fits_double(*l) => {
            return pick(keep(*l as f64, *r));
        }
        // array.c:1308 / :1436 — the double_compare label.
        (Value::Float(l), Value::Float(r)) => return pick(keep(*l, *r)),
        // array.c:1309 / :1437 — double against int, same representability test.
        (Value::Float(l), Value::Int(r)) if long_fits_double(*r) => {
            return pick(keep(*l, *r as f64));
        }
        _ => {}
    }
    // array.c:1317 / :1445 — generic_compare.
    let ord = php_compare(h, lhs, rhs);
    pick(if want_max { ord >= 0 } else { ord < 0 })
}

/// Which of the two operands a fold replaces its running winner with, once the
/// variadic loop has decided how to read them.
///
/// Mirrors the three code paths `PHP_FUNCTION(min)` runs between with `goto`
/// (`ext/standard/array.c:1229`-`:1275`): an all-integer loop, an all-double
/// loop, and the generic `zend_compare` loop. A `goto` there jumps INTO the next
/// loop's body without re-running its `for` initializer, so the argument index
/// is deliberately not reset when the mode changes here either.
#[derive(Clone, Copy, PartialEq)]
enum FoldMode {
    Long,
    Double,
    Generic,
}

/// `min`/`max` reached any way OTHER than a direct two-argument call —
/// `PHP_FUNCTION(min)` at `ext/standard/array.c:1197` and `(max)` at `:1325`.
///
/// Three answers to the same question live here, and which one a program gets
/// depends on the SHAPE of the call, not on the values:
///
/// * one array argument → `zend_hash_minmax` (`array.c:1212`, `:1340`), which
///   compares `(winner, candidate)` and so ADOPTS an unordered candidate;
/// * two or more arguments → the loop below, which compares
///   `(candidate, winner)` and so REJECTS one;
/// * a direct two-argument call → [`minmax_frameless`], which never reaches
///   this function at all.
///
/// That is why the reference answers `min(1, NAN)` with NAN, `min([1, NAN, 2])`
/// with 2, and `call_user_func('min', 1, NAN)` with 1. The three are not
/// reconcilable into one comparison rule, so all three are ported.
fn fold_cmp(h: &host::PhpHost, args: &[Value], want_max: bool) -> Result<Value, String> {
    let who = if want_max { "max" } else { "min" };
    // Called with nothing at all, these are an arity error rather than a value
    // error — the parameter is variadic with a minimum of one.
    if args.is_empty() {
        return Err(throws(
            "ArgumentCountError",
            format!("{who}() expects at least 1 argument, 0 given"),
        ));
    }
    if args.len() == 1 {
        // array.c:1208 / :1336 — a lone argument MUST be an array. A scalar is a
        // TypeError, not a one-element fold that answers itself.
        if !h.is_array(&args[0]) {
            let given = h.type_name_for_error(&args[0]);
            return Err(throws(
                "TypeError",
                format!("{who}(): Argument #1 ($value) must be of type array, {given} given"),
            ));
        }
        let items: Vec<Value> = h
            .array_pairs(&args[0])
            .unwrap_or_default()
            .into_iter()
            .map(|(_, v)| v)
            .collect();
        // array.c:1216 / :1344 — `zend_hash_minmax` answers NULL for an empty
        // table and the caller turns that into a value error.
        let Some(first) = items.first() else {
            return Err(throws(
                "ValueError",
                format!("{who}(): Argument #1 ($value) must contain at least one element"),
            ));
        };
        // zend_hash.c:3272 (min) / :3294 (max): `compar(res, zv)` — the WINNER is
        // the left operand. `zend_compare` answers 1 for an unordered pair either
        // way round, so `> 0` is true whenever the winner is a NaN and the fold
        // walks off it, while `< 0` is false and `max` stays stuck on it.
        //
        // The reference's loop starts at the element it took `res` from and so
        // compares it with itself first; that test can only answer 0 or 1 and
        // neither replaces anything, so the walk starts past it here.
        let mut best = first.clone();
        for v in &items[1..] {
            let ord = php_compare(h, &best, v);
            if (want_max && ord < 0) || (!want_max && ord > 0) {
                best = v.clone();
            }
        }
        return Ok(best);
    }

    // array.c:1220-:1277 — the variadic fold. `best` is the reference's `min` /
    // `max` POINTER: the running `lval`/`dval` are only how the loop compares,
    // and the value that comes back is always the argument itself, with the type
    // it was passed as.
    let mut best = 0usize;
    let mut i = 1usize;
    let mut lval = 0i64;
    let mut dval = 0f64;
    let mut mode = match &args[0] {
        Value::Int(n) => {
            lval = *n;
            FoldMode::Long
        }
        Value::Float(d) => {
            dval = *d;
            FoldMode::Double
        }
        _ => FoldMode::Generic,
    };
    loop {
        match mode {
            // array.c:1232-:1245 — every argument so far has been an integer.
            FoldMode::Long => {
                let Some(v) = args.get(i) else {
                    // array.c:1247 / :1375 — `RETURN_LONG(min_lval)`.
                    return Ok(Value::int(lval));
                };
                match v {
                    Value::Int(r) => {
                        if if want_max { lval < *r } else { lval > *r } {
                            lval = *r;
                            best = i;
                        }
                        i += 1;
                    }
                    // array.c:1238 — `goto double_compare`, which lands inside the
                    // double loop's body on the SAME argument.
                    Value::Float(_) if long_fits_double(lval) => {
                        dval = lval as f64;
                        mode = FoldMode::Double;
                    }
                    // array.c:1243 — `goto generic_compare`, likewise.
                    _ => mode = FoldMode::Generic,
                }
            }
            // array.c:1251-:1267.
            FoldMode::Double => {
                let Some(v) = args.get(i) else { break };
                match v {
                    Value::Float(r) => {
                        if if want_max { dval < *r } else { dval > *r } {
                            dval = *r;
                            best = i;
                        }
                        i += 1;
                    }
                    // array.c:1258 — an integer joins the double loop only when it
                    // is exactly representable.
                    Value::Int(r) if long_fits_double(*r) => {
                        let r = *r as f64;
                        if if want_max { dval < r } else { dval > r } {
                            dval = r;
                            best = i;
                        }
                        i += 1;
                    }
                    _ => mode = FoldMode::Generic,
                }
            }
            // array.c:1269-:1274 — `zend_compare(&args[i], min)`: the CANDIDATE is
            // the left operand, the opposite way round from the array form. An
            // unordered pair answers 1, so `< 0` is false and `min` keeps what it
            // has rather than taking the NaN.
            //
            // The comparison reads the winning ARGUMENT, not the running
            // `lval`/`dval`, so a fold that passed through one of the numeric
            // loops still compares against the original operand here.
            FoldMode::Generic => {
                let Some(v) = args.get(i) else { break };
                let ord = php_compare(h, v, &args[best]);
                if (want_max && ord > 0) || (!want_max && ord < 0) {
                    best = i;
                }
                i += 1;
            }
        }
    }
    // array.c:1277 / :1405 — `RETURN_COPY(min)`.
    Ok(args[best].clone())
}

/// `substr($string, $offset, $length)`, counting BYTES: a cut through a
/// multi-byte character leaves its bytes, as the reference does.
fn php_substr(s: &str, args: &[Value]) -> String {
    let chars = crate::bytes::to_bytes(s);
    let len = chars.len() as i64;
    let mut start = host::long_of(&arg(args, 1));
    if start < 0 {
        start = (len + start).max(0);
    }
    let start = start.min(len).max(0) as usize;
    let count = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => {
            let l = host::long_of(v);
            if l < 0 {
                (len - start as i64 + l).max(0) as usize
            } else {
                l as usize
            }
        }
        _ => chars.len() - start,
    };
    crate::bytes::from_bytes(&chars[start..(start + count).min(chars.len())])
}

/// `strpos($haystack, $needle, $offset = 0)`.
///
/// `$offset` was previously ignored outright — `strpos("abcabc", "a", 3)`
/// answered 0 instead of 3. It counts BYTES from the start, or from the end when
/// negative, and an offset outside `[-strlen, strlen]` is a ValueError rather
/// than a no-match: PHP distinguishes "looked and did not find" from "you cannot
/// look there".
fn php_strpos(h: &host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let hay = h.to_str(&arg(args, 0));
    let needle = h.to_str(&arg(args, 1));
    let len = hay.len() as i64;
    let raw = args.get(2).map(|v| h.to_number(v).to_int()).unwrap_or(0);
    let start = if raw < 0 { len + raw } else { raw };
    if start < 0 || start > len {
        return Err(throws(
            "ValueError",
            "strpos(): Argument #3 ($offset) must be contained in argument #1 ($haystack)",
        ));
    }
    // Search the BYTE view: a `$offset` that lands mid-character must not panic
    // the way slicing the `&str` would.
    let from = start as usize;
    let hb = &*crate::bytes::to_bytes(&hay);
    let nb = &*crate::bytes::to_bytes(&needle);
    if nb.is_empty() {
        return Ok(Value::int(start));
    }
    if nb.len() > hb.len() - from {
        return Ok(Value::bool(false));
    }
    for i in from..=(hb.len() - nb.len()) {
        if &hb[i..i + nb.len()] == nb {
            return Ok(Value::int(i as i64));
        }
    }
    Ok(Value::bool(false))
}

/// `str_replace($search, $replace, $subject, &$count)`.
///
/// `$search` and `$replace` may each be an array: with two arrays the pairs line
/// up by position (a missing replacement is `""`), and with an array search plus
/// a string replacement every needle maps to that one string. An array
/// `$subject` is processed element-wise and returns an array.
///
/// The searches are applied in sequence to the *running* result, which is why
/// `str_replace(["a", "aa"], ["1", "2"], "aaa")` is `"111"` — by the time `"aa"`
/// is tried, no `a` is left.
/// `(array) $v` — an array stays itself, `null` becomes the empty array, an
/// object yields its properties keyed by name, and any other scalar becomes a
/// one-element list.
/// `intval($string, $base)` for an explicit base.
///
/// Base 0 auto-detects from the prefix (`0x` hex, `0b` binary, a leading `0`
/// octal, else decimal). Bases 16, 2 and 8 also accept — but do not require —
/// their prefix. Parsing takes as many valid digits as it can and stops at the
/// first one that is out of range, so `intval("42abc", 10)` is 42.
fn intval_base(s: &str, base: i64) -> i64 {
    let t = s.trim_start();
    let (neg, t) = match t.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, t.strip_prefix('+').unwrap_or(t)),
    };
    let lower = t.to_ascii_lowercase();
    // Strip a prefix when it agrees with the requested base (or picks it, at 0).
    let (base, digits) = match base {
        0 if lower.starts_with("0x") => (16, &t[2..]),
        0 if lower.starts_with("0b") => (2, &t[2..]),
        0 if t.len() > 1 && t.starts_with('0') => (8, &t[1..]),
        0 => (10, t),
        16 if lower.starts_with("0x") => (16, &t[2..]),
        2 if lower.starts_with("0b") => (2, &t[2..]),
        8 if lower.starts_with("0o") => (8, &t[2..]),
        b => (b, t),
    };
    if !(2..=36).contains(&base) {
        return 0;
    }
    let mut acc: i64 = 0;
    for c in digits.chars() {
        let Some(d) = c.to_digit(base as u32) else {
            break;
        };
        acc = acc.saturating_mul(base).saturating_add(d as i64);
    }
    if neg {
        -acc
    } else {
        acc
    }
}

/// The array wrapped by an `ArrayObject` / `ArrayIterator` (or subclass),
/// held in the prelude's private `storage` slot. `None` under STD_PROP_LIST,
/// where `spl_array_get_properties_for` hands back the ordinary properties.
fn spl_array_storage(h: &host::PhpHost, v: &Value) -> Option<Value> {
    if h.spl_array_flags(v).is_some_and(|f| f & 1 != 0) {
        return None;
    }
    h.object_props_mangled(v)
        .into_iter()
        .find(|(n, _)| n == "\0ArrayObject\0storage" || n == "\0ArrayIterator\0storage")
        .map(|(_, st)| st)
}

/// The elements an `ArrayObject`/`ArrayIterator` wraps: its storage array, or —
/// for an object backing — the backing object's properties, following a
/// backing that is itself one of the two to the storage it shares.
fn spl_storage_pairs(h: &host::PhpHost, v: &Value) -> Option<Vec<(Value, Value)>> {
    let st = spl_array_storage(h, v)?;
    if h.is_array(&st) {
        return h.array_pairs(&st);
    }
    if spl_array_storage(h, &st).is_some() {
        return spl_storage_pairs(h, &st);
    }
    Some(
        h.object_props(&st)
            .into_iter()
            .map(|(k, val)| (host::prop_key(&k), val))
            .collect(),
    )
}

/// Prelude slots of the SPL classes whose state the reference keeps out of the
/// property table: `(array)` and `var_export` never show them.
const SPL_HIDDEN_SLOTS: [&str; 6] = [
    "\0ArrayObject\0",
    "\0ArrayIterator\0",
    "\0SplDoublyLinkedList\0",
    "\0SplObjectStorage\0",
    "\0SplHeap\0",
    "\0SplPriorityQueue\0",
];

/// What `(array)` and `var_export` see of an SPL prelude object, when that
/// differs from its raw properties: the wrapped array of an `ArrayObject`,
/// `ArrayIterator` or `SplFixedArray`, or the properties left once the
/// prelude's internal slots are dropped. `None` for any other object.
fn spl_view(h: &host::PhpHost, v: &Value) -> Option<Vec<(Value, Value)>> {
    if let Some(pairs) = spl_storage_pairs(h, v) {
        return Some(pairs);
    }
    let props = h.object_props_mangled(v);
    if let Some((_, el)) = props
        .iter()
        .find(|(n, _)| n == "\0SplFixedArray\0__elements")
    {
        return h.array_pairs(el);
    }
    props
        .iter()
        .any(|(n, _)| SPL_HIDDEN_SLOTS.iter().any(|s| n.starts_with(s)))
        .then(|| {
            props
                .into_iter()
                .filter(|(n, _)| !SPL_HIDDEN_SLOTS.iter().any(|s| n.starts_with(s)))
                .map(|(n, val)| (Value::str(n), val))
                .collect()
        })
}

fn php_cast_array(h: &mut host::PhpHost, v: &Value) -> Value {
    if h.is_array(v) {
        return v.clone();
    }
    let out = h.new_array();
    if matches!(v, Value::Undef) {
        return out;
    }
    // A generator is an object with no properties: `[]`. A closure is not cast
    // through its properties: `ZEND_CAST` wraps it like a scalar, `[$closure]`.
    if h.is_object(v) || h.is_generator_val(v) {
        // `(array)` on an ArrayObject / ArrayIterator yields the wrapped array
        // itself (spl_array_get_properties), not the object's own properties.
        // The prelude keeps it in the private `storage` slot of those classes.
        if let Some(pairs) = spl_view(h, v) {
            for (k, val) in pairs {
                h.arr_set_key(&out, &k, val);
            }
            return out;
        }
        // Non-public property names are mangled with NUL separators, as PHP's
        // cast does — see `PhpHost::object_props_mangled`.
        for (name, val) in h.object_props_mangled(v) {
            h.arr_set_key(&out, &host::prop_key(&name), val);
        }
        return out;
    }
    h.arr_push_auto(&out, v.clone());
    out
}

/// `settype($var, $type)` — convert `$var` in place to `$type` and return true.
///
/// The conversion is the same one the matching cast performs, so `settype($x,
/// "integer")` and `$x = (int) $x` agree, including on the cases where they
/// differ from arithmetic: a non-numeric string becomes `0`, a scalar becomes a
/// one-element array, and `"null"` clears the value. An unrecognised type name is
/// a `ValueError` in PHP 8.
fn php_settype(args: &[Value]) -> Result<Value, String> {
    let v = arg(args, 0);
    let ty = with_host(|h| h.to_str(&arg(args, 1))).to_ascii_lowercase();
    let out = match ty.as_str() {
        "bool" | "boolean" => Value::bool(with_host(|h| h.is_truthy(&v))),
        "int" | "integer" => Value::int(with_host(|h| h.to_number(&v)).to_int()),
        "float" | "double" => Value::float(with_host(|h| h.to_number(&v)).to_float()),
        "string" => Value::str(host::to_str_ext(&v)),
        "array" => with_host(|h| php_cast_array(h, &v)),
        "object" => php_cast_object(&v)?,
        "null" => Value::Undef,
        // The message does NOT name the type it was given: PHP's
        // `zend_argument_value_error(2, "must be a valid type")` takes no
        // argument, unlike the `, %s given` suffix a TypeError carries.
        _ => {
            return Err(throws(
                "ValueError",
                "settype(): Argument #2 ($type) must be a valid type",
            ))
        }
    };
    with_host(|h| h.byref_out_put(0, out));
    Ok(Value::bool(true))
}

/// `(object) $v` — an array becomes a `stdClass` with the same keys as
/// properties, `null` an empty `stdClass`, and any other scalar a `stdClass`
/// whose single `scalar` property holds the value. An object passes through.
fn php_cast_object(v: &Value) -> Result<Value, String> {
    // `new_object` re-enters the host, so it must run outside `with_host`.
    if with_host(|h| h.is_object(v)) {
        return Ok(v.clone());
    }
    let obj = host::new_object("stdClass", Vec::new())?;
    with_host(|h| {
        if h.is_array(v) {
            for (k, val) in h.array_pairs(v).unwrap_or_default() {
                let name = h.to_str(&k);
                h.prop_set(&obj, &name, val);
            }
        } else if !matches!(v, Value::Undef) {
            h.prop_set(&obj, "scalar", v.clone());
        }
    });
    Ok(obj)
}

/// `str_replace` and, with `ci`, `str_ireplace` — one body, as in the
/// reference's `php_str_replace_common(…, case_sensitivity)`: an array
/// `$subject` is replaced element by element with its keys kept, and `$count`
/// receives the total number of replacements.
fn php_str_replace(h: &mut host::PhpHost, args: &[Value], ci: bool) -> Result<Value, String> {
    let search = arg(args, 0);
    let replace = arg(args, 1);
    let subject = arg(args, 2);
    // A single search string has a single replacement: an array there is
    // refused once the arguments have parsed.
    if !h.is_array(&search) && h.is_array(&replace) {
        let func = if ci { "str_ireplace" } else { "str_replace" };
        return Err(throws(
            "TypeError",
            format!(
                "{func}(): Argument #2 ($replace) must be of type string when argument #1 ($search) is a string"
            ),
        ));
    }

    // Normalise search/replace into parallel lists.
    let pairs: Vec<(String, String)> = if h.is_array(&search) {
        let searches = h.array_pairs(&search).unwrap_or_default();
        let replaces = if h.is_array(&replace) {
            h.array_pairs(&replace)
                .unwrap_or_default()
                .into_iter()
                .map(|(_, v)| h.to_str(&v))
                .collect()
        } else {
            vec![h.to_str(&replace); searches.len()]
        };
        searches
            .into_iter()
            .enumerate()
            .map(|(i, (_, s))| (h.to_str(&s), replaces.get(i).cloned().unwrap_or_default()))
            .collect()
    } else {
        vec![(h.to_str(&search), h.to_str(&replace))]
    };

    let mut count = 0usize;
    // `$count` is a by-reference OUT parameter: the number of replacements.
    let result = if h.is_array(&subject) {
        let out = h.new_array();
        for (k, v) in h.array_pairs(&subject).unwrap_or_default() {
            let s = replace_all_pairs(&h.to_str(&v), &pairs, ci, &mut count);
            h.arr_set_key(&out, &k, Value::str(s));
        }
        out
    } else {
        Value::str(replace_all_pairs(
            &h.to_str(&subject),
            &pairs,
            ci,
            &mut count,
        ))
    };
    h.byref_out_put(3, Value::int(count as i64));
    Ok(result)
}

/// Apply each `(search, replace)` pair in order to `subject`, accumulating the
/// number of replacements. An empty needle matches nothing, as in PHP. `ci`
/// matches ASCII case-insensitively, as `str_ireplace` does.
fn replace_all_pairs(
    subject: &str,
    pairs: &[(String, String)],
    ci: bool,
    count: &mut usize,
) -> String {
    // Over bytes: a needle holding a stray byte (`"\xA9"`) matches inside a
    // character of the subject (`"é"` is `C3 A9`), which a `str` search
    // cannot see.
    let mut cur = crate::bytes::to_bytes(subject).into_owned();
    for (needle, rep) in pairs {
        let (n, r) = (crate::bytes::to_bytes(needle), crate::bytes::to_bytes(rep));
        if n.is_empty() {
            continue;
        }
        let (next, hits) = if ci {
            crate::stdlib::strings::ci_replace(&cur, &n, &r)
        } else {
            crate::bytes::replace(&cur, &n, &r)
        };
        *count += hits;
        cur = next;
    }
    crate::bytes::from_bytes(&cur)
}

fn php_implode(name: &str, args: &[Value]) -> Result<Value, String> {
    // `PHP_FUNCTION(implode)`, as measured: `implode($array)` joins with "".
    // Given both arguments, `$separator` is judged first — an array or a
    // non-stringable object is refused, null is deprecated — then `$array`,
    // whose null is refused with the two-argument wording a lone non-array
    // separator also gets.
    let sep = arg(args, 0);
    let if_string = || {
        throws(
            "TypeError",
            format!(
                "{name}(): If argument #1 ($separator) is of type string, argument #2 \
                 ($array) must be of type array, null given"
            ),
        )
    };
    let (glue, arr) = if args.len() < 2 {
        if !with_host(|h| h.is_array(&sep)) {
            return Err(if_string());
        }
        (String::new(), sep)
    } else {
        let refused = with_host(|h| {
            let bad = h.is_array(&sep)
                || h.object_class(&sep)
                    .is_some_and(|c| !h.class_has_method(&c, "__tostring"));
            bad.then(|| h.type_name_for_error(&sep))
        });
        if let Some(given) = refused {
            return Err(throws(
                "TypeError",
                format!("{name}(): Argument #1 ($separator) must be of type string, {given} given"),
            ));
        }
        if matches!(sep, Value::Undef) {
            with_host(|h| {
                h.deprecated(format!(
                    "{name}(): Passing null to parameter #1 ($separator) of type array|string \
                     is deprecated"
                ))
            });
        }
        let pieces = arg(args, 1);
        if matches!(pieces, Value::Undef) {
            return Err(if_string());
        }
        if !with_host(|h| h.is_array(&pieces)) {
            let given = with_host(|h| h.type_name_for_error(&pieces));
            return Err(throws(
                "TypeError",
                format!("{name}(): Argument #2 ($array) must be of type ?array, {given} given"),
            ));
        }
        (host::to_str_ext(&sep), pieces)
    };
    let vals: Vec<Value> = with_host(|h| h.array_pairs(&arr).unwrap_or_default())
        .into_iter()
        .map(|(_, v)| v)
        .collect();
    // Each element is joined *as a string*, so one with `__toString` runs it —
    // which re-enters the host, hence the conversion outside the borrow.
    //
    // An element that is itself an ARRAY has no string form: the reference warns
    // `Array to string conversion` (once per such element) and joins the literal
    // text `Array`.
    // `to_str_ext` raises the conversion's own warning, once per element.
    let parts: Vec<String> = vals.iter().map(host::to_str_ext).collect();
    Ok(Value::str(parts.join(&glue)))
}

/// The name `php_charmask` reports a malformed `..` range under, given which of
/// the three trim entry points is running. Upstream this falls out of
/// `php_error_docref(NULL, …)` reading the active function from the stack.
fn trim_fname(start: bool, end: bool) -> &'static str {
    match (start, end) {
        (true, true) => "trim",
        (true, false) => "ltrim",
        _ => "rtrim",
    }
}

/// `trim`/`ltrim`/`rtrim` with PHP's optional `$characters` list. The default set
/// is `" \t\n\r\0\x0B"` — note it does NOT include the form feed `\x0C`, which
/// Rust's `str::trim` would strip.
///
/// Byte-oriented, like `php_trim_int`: the charlist goes through the shared
/// [`crate::stdlib::common::charmask`] so `"a..z"` is an inclusive range and a
/// malformed one warns under this function's own name.
fn php_trim(h: &mut host::PhpHost, args: &[Value], start: bool, end: bool) -> Value {
    let s = h.to_str(&arg(args, 0));
    let mask = match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => {
            let list = h.to_str(v);
            crate::stdlib::common::charmask(
                h,
                &crate::bytes::to_bytes(&list),
                trim_fname(start, end),
            )
        }
        _ => {
            let mut m = [false; 256];
            for c in [b' ', b'\t', b'\n', b'\r', 0, 0x0b] {
                m[c as usize] = true;
            }
            m
        }
    };
    let b = &*crate::bytes::to_bytes(&s);
    let mut lo = 0usize;
    let mut hi = b.len();
    if start {
        while lo < hi && mask[b[lo] as usize] {
            lo += 1;
        }
    }
    if end {
        while hi > lo && mask[b[hi - 1] as usize] {
            hi -= 1;
        }
    }
    Value::str(crate::bytes::from_bytes(&b[lo..hi]))
}

/// `explode($separator, $string, $limit = PHP_INT_MAX)`.
///
/// A positive limit caps the number of parts, the last one keeping the whole
/// remainder; a negative limit drops that many parts off the end; `0` behaves
/// as `1`.
fn php_explode(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let sep = h.to_str(&arg(args, 0));
    let subject = h.to_str(&arg(args, 1));
    let arr = h.new_array();
    // An empty separator is an error, not "split into one piece". PHP 7 returned
    // `false` with a warning; PHP 8 throws.
    if sep.is_empty() {
        return Err(throws(
            "ValueError",
            "explode(): Argument #1 ($separator) must not be empty",
        ));
    }
    let limit = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => v.to_int(),
        _ => i64::MAX,
    };
    // Split on bytes, so a separator holding a stray byte splits inside a
    // character of the subject as the reference does.
    let (sep, whole) = (
        crate::bytes::to_bytes(&sep),
        crate::bytes::to_bytes(&subject),
    );
    // A zero limit is 1: everything in a single element.
    let cap = match limit {
        0 => 1,
        1.. => usize::try_from(limit).unwrap_or(usize::MAX),
        _ => usize::MAX,
    };
    let mut parts: Vec<&[u8]> = Vec::new();
    let mut rest: &[u8] = &whole;
    while parts.len() + 1 < cap {
        let Some(at) = crate::bytes::find(rest, &sep) else {
            break;
        };
        parts.push(&rest[..at]);
        rest = &rest[at + sep.len()..];
    }
    parts.push(rest);
    if limit < 0 {
        let drop = limit.unsigned_abs() as usize;
        parts.truncate(parts.len().saturating_sub(drop));
    }
    for part in parts {
        h.arr_push_auto(&arr, Value::str(crate::bytes::from_bytes(part)));
    }
    Ok(arr)
}

fn php_in_array(h: &host::PhpHost, args: &[Value]) -> Value {
    let needle = arg(args, 0);
    let hay = arg(args, 1);
    let strict = args.get(2).map(|v| h.is_truthy(v)).unwrap_or(false);
    let found = h
        .array_pairs(&hay)
        .unwrap_or_default()
        .iter()
        .any(|(_, v)| {
            if strict {
                strict_eq(h, &needle, v)
            } else {
                loose_eq(h, &needle, v)
            }
        });
    Value::bool(found)
}

fn php_array_values(h: &mut host::PhpHost, v: &Value) -> Value {
    let pairs = h.array_pairs(v).unwrap_or_default();
    let arr = h.new_array();
    for (_, val) in pairs {
        h.arr_push_auto(&arr, val);
    }
    arr
}

fn php_array_push(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    for v in &args[1.min(args.len())..] {
        // Same refusal as `$a[] =`: an append onto a saturated array has no key
        // to take, and the reference raises a catchable `Error` rather than
        // overwriting `PHP_INT_MAX`.
        if h.append_slot_taken(&arr) {
            return Err(throws_bare("Error", host::NEXT_ELEMENT_OCCUPIED));
        }
        h.arr_push_auto(&arr, v.clone());
    }
    Ok(Value::int(h.array_len(&arr)))
}

/// How `range()` reads one of its bounds, ported from `php_range_process_input`
/// in `ext/standard/array.c`. The ORDER matters and is load-bearing: the caller
/// tests `>= Str` to mean "spell this range in characters" and `!= Ambig` to
/// mean "the user really wrote a string", exactly as the C compares the zval
/// type ids `IS_LONG < IS_DOUBLE < IS_STRING < IS_ARRAY`. `Ambig` stands in for
/// the C's `IS_ARRAY` sentinel: a ONE-BYTE numeric string like `"5"`, which can
/// be read either as the int 5 or as the character `5`, and whose reading is
/// decided by what the other bound turned out to be.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum RangeInput {
    Long,
    Double,
    Str,
    Ambig,
}

/// Read one `range()` bound into both an int and a float view, reporting which
/// of them is meaningful. Port of `php_range_process_input`.
///
/// The diagnostics are part of the contract, not decoration: an empty string
/// warns and becomes 0, and a multi-byte non-numeric string warns that only its
/// first byte survives.
fn range_process_input(
    h: &mut host::PhpHost,
    input: &Value,
    arg_num: u32,
    arg_name: &str,
) -> Result<(RangeInput, i64, f64), String> {
    let finite = |d: f64, h: &mut host::PhpHost| -> Result<(), String> {
        let _ = h;
        if d.is_infinite() {
            return Err(throws(
                "ValueError",
                format!(
                    "range(): Argument #{arg_num} (${arg_name}) must be a finite number, \
                     INF provided"
                ),
            ));
        }
        if d.is_nan() {
            return Err(throws(
                "ValueError",
                format!(
                    "range(): Argument #{arg_num} (${arg_name}) must be a finite number, \
                     NAN provided"
                ),
            ));
        }
        Ok(())
    };

    match input {
        Value::Int(n) => Ok((RangeInput::Long, *n, *n as f64)),
        Value::Float(d) => {
            finite(*d, h)?;
            Ok((RangeInput::Double, 0, *d))
        }
        Value::Str(s) => {
            if s.is_empty() {
                h.warn(format_args!(
                    "range(): Argument #{arg_num} (${arg_name}) must not be empty, casted to 0"
                ));
                return Ok((RangeInput::Long, 0, 0.0));
            }
            match host::parse_php_number_full(s) {
                Some(Value::Float(d)) => {
                    finite(d, h)?;
                    Ok((RangeInput::Double, 0, d))
                }
                Some(Value::Int(n)) => Ok((
                    if s.len() == 1 {
                        RangeInput::Ambig
                    } else {
                        RangeInput::Long
                    },
                    n,
                    n as f64,
                )),
                _ => {
                    if s.len() != 1 {
                        h.warn(format_args!(
                            "range(): Argument #{arg_num} (${arg_name}) must be a single byte, \
                             subsequent bytes are ignored"
                        ));
                    }
                    Ok((RangeInput::Str, 0, 0.0))
                }
            }
        }
        // `Z_PARAM_NUMBER_OR_STR` in weak mode: bool and null coerce, everything
        // else is rejected before the body runs.
        Value::Bool(b) => Ok((RangeInput::Long, i64::from(*b), f64::from(*b))),
        Value::Undef => {
            h.deprecated(format_args!(
                "range(): Passing null to parameter #{arg_num} (${arg_name}) of type \
                 string|int|float is deprecated"
            ));
            Ok((RangeInput::Long, 0, 0.0))
        }
        other => {
            let t = h.type_name_for_error(other);
            Err(throws(
                "TypeError",
                format!(
                    "range(): Argument #{arg_num} (${arg_name}) must be of type \
                     string|int|float, {t} given"
                ),
            ))
        }
    }
}

/// The engine's hard cap on a hash-table's element count, `HT_MAX_SIZE`. Every
/// `range()` size overflow message quotes it verbatim.
const HT_MAX_SIZE: u64 = 1 << 30;

/// `range($start, $end, $step = 1)`: an inclusive sequence of ints, floats, or
/// single-byte characters.
///
/// Ported from `PHP_FUNCTION(range)` in `ext/standard/array.c` (PHP 8.5). The
/// structure follows the C: `$step` is validated FIRST and independently of the
/// bounds (so `range("", "", 0)` reports the step, never the empty strings),
/// then each bound is classified by [`range_process_input`], then one of three
/// generators runs. Direction comes from `$start` vs `$end`; a negative `$step`
/// is only legal when the range is decreasing.
///
/// The three ValueErrors are distinct and PHP distinguishes them: `cannot be 0`,
/// `must be greater than 0 for increasing ranges`, and `must be less than the
/// range spanned by …`. A range whose element count would exceed `HT_MAX_SIZE`
/// is a fourth, with the counts spelled out.
fn php_range(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    const NEGATIVE_STEP_ERR: &str =
        "range(): Argument #3 ($step) must be greater than 0 for increasing ranges";
    const BOUNDARY_ERR: &str = "range(): Argument #3 ($step) must be less than the range \
                                spanned by argument #1 ($start) and argument #2 ($end)";

    // ── $step, before anything else ──────────────────────────────────────────
    let mut is_step_double = false;
    let mut is_step_negative = false;
    let mut step_double = 1.0f64;
    let mut step: i64 = 1;

    if let Some(user_step) = args.get(2) {
        // `Z_PARAM_NUMBER` (weak): int/float pass, a numeric string and bool
        // coerce, null coerces with a deprecation, anything else is a TypeError.
        let num = match user_step {
            Value::Int(_) | Value::Float(_) => user_step.clone(),
            Value::Bool(b) => Value::int(i64::from(*b)),
            Value::Undef => {
                h.deprecated(
                    "range(): Passing null to parameter #3 ($step) of type int|float \
                     is deprecated",
                );
                Value::int(0)
            }
            Value::Str(s) => match host::parse_php_number_full(s) {
                Some(v) => v,
                None => {
                    return Err(throws(
                        "TypeError",
                        "range(): Argument #3 ($step) must be of type int|float, string given",
                    ))
                }
            },
            other => {
                let t = h.type_name_for_error(other);
                return Err(throws(
                    "TypeError",
                    format!("range(): Argument #3 ($step) must be of type int|float, {t} given"),
                ));
            }
        };

        match num {
            Value::Float(mut d) => {
                if d.is_infinite() {
                    return Err(throws(
                        "ValueError",
                        "range(): Argument #3 ($step) must be a finite number, INF provided",
                    ));
                }
                if d.is_nan() {
                    return Err(throws(
                        "ValueError",
                        "range(): Argument #3 ($step) must be a finite number, NAN provided",
                    ));
                }
                if d < 0.0 {
                    is_step_negative = true;
                    d *= -1.0;
                }
                step_double = d;
                // `zend_dval_to_lval_silent` then `zend_is_long_compatible`: a
                // step of `2.0` is an INT step and keeps an int range int, while
                // `2.5` forces the whole range to floats.
                step = d as i64;
                if (step as f64) != d {
                    is_step_double = true;
                }
            }
            other => {
                step = other.to_int();
                if step < 0 {
                    // `-step` would overflow, so the reference rejects the value
                    // rather than negating it.
                    if step == i64::MIN {
                        return Err(throws(
                            "ValueError",
                            format!("range(): Argument #3 ($step) must be greater than {step}"),
                        ));
                    }
                    is_step_negative = true;
                    step = -step;
                }
                step_double = step as f64;
            }
        }

        if step_double == 0.0 {
            return Err(throws(
                "ValueError",
                "range(): Argument #3 ($step) cannot be 0",
            ));
        }
    }

    // ── the two bounds ───────────────────────────────────────────────────────
    let user_start = arg(args, 0);
    let user_end = arg(args, 1);
    let (mut start_type, start_long, start_double) =
        range_process_input(h, &user_start, 1, "start")?;
    let (mut end_type, end_long, end_double) = range_process_input(h, &user_end, 2, "end")?;

    let arr = h.new_array();

    // ── character range ──────────────────────────────────────────────────────
    if start_type >= RangeInput::Str || end_type >= RangeInput::Str {
        let mut fall_through_to_numeric = false;

        if start_type < RangeInput::Str || end_type < RangeInput::Str {
            // Exactly one side reads as a character. The other is coerced to 0,
            // and PHP says so — unless the character side was merely AMBIGUOUS
            // (a one-byte numeric string), in which case reading it as a number
            // was always legitimate and there is nothing to warn about.
            if start_type < RangeInput::Str {
                if end_type != RangeInput::Ambig {
                    h.warn(
                        "range(): Argument #1 ($start) must be a single byte string if \
                         argument #2 ($end) is a single byte string, argument #2 ($end) \
                         converted to 0",
                    );
                }
                end_type = RangeInput::Long;
            } else {
                if start_type != RangeInput::Ambig {
                    h.warn(
                        "range(): Argument #2 ($end) must be a single byte string if \
                         argument #1 ($start) is a single byte string, argument #1 ($start) \
                         converted to 0",
                    );
                }
                start_type = RangeInput::Long;
            }
            fall_through_to_numeric = true;
        } else if is_step_double {
            // A fractional step cannot walk characters. Both bounds become 0.
            if start_type == RangeInput::Str || end_type == RangeInput::Str {
                h.warn(
                    "range(): Argument #3 ($step) must be of type int when generating an \
                     array of characters, inputs converted to 0",
                );
            }
            start_type = RangeInput::Long;
            end_type = RangeInput::Long;
            fall_through_to_numeric = true;
        }

        if !fall_through_to_numeric {
            let low = crate::bytes::to_bytes(&h.to_str(&user_start))[0];
            let high = crate::bytes::to_bytes(&h.to_str(&user_end))[0];
            let ustep = step as u64;
            match low.cmp(&high) {
                std::cmp::Ordering::Greater => {
                    if u64::from(low - high) < ustep {
                        return Err(throws("ValueError", BOUNDARY_ERR));
                    }
                    let mut c = low;
                    while c >= high {
                        h.arr_push_auto(&arr, Value::str((c as char).to_string()));
                        if (c as i64) - (step) < 0 {
                            break;
                        }
                        c -= step as u8;
                    }
                }
                std::cmp::Ordering::Less => {
                    if is_step_negative {
                        return Err(throws("ValueError", NEGATIVE_STEP_ERR));
                    }
                    if u64::from(high - low) < ustep {
                        return Err(throws("ValueError", BOUNDARY_ERR));
                    }
                    let mut c = low;
                    while c <= high {
                        h.arr_push_auto(&arr, Value::str((c as char).to_string()));
                        if (c as i64) + step > 255 {
                            break;
                        }
                        c += step as u8;
                    }
                }
                std::cmp::Ordering::Equal => {
                    h.arr_push_auto(&arr, Value::str((low as char).to_string()));
                }
            }
            return Ok(arr);
        }
    }

    // ── numeric range ────────────────────────────────────────────────────────
    if start_type == RangeInput::Double || end_type == RangeInput::Double || is_step_double {
        // `RANGE_CHECK_DOUBLE_INIT_ARRAY`: the size is computed from the SPAN,
        // and the message names the smaller bound `start=` whichever way the
        // range runs — the C macro is called with its operands swapped for the
        // decreasing case, so both directions print the same text.
        let check = |span_hi: f64, span_lo: f64| -> Result<u64, String> {
            let calc = ((span_hi - span_lo) / step_double) + 1.0;
            if calc >= HT_MAX_SIZE as f64 {
                let exceed = calc - HT_MAX_SIZE as f64;
                return Err(throws(
                    "ValueError",
                    format!(
                        "The supplied range exceeds the maximum array size by {exceed:.1} \
                         elements: start={span_lo:.1}, end={span_hi:.1}, step={step_double:.1}. \
                         Max size: {}",
                        HT_MAX_SIZE
                    ),
                ));
            }
            Ok(calc.round() as u64)
        };

        if start_double > end_double {
            if start_double - end_double < step_double {
                return Err(throws("ValueError", BOUNDARY_ERR));
            }
            let size = check(start_double, end_double)?;
            let mut element = start_double;
            let mut i = 0u64;
            while i < size && element >= end_double {
                h.arr_push_auto(&arr, Value::float(element));
                i += 1;
                element = start_double - (i as f64 * step_double);
            }
        } else if end_double > start_double {
            if is_step_negative {
                return Err(throws("ValueError", NEGATIVE_STEP_ERR));
            }
            if end_double - start_double < step_double {
                return Err(throws("ValueError", BOUNDARY_ERR));
            }
            let size = check(end_double, start_double)?;
            let mut element = start_double;
            let mut i = 0u64;
            while i < size && element <= end_double {
                h.arr_push_auto(&arr, Value::float(element));
                i += 1;
                element = start_double + (i as f64 * step_double);
            }
        } else {
            h.arr_push_auto(&arr, Value::float(start_double));
        }
        return Ok(arr);
    }

    // Both bounds are ints and the step is a whole number. Every subtraction
    // here is UNSIGNED and wrapping, which is what lets the reference span the
    // full i64 width without overflowing before it can report the size error.
    let ustep = step as u64;
    let check = |span_hi: i64, span_lo: i64| -> Result<u64, String> {
        let calc = (span_hi as u64).wrapping_sub(span_lo as u64) / ustep;
        if calc >= HT_MAX_SIZE - 1 {
            let excess = calc - (HT_MAX_SIZE - 1);
            return Err(throws(
                "ValueError",
                format!(
                    "The supplied range exceeds the maximum array size by {excess} elements: \
                     start={span_lo}, end={span_hi}, step={step}. Calculated size: {calc}. \
                     Maximum size: {HT_MAX_SIZE}."
                ),
            ));
        }
        Ok(calc + 1)
    };

    match start_long.cmp(&end_long) {
        std::cmp::Ordering::Greater => {
            if (start_long as u64).wrapping_sub(end_long as u64) < ustep {
                return Err(throws("ValueError", BOUNDARY_ERR));
            }
            let size = check(start_long, end_long)?;
            for i in 0..size {
                let v = (start_long as u64).wrapping_sub(i.wrapping_mul(ustep)) as i64;
                h.arr_push_auto(&arr, Value::int(v));
            }
        }
        std::cmp::Ordering::Less => {
            if is_step_negative {
                return Err(throws("ValueError", NEGATIVE_STEP_ERR));
            }
            if (end_long as u64).wrapping_sub(start_long as u64) < ustep {
                return Err(throws("ValueError", BOUNDARY_ERR));
            }
            let size = check(end_long, start_long)?;
            for i in 0..size {
                let v = (start_long as u64).wrapping_add(i.wrapping_mul(ustep)) as i64;
                h.arr_push_auto(&arr, Value::int(v));
            }
        }
        std::cmp::Ordering::Equal => {
            h.arr_push_auto(&arr, Value::int(start_long));
        }
    }
    Ok(arr)
}

/// Every conversion character the reference's `switch` has a case for. Anything
/// else is a ValueError, which is why `%i` — a C spelling many people expect to
/// work — is rejected rather than treated as `%d`.
const KNOWN_CONVERSIONS: &str = "sdugGhHeEfFcoxXb%";

/// A parsed conversion spec `%[argnum$][flags][width][.precision]conv`.
#[derive(Clone, Copy)]
struct FmtSpec {
    argnum: Option<usize>,
    left: bool,
    plus: bool,
    pad: char,
    width: usize,
    precision: Option<usize>,
    conv: char,
}

/// `sprintf`: a format engine covering PHP's flags (`- + 0 ' `), width, precision,
/// positional args (`%2$s`), and the `d i u f F e E g G s x X o b c %` conversions.
///
/// `args[0]` is the format; the conversions consume `args[1..]`. A conversion
/// that reaches past the end does NOT render — the reference records the highest
/// index it wanted and reports the shortfall once, after the whole format has
/// been walked, so `sprintf("%d %d")` names the second missing argument and not
/// the first.
///
/// `array_form` selects which failure that shortfall is. `vsprintf`/`vprintf`
/// were handed an array, so a short one is a ValueError about the array; plain
/// `sprintf`/`printf` were handed loose parameters, so it is an
/// ArgumentCountError whose counts include the format string itself.
pub(crate) fn php_sprintf(
    h: &mut host::PhpHost,
    args: &[Value],
    array_form: bool,
) -> Result<String, String> {
    let fmt: Vec<char> = h.to_str(&arg(args, 0)).chars().collect();
    let mut out = String::new();
    let mut i = 0;
    let mut next_arg = 1usize;
    // Highest 1-based `args` index a conversion asked for and did not get.
    let mut max_missing: Option<usize> = None;
    while i < fmt.len() {
        if fmt[i] != '%' {
            out.push(fmt[i]);
            i += 1;
            continue;
        }
        i += 1;
        if i < fmt.len() && fmt[i] == '%' {
            out.push('%');
            i += 1;
            continue;
        }
        let Some(spec) = parse_spec(&fmt, &mut i)? else {
            out.push('%');
            continue;
        };
        let ai = spec.argnum.unwrap_or_else(|| {
            let a = next_arg;
            next_arg += 1;
            a
        });
        if ai >= args.len() {
            // The reference records the gap and moves on WITHOUT looking at the
            // conversion character, which is why `sprintf("%")` reports a
            // missing argument rather than a missing specifier. Nor does it
            // CONSUME that character: the scan resumes on it, so the `%` of
            // `"%5%"` opens a second spec, which wants a second argument.
            max_missing = Some(max_missing.map_or(ai, |m: usize| m.max(ai)));
            if spec.conv != '\0' {
                i -= 1;
            }
            continue;
        }
        if spec.conv == '\0' {
            return Err(throws(
                "ValueError",
                "Missing format specifier at end of string",
            ));
        }
        if !KNOWN_CONVERSIONS.contains(spec.conv) {
            return Err(throws(
                "ValueError",
                format!("Unknown format specifier \"{}\"", spec.conv),
            ));
        }
        out.push_str(&render_spec(h, &spec, &arg(args, ai)));
    }
    if let Some(missing) = max_missing {
        // `missing` is a 1-based index into `args`; the reference counts the
        // supplied arguments as `args.len() - 1` (the format is not one of them).
        let supplied = args.len() - 1;
        return Err(if array_form {
            throws(
                "ValueError",
                format!("The arguments array must contain {missing} items, {supplied} given"),
            )
        } else {
            throws(
                "ArgumentCountError",
                format!(
                    "{} arguments are required, {} given",
                    missing + 1,
                    supplied + 1
                ),
            )
        });
    }
    Ok(out)
}

/// Parse one conversion spec, advancing `i` past it. `Ok(None)` (with `i` left
/// just past a stray `%`) means the spec is malformed and the `%` is literal.
///
/// `Err` is reserved for the three faults the reference reports as a throw
/// rather than as literal text: a `'` padding flag with nothing after it, and a
/// width or precision whose digit run exceeds `INT_MAX`. Accumulating those
/// digits into a `usize` is what used to overflow.
fn parse_spec(fmt: &[char], i: &mut usize) -> Result<Option<FmtSpec>, String> {
    let mut j = *i;
    // Positional `N$`.
    let mut argnum = None;
    let mut k = j;
    while k < fmt.len() && fmt[k].is_ascii_digit() {
        k += 1;
    }
    if k > j && k < fmt.len() && fmt[k] == '$' {
        argnum = fmt[j..k].iter().collect::<String>().parse::<usize>().ok();
        j = k + 1;
    }
    // Flags.
    let (mut left, mut plus, mut pad) = (false, false, ' ');
    loop {
        match fmt.get(j) {
            Some('-') => left = true,
            Some('+') => plus = true,
            // PHP treats a space as a padding-character flag (pad with spaces),
            // not as C-style sign-space; the last padding flag in the run wins, so
            // `% 05d` pads with zeros while `%0 5d` pads with spaces.
            Some(' ') => pad = ' ',
            Some('0') => pad = '0',
            Some('\'') => {
                let Some(c) = fmt.get(j + 1) else {
                    return Err(throws("ValueError", "Missing padding character"));
                };
                pad = *c;
                j += 2;
                continue;
            }
            _ => break,
        }
        j += 1;
    }
    // Width. `php_sprintf_getnumber` reads the digit run with `strtol` and
    // rejects anything AT or past `INT_MAX` — the bound is exclusive even though
    // the message reads "between 0 and 2147483647". Accumulating the digits
    // without that cap is what overflowed.
    let mut width = 0usize;
    let mut saw_width = false;
    while let Some(d) = fmt.get(j).filter(|c| c.is_ascii_digit()) {
        saw_width = true;
        width = width
            .saturating_mul(10)
            .saturating_add(*d as usize - '0' as usize);
        j += 1;
    }
    if saw_width && width >= i32::MAX as usize {
        return Err(throws(
            "ValueError",
            format!("Width must be between 0 and {}", i32::MAX),
        ));
    }
    // Precision, under the same cap.
    let mut precision = None;
    if fmt.get(j) == Some(&'.') {
        j += 1;
        let mut p = 0usize;
        let mut saw_prec = false;
        while let Some(d) = fmt.get(j).filter(|c| c.is_ascii_digit()) {
            saw_prec = true;
            p = p
                .saturating_mul(10)
                .saturating_add(*d as usize - '0' as usize);
            j += 1;
        }
        if saw_prec && p >= i32::MAX as usize {
            return Err(throws(
                "ValueError",
                format!("Precision must be between 0 and {}", i32::MAX),
            ));
        }
        precision = Some(p);
    }
    // `l` is a C length modifier the reference silently swallows, so `%ld` is
    // `%d`. Consuming it here is why `%l` alone reports a MISSING specifier
    // rather than an unknown one.
    if fmt.get(j) == Some(&'l') {
        j += 1;
    }
    // Running off the end leaves the conversion unset. The reference still
    // consumes an argument for the spec first, so this cannot be reported until
    // the argument has been looked for — see [`php_sprintf`].
    let conv = fmt.get(j).copied().unwrap_or('\0');
    if conv != '\0' {
        j += 1;
    }
    *i = j;
    Ok(Some(FmtSpec {
        argnum,
        left,
        plus,
        pad,
        width,
        precision,
        conv,
    }))
}

/// Render one parsed spec against its argument value.
///
/// The float conversions cap `$precision` at 53 digits — the most an IEEE double
/// can carry — and the reference says so with an E_NOTICE before truncating.
/// That cap is also what keeps a `%.2147483646f` from trying to build a
/// two-gigabyte string.
fn render_spec(h: &mut host::PhpHost, s: &FmtSpec, v: &Value) -> String {
    const MAX_FLOAT_PRECISION: usize = 53;
    let s = &if matches!(s.conv, 'f' | 'F' | 'e' | 'E' | 'g' | 'G' | 'h' | 'H')
        && s.precision.is_some_and(|p| p > MAX_FLOAT_PRECISION)
    {
        let asked = s.precision.unwrap_or(0);
        h.notice(format_args!(
            "sprintf(): Requested precision of {asked} digits was truncated to \
             PHP maximum of {MAX_FLOAT_PRECISION} digits"
        ));
        FmtSpec {
            precision: Some(MAX_FLOAT_PRECISION),
            ..*s
        }
    } else {
        FmtSpec { ..*s }
    };
    // A non-finite float is printed bare by every float conversion — no sign
    // flag, no width, no padding (`php_sprintf_appenddouble`'s early return).
    if matches!(s.conv, 'f' | 'F' | 'e' | 'E' | 'g' | 'G' | 'h' | 'H') {
        let f = h.to_number(v).to_float();
        if f.is_nan() {
            return "NaN".to_string();
        }
        if f.is_infinite() {
            return if f < 0.0 { "-INF" } else { "INF" }.to_string();
        }
    }
    // `body` = the value with sign but no field padding; `is_num` gates
    // zero-padding-after-sign.
    let (body, is_num) = match s.conv {
        'd' | 'i' => {
            let n = h.to_number(v).to_int();
            (signed(n.unsigned_abs().to_string(), n < 0, s), true)
        }
        'u' => ((h.to_number(v).to_int() as u64).to_string(), true),
        'b' => (
            (h.to_number(v).to_int() as u64).pipe(|u| format!("{u:b}")),
            true,
        ),
        'o' => (
            (h.to_number(v).to_int() as u64).pipe(|u| format!("{u:o}")),
            true,
        ),
        'x' => (
            (h.to_number(v).to_int() as u64).pipe(|u| format!("{u:x}")),
            true,
        ),
        'X' => (
            (h.to_number(v).to_int() as u64).pipe(|u| format!("{u:X}")),
            true,
        ),
        'c' => (
            crate::bytes::from_bytes(&[(h.to_number(v).to_int() & 0xff) as u8]),
            false,
        ),
        'f' | 'F' => {
            let f = h.to_number(v).to_float();
            let p = s.precision.unwrap_or(6);
            (
                signed(
                    locale_point(format!("{:.*}", p, f.abs()), s.conv == 'f'),
                    f < 0.0,
                    s,
                ),
                true,
            )
        }
        'e' | 'E' => {
            let f = h.to_number(v).to_float();
            // `-0.0` prints unsigned here, as in `%f`; `%g` keeps its sign.
            let mag = fmt_exp(f.abs(), s.precision.unwrap_or(6), s.conv == 'E');
            (signed(mag, f < 0.0, s), true)
        }
        // `h`/`H` are `g`/`G` with the decimal separator pinned to `.` instead of
        // taken from the locale.
        'g' | 'G' | 'h' | 'H' => {
            let f = h.to_number(v).to_float();
            let p = s.precision.unwrap_or(6).max(1);
            let g = host::php_gcvt(f.abs(), p);
            let lower = s.conv == 'g' || s.conv == 'h';
            let g = if lower { g.to_lowercase() } else { g };
            let g = locale_point(g, matches!(s.conv, 'g' | 'G'));
            (signed(g, f.is_sign_negative(), s), true)
        }
        's' => {
            let mut txt = h.to_str_diag(v);
            // The precision cuts BYTES, as everything about `%s` counts them.
            if let Some(p) = s.precision {
                let b = crate::bytes::to_bytes(&txt);
                txt = crate::bytes::from_bytes(&b[..p.min(b.len())]);
            }
            (txt, false)
        }
        // `case '%'`: one `%`, whatever the flags and width said.
        '%' => return "%".to_string(),
        other => return format!("%{other}"),
    };
    pad_field(body, s, is_num)
}

/// Prefix a magnitude string with the correct sign per the `+`/` ` flags.
fn signed(mag: String, neg: bool, s: &FmtSpec) -> String {
    if neg {
        format!("-{mag}")
    } else if s.plus {
        format!("+{mag}")
    } else {
        mag
    }
}

/// PHP `%e`: `d.dddddde±d`, exponent always signed with at least one digit.
fn fmt_exp(f: f64, prec: usize, upper: bool) -> String {
    let raw = format!("{:.*e}", prec, f);
    let (mant, ex) = raw.split_once('e').unwrap_or((raw.as_str(), "0"));
    let exp_n: i32 = ex.parse().unwrap_or(0);
    let e = if upper { 'E' } else { 'e' };
    format!(
        "{mant}{e}{}{}",
        if exp_n < 0 { "-" } else { "+" },
        exp_n.abs()
    )
}

/// Apply width/justification/pad to a rendered body.
fn pad_field(body: String, s: &FmtSpec, is_num: bool) -> String {
    // `php_sprintf_appendchar` takes no width at all.
    if s.conv == 'c' {
        return body;
    }
    let len = crate::bytes::byte_len(&body);
    if len >= s.width {
        return body;
    }
    let fill = s.width - len;
    if s.left {
        // A left-justified field pads on the right with its padding character —
        // except that `php_sprintf_appendint`/`appenduint` swap a `0` for a
        // space (`%-05d` is `42   `, but `%-05x` is `2a000`).
        let pad = if s.pad == '0' && matches!(s.conv, 'd' | 'i' | 'u') {
            ' '
        } else {
            s.pad
        };
        format!("{body}{}", pad.to_string().repeat(fill))
    } else if s.pad == '0' && is_num {
        // Zero-pad after any leading sign character.
        let mut chars = body.chars();
        match body.chars().next() {
            Some(sign @ ('-' | '+' | ' ')) => {
                chars.next();
                format!("{sign}{}{}", "0".repeat(fill), chars.as_str())
            }
            _ => format!("{}{body}", "0".repeat(fill)),
        }
    } else {
        format!("{}{body}", s.pad.to_string().repeat(fill))
    }
}

/// `wordwrap($string, $width = 75, $break = "\n", $cut_long_words = false)`.
///
/// Port of `PHP_FUNCTION(wordwrap)` (ext/standard/string.c), over bytes: a
/// single-byte break without cutting rewrites spaces in place; otherwise the
/// text is copied with breaks inserted, an existing `$break` in the text
/// resetting the line.
fn php_wordwrap(h: &host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let text = crate::bytes::to_bytes(&h.to_str(&arg(args, 0))).into_owned();
    let width = args.get(1).map(crate::host::long_of).unwrap_or(75);
    let brk = match args.get(2) {
        Some(v) => crate::bytes::to_bytes(&h.to_str(v)).into_owned(),
        None => b"\n".to_vec(),
    };
    let docut = args.get(3).map(|v| h.is_truthy(v)).unwrap_or(false);
    if text.is_empty() {
        return Ok(Value::str(""));
    }
    if brk.is_empty() {
        return Err(throws(
            "ValueError",
            "wordwrap(): Argument #3 ($break) must not be empty",
        ));
    }
    if width == 0 && docut {
        return Err(throws(
            "ValueError",
            "wordwrap(): Argument #4 ($cut_long_words) cannot be true when \
             argument #2 ($width) is 0",
        ));
    }
    let len = text.len() as i64;
    let (mut laststart, mut lastspace) = (0i64, 0i64);
    if brk.len() == 1 && !docut {
        let mut out = text.clone();
        for current in 0..len {
            let c = text[current as usize];
            if c == brk[0] {
                laststart = current + 1;
                lastspace = current + 1;
            } else if c == b' ' {
                if current - laststart >= width {
                    out[current as usize] = brk[0];
                    laststart = current + 1;
                }
                lastspace = current;
            } else if current - laststart >= width && laststart != lastspace {
                out[lastspace as usize] = brk[0];
                laststart = lastspace + 1;
            }
        }
        return Ok(Value::str(crate::bytes::from_bytes(&out)));
    }
    let span = |a: i64, b: i64| &text[a as usize..b as usize];
    let mut out = Vec::with_capacity(text.len() + brk.len());
    let mut current = 0i64;
    while current < len {
        let c = text[current as usize];
        if c == brk[0] && text[current as usize..].starts_with(&brk) {
            out.extend_from_slice(span(laststart, current + brk.len() as i64));
            current += brk.len() as i64 - 1;
            laststart = current + 1;
            lastspace = current + 1;
        } else if c == b' ' {
            if current - laststart >= width {
                out.extend_from_slice(span(laststart, current));
                out.extend_from_slice(&brk);
                laststart = current + 1;
            }
            lastspace = current;
        } else if current - laststart >= width && docut && laststart >= lastspace {
            out.extend_from_slice(span(laststart, current));
            out.extend_from_slice(&brk);
            laststart = current;
            lastspace = current;
        } else if current - laststart >= width && laststart < lastspace {
            out.extend_from_slice(span(laststart, lastspace));
            out.extend_from_slice(&brk);
            laststart = lastspace + 1;
            lastspace = laststart;
        }
        current += 1;
    }
    if laststart != current {
        out.extend_from_slice(span(laststart, current));
    }
    Ok(Value::str(crate::bytes::from_bytes(&out)))
}

/// Tiny postfix-apply helper so integer→radix formatting reads left-to-right.
trait Pipe: Sized {
    fn pipe<R>(self, f: impl FnOnce(Self) -> R) -> R {
        f(self)
    }
}
impl Pipe for u64 {}

/// `print_r` rendering (arrays one level indented, as PHP).
fn php_print_r(h: &host::PhpHost, v: &Value, depth: usize, seen: &mut host::Visiting) -> String {
    if let Some(pairs) = h.array_pairs(v) {
        // The head is printed either way; only the block is replaced, which is
        // why the reference's output reads `Array\n *RECURSION*`.
        if !seen.enter(v) {
            return "Array\n *RECURSION*".to_string();
        }
        let pad = "    ".repeat(depth);
        let inner = "    ".repeat(depth + 1);
        let mut s = format!("Array\n{pad}(\n");
        for (k, val) in pairs {
            s.push_str(&format!(
                "{inner}[{}] => {}\n",
                h.to_str(&k),
                php_print_r(h, &val, depth + 2, seen)
            ));
        }
        s.push_str(&format!("{pad})\n"));
        seen.leave();
        s
    } else if h.is_object(v) || is_dumped_closure(h, v) {
        php_print_r_object(h, v, depth, seen)
    } else {
        h.to_str(v)
    }
}

/// Run `render` with every `__debugInfo` reachable from `roots` answered first.
///
/// `var_dump` and `print_r` show an object through `get_debug_info`
/// (`zend_std_get_debug_info`): the array its class's `__debugInfo()` returns,
/// `null` read as an empty array, and only the declared properties when the
/// class has none. The method is PHP code, so it cannot run inside the
/// renderer's host borrow; the reachable values are walked first, depth-first
/// in render order, and each answer is parked in `PhpHost::debug_info` by
/// handle for the renderer to read. `None` when a `__debugInfo` threw — the
/// exception is left pending and nothing is rendered.
fn with_debug_info<T>(roots: &[Value], render: impl FnOnce(&mut host::PhpHost) -> T) -> Option<T> {
    let map = host::collect_object_hooks(roots, &["__debugInfo"], &|_, class, _, r| {
        Some(with_host(|h| {
            if h.is_array(&r) {
                return r;
            }
            if matches!(r, Value::Undef) {
                h.deprecated(format!(
                    "Returning null from {}::__debugInfo() is deprecated, return an empty \
                     array instead",
                    host::display_class(class)
                ));
            }
            // DIVERGENCE: an answer that is neither an array nor null is the
            // reference's fatal `__debuginfo() must return an array`; it
            // renders empty here.
            h.new_array()
        }))
    })?;
    // A `var_dump` inside a `__debugInfo` renders with its own map; the outer
    // one is restored after.
    Some(with_host(|h| {
        let outer = std::mem::replace(&mut h.debug_info, map);
        let out = render(h);
        h.debug_info = outer;
        out
    }))
}

/// as an object of class `Closure` with those rows.
fn is_dumped_closure(h: &host::PhpHost, v: &Value) -> bool {
    matches!(v, Value::Obj(id) if h.debug_info.contains_key(id))
        && (h.is_closure(v) || h.is_generator_val(v))
}

/// How `var_dump` and `print_r` label one property row of an object.
enum PropRow {
    /// A public (or dynamic) property.
    Named(String),
    /// An integer key, which only a `__debugInfo` array can produce.
    Index(i64),
    Protected(String),
    /// `(declaring class, name)`.
    Private(String, String),
}

/// The row label for a declared or dynamic property `name` of `class`.
fn prop_row(h: &host::PhpHost, class: &str, name: String) -> PropRow {
    if let Value::Int(n) = host::prop_key(&name) {
        return PropRow::Index(n);
    }
    match h.prop_visibility(class, &name) {
        Some((_, crate::ast::Visibility::Protected)) => PropRow::Protected(name),
        Some((declaring, crate::ast::Visibility::Private)) => PropRow::Private(declaring, name),
        _ => PropRow::Named(name),
    }
}

/// The `(label, value, is_reference)` rows `var_dump` / `print_r` show for
/// object `v`: its `__debugInfo` answer when one was collected, read the way
/// `php_var_dump`'s `php_object_property_dump` reads a key — `"\0*\0p"` is
/// protected, `"\0Class\0p"` private to `Class`, an integer key bare — and its
/// properties otherwise.
fn debug_rows(h: &host::PhpHost, v: &Value, class: &str) -> Vec<(PropRow, Value, bool)> {
    let info = match v {
        Value::Obj(id) => h.debug_info.get(id),
        _ => None,
    };
    let Some(info) = info else {
        let mut rows: Vec<(PropRow, Value, bool)> = h
            .object_props_marked(v)
            .into_iter()
            .map(|(name, val, r)| (prop_row(h, class, name), val, r))
            .collect();
        // `spl_array_get_debug_info`: the ordinary properties, then the
        // storage, which the reference keeps outside the property table.
        if h.spl_array_flags(v).is_some() {
            if let Some(i) = rows.iter().position(|(row, ..)| {
                matches!(row, PropRow::Private(c, n)
                    if n == "storage" && (c == "ArrayObject" || c == "ArrayIterator"))
            }) {
                let storage = rows.remove(i);
                rows.push(storage);
            }
        }
        return rows;
    };
    h.array_pairs_marked(info)
        .unwrap_or_default()
        .into_iter()
        .map(|(k, val, r)| {
            let row = match k {
                Value::Int(n) => PropRow::Index(n),
                k => {
                    let key = h.to_str(&k);
                    match key
                        .strip_prefix('\0')
                        .and_then(|rest| rest.split_once('\0'))
                    {
                        Some(("*", name)) => PropRow::Protected(name.to_string()),
                        Some((declaring, name)) => {
                            PropRow::Private(declaring.to_string(), name.to_string())
                        }
                        None => PropRow::Named(key),
                    }
                }
            };
            (row, val, r)
        })
        .collect()
}

/// `print_r` of an object: the same parenthesised block an array gets, headed by
/// the class name rather than `Array`, and with each non-public property name
/// annotated — `[b:protected]`, `[c:Declaring:private]`.
///
/// An `enum` case heads its block `Suit Enum:string` (a backed enum, naming the
/// backing type) or `Suit Enum` (a pure one), which is why it cannot simply reuse
/// the object path.
fn php_print_r_object(
    h: &host::PhpHost,
    v: &Value,
    depth: usize,
    seen: &mut host::Visiting,
) -> String {
    let pad = "    ".repeat(depth);
    let inner = "    ".repeat(depth + 1);
    let class = h
        .object_class(v)
        .or_else(|| h.instance_class(v))
        .unwrap_or_else(|| "stdClass".to_string());
    // An anonymous class prints only the head of its name — see `display_class`.
    let shown = host::display_class(&class);
    let head = match h.enum_case_of(v) {
        Some((_, Some(backing))) => format!("{shown} Enum:{}", enum_backing_type(&backing)),
        Some((_, None)) => format!("{shown} Enum"),
        None => format!("{shown} Object"),
    };
    if !seen.enter(v) {
        return format!("{head}\n *RECURSION*");
    }
    let mut s = format!("{head}\n{pad}(\n");
    for (row, val, _) in debug_rows(h, v, &class) {
        let label = match row {
            PropRow::Named(name) => name,
            PropRow::Index(n) => n.to_string(),
            PropRow::Protected(name) => format!("{name}:protected"),
            PropRow::Private(declaring, name) => format!("{name}:{declaring}:private"),
        };
        s.push_str(&format!(
            "{inner}[{label}] => {}\n",
            php_print_r(h, &val, depth + 2, seen)
        ));
    }
    s.push_str(&format!("{pad})\n"));
    seen.leave();
    s
}

/// The name `print_r` gives a backed enum's backing type in its header line.
/// Only `int` and `string` can back an enum, so anything else cannot arise.
fn enum_backing_type(backing: &Value) -> &'static str {
    match backing {
        Value::Int(_) => "int",
        _ => "string",
    }
}

/// `var_dump` rendering for scalars and one level of arrays.
fn php_var_dump(h: &host::PhpHost, v: &Value, depth: usize) -> String {
    php_var_dump_ref(h, v, depth, false, &mut host::Visiting::default())
}

/// `var_dump` of one value. `is_ref` marks a slot a `&` binding has turned into a
/// reference: PHP prefixes such a value's type with `&` (`&int(2)`), between the
/// indentation and the type, at every nesting level.
fn php_var_dump_ref(
    h: &host::PhpHost,
    v: &Value,
    depth: usize,
    is_ref: bool,
    seen: &mut host::Visiting,
) -> String {
    let pad = "  ".repeat(depth);
    // Unlike `print_r`, `var_dump` replaces the WHOLE value — type header and
    // all — with the marker.
    if h.is_object(v) || h.is_array(v) {
        if !seen.enter(v) {
            return format!("{pad}*RECURSION*\n");
        }
        let out = php_var_dump_body(h, v, depth, is_ref, seen);
        seen.leave();
        return out;
    }
    php_var_dump_body(h, v, depth, is_ref, seen)
}

/// The body of [`php_var_dump_ref`], entered only once the recursion guard has
/// admitted `v`.
fn php_var_dump_body(
    h: &host::PhpHost,
    v: &Value,
    depth: usize,
    is_ref: bool,
    seen: &mut host::Visiting,
) -> String {
    let pad = "  ".repeat(depth);
    let amp = if is_ref { "&" } else { "" };
    match v {
        Value::Undef => format!("{pad}NULL\n"),
        Value::Bool(b) => format!("{pad}{amp}bool({})\n", if *b { "true" } else { "false" }),
        Value::Int(n) => format!("{pad}{amp}int({n})\n"),
        // var_dump reports floats at serialize_precision, not echo's precision=14.
        Value::Float(f) => format!(
            "{pad}{amp}float({})\n",
            crate::stdlib::types::serialize_float(*f)
        ),
        Value::Str(s) => format!("{pad}{amp}string({}) \"{s}\"\n", crate::bytes::byte_len(s)),
        // `php_var_dump`'s IS_RESOURCE arm: the number, and the type name
        // `zend_rsrc_list_get_rsrc_type` gives — `Unknown` once it is closed.
        Value::Obj(_) if h.is_stream(v) => {
            let s = h.stream_any(v).expect("checked by is_stream");
            format!("{pad}{amp}resource({}) of type ({})\n", s.id, s.type_name())
        }
        // A class instance prints as `object(Class)#n (count) { ... }` with its
        // properties, not as the bare array its handle would otherwise yield.
        // An `enum` case is one line naming the case, not the two-property
        // object it is implemented as.
        Value::Obj(_) if h.enum_case_of(v).is_some() => {
            let class = h.object_class(v).unwrap_or_default();
            let (case, _) = h.enum_case_of(v).unwrap_or_default();
            format!("{pad}{amp}enum({class}::{case})\n")
        }
        Value::Obj(_) if h.is_object(v) || is_dumped_closure(h, v) => {
            let class = h
                .object_class(v)
                .or_else(|| h.instance_class(v))
                .unwrap_or_else(|| "stdClass".to_string());
            let props = debug_rows(h, v, &class);
            let mut s = format!(
                "{pad}{amp}object({})#{} ({}) {{\n",
                host::display_class(&class),
                h.object_ordinal(v),
                props.len()
            );
            // A non-public property carries its visibility in the key, and a
            // private one also names the class that declared it.
            let label = |row: &PropRow| match row {
                PropRow::Named(name) => format!("\"{name}\""),
                PropRow::Index(n) => n.to_string(),
                PropRow::Protected(name) => format!("\"{name}\":protected"),
                PropRow::Private(declaring, name) => {
                    format!("\"{name}\":\"{declaring}\":private")
                }
            };
            // An uninitialized typed property is not counted in the header, but
            // its slot still prints, as `php_var_dump` walks the declared slots.
            // A `__debugInfo` answer replaces the slots altogether.
            let uninit = match v {
                Value::Obj(id) if h.debug_info.contains_key(id) => Vec::new(),
                _ => h.uninit_slots(v),
            };
            let mut uninit = uninit.into_iter().peekable();
            let inner = "  ".repeat(depth);
            for (i, (row, val, pref)) in props.into_iter().enumerate() {
                while let Some((_, uname, ty)) = uninit.next_if(|(at, _, _)| *at <= i) {
                    s.push_str(&format!(
                        "{inner}  [{}]=>\n{inner}  uninitialized({ty})\n",
                        label(&prop_row(h, &class, uname))
                    ));
                }
                s.push_str(&format!("{inner}  [{}]=>\n", label(&row)));
                s.push_str(&php_var_dump_ref(h, &val, depth + 1, pref, seen));
            }
            for (_, uname, ty) in uninit {
                s.push_str(&format!(
                    "{inner}  [{}]=>\n{inner}  uninitialized({ty})\n",
                    label(&prop_row(h, &class, uname))
                ));
            }
            s.push_str(&format!("{pad}}}\n"));
            s
        }
        Value::Obj(_) => {
            let pairs = h.array_pairs_marked(v).unwrap_or_default();
            let mut s = format!("{pad}{amp}array({}) {{\n", pairs.len());
            for (k, val, eref) in pairs {
                let key = match k {
                    Value::Int(n) => format!("{}  [{n}]=>\n", "  ".repeat(depth)),
                    other => format!("{}  [\"{}\"]=>\n", "  ".repeat(depth), h.to_str(&other)),
                };
                s.push_str(&key);
                s.push_str(&php_var_dump_ref(h, &val, depth + 1, eref, seen));
            }
            s.push_str(&format!("{pad}}}\n"));
            s
        }
        _ => format!("{pad}NULL\n"),
    }
}

// ── string helpers (added stdlib wave) ───────────────────────────────────────

/// PHP's `zend_binary_strcmp`, which is what `strcmp` and its relatives return.
///
/// It is *not* a sign: over the shared prefix the result is the difference of the
/// first differing byte (`strcmp("a", "z")` is -25, not -1), because PHP returns
/// `memcmp`'s value unchanged. Only when one string is a prefix of the other does
/// it fall back to a three-way compare of the lengths, which is -1/0/1.
pub(crate) fn binary_strcmp(a: &[u8], b: &[u8]) -> i64 {
    for (x, y) in a.iter().zip(b) {
        if x != y {
            return *x as i64 - *y as i64;
        }
    }
    match a.len().cmp(&b.len()) {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// Sign of an ordering as PHP's strcmp-style -1/0/1.
fn sign(o: std::cmp::Ordering) -> i64 {
    match o {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// `substr_compare($haystack, $needle, $offset, $length = null, $case_insensitive
/// = false)` — port of `PHP_FUNCTION(substr_compare)` (php-src 8.5
/// `ext/standard/string.c:6216`) over `zend_binary_strncmp` /
/// `zend_binary_strncasecmp_l` (`Zend/zend_operators.c:3259`, `:3340`).
///
/// The result is NOT normalized to -1/0/1: when the compared bytes differ the
/// answer is their signed difference (`substr_compare("abc","abz",0,3)` is -23),
/// and only a tie on content falls back to the three-way length comparison.
fn php_substr_compare(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let main = h.to_str(&arg(args, 0));
    let needle = h.to_str(&arg(args, 1));
    let mb = &*crate::bytes::to_bytes(&main);
    let nb = &*crate::bytes::to_bytes(&needle);
    let slen = mb.len() as i64;

    let len_given = matches!(args.get(3), Some(v) if !matches!(v, Value::Undef));
    let len = if len_given {
        host::long_of(&arg(args, 3))
    } else {
        0
    };
    if len_given && len <= 0 {
        if len == 0 {
            return Ok(Value::int(0));
        }
        return Err(throws(
            "ValueError",
            "substr_compare(): Argument #4 ($length) must be greater than or equal to 0",
        ));
    }

    let mut off = host::long_of(&arg(args, 2));
    if off < 0 {
        off = (slen + off).max(0);
    }
    if off > slen {
        return Err(throws(
            "ValueError",
            "substr_compare(): Argument #3 ($offset) must be contained in argument #1 ($haystack)",
        ));
    }
    let off = off as usize;
    let ci = args.get(4).map(|v| h.is_truthy(v)).unwrap_or(false);

    let hay = &mb[off..];
    // `len == 0` here means "not supplied": upstream's `cmp_len = len ? len :
    // MAX(needle_len, haystack_len - offset)`.
    let cmp_len = if len != 0 {
        len as usize
    } else {
        nb.len().max(hay.len())
    };

    let n = cmp_len.min(hay.len()).min(nb.len());
    for i in 0..n {
        let (a, b) = if ci {
            (
                hay[i].to_ascii_lowercase() as i64,
                nb[i].to_ascii_lowercase() as i64,
            )
        } else {
            (hay[i] as i64, nb[i] as i64)
        };
        if a != b {
            return Ok(Value::int(a - b));
        }
    }
    Ok(Value::int(sign(
        cmp_len.min(hay.len()).cmp(&cmp_len.min(nb.len())),
    )))
}

fn php_str_split(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let s = h.to_str(&arg(args, 0));
    let raw_len = args.get(1).map(crate::host::long_of).unwrap_or(1);
    if raw_len < 1 {
        return Err(throws(
            "ValueError",
            "str_split(): Argument #2 ($length) must be greater than 0",
        ));
    }
    let len = usize::try_from(raw_len).unwrap_or(usize::MAX);
    // Chunks of BYTES: `str_split("é")` is two one-byte strings.
    let bytes = crate::bytes::to_bytes(&s);
    let arr = h.new_array();
    // PHP 8.2 changed this: an empty subject is an EMPTY array, where PHP 8.1
    // and earlier answered `[""]`. Chunking an empty slice already yields no
    // chunks, so the case needs no arm of its own — it needed one only to
    // produce the old answer.
    for chunk in bytes.chunks(len) {
        h.arr_push_auto(&arr, Value::str(crate::bytes::from_bytes(chunk)));
    }
    Ok(arr)
}

fn php_str_pad(h: &host::PhpHost, args: &[Value]) -> Result<String, String> {
    let s = h.to_str(&arg(args, 0));
    let target = host::long_of(&arg(args, 1));
    // An explicitly EMPTY pad string is rejected; an omitted one defaults to a
    // space. Silently substituting the default for `""` turns an error into a
    // plausible-looking result.
    let pad = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => {
            let p = h.to_str(v);
            if p.is_empty() {
                return Err(throws(
                    "ValueError",
                    "str_pad(): Argument #3 ($pad_string) must not be empty",
                ));
            }
            p
        }
        _ => " ".to_string(),
    };
    // STR_PAD_RIGHT=1 (default), STR_PAD_LEFT=0, STR_PAD_BOTH=2.
    let ty = args.get(3).map(crate::host::long_of).unwrap_or(1);
    let cur = crate::bytes::byte_len(&s) as i64;
    if target <= cur {
        return Ok(s);
    }
    let need = (target - cur) as usize;
    // The pad string repeats BYTE by byte, as the width is counted: a
    // multi-byte pad fills `n` bytes, not `n` characters.
    let make = |n: usize| -> String {
        let bytes: Vec<u8> = crate::bytes::to_bytes(&pad)
            .iter()
            .copied()
            .cycle()
            .take(n)
            .collect();
        crate::bytes::from_bytes(&bytes)
    };
    Ok(crate::bytes::canonical(match ty {
        0 => format!("{}{}", make(need), s),
        2 => {
            let left = need / 2;
            let right = need - left;
            format!("{}{}{}", make(left), s, make(right))
        }
        _ => format!("{}{}", s, make(need)),
    }))
}

/// `ucwords($string, $separators = " \t\r\n\f\v")` — uppercase the first byte and
/// every byte that directly follows a separator.
///
/// The `$separators` argument *replaces* the default set rather than extending
/// it, so `ucwords("hello world-foo bar", "-")` capitalises only after the dash
/// and yields `"Hello world-Foo bar"`. Byte-wise and ASCII-only, like the rest of
/// PHP's case family.
fn ucwords(s: &str, separators: &str) -> String {
    let delims: Vec<u8> = separators.bytes().collect();
    let mut bytes = (*crate::bytes::to_bytes(s)).to_vec();
    let mut cap = true;
    for b in &mut bytes {
        if cap {
            b.make_ascii_uppercase();
        }
        cap = delims.contains(b);
    }
    // Only ASCII bytes were altered, so the original UTF-8 structure survives.
    crate::bytes::from_bytes(&bytes)
}

fn lcfirst(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        // ASCII-only, mirroring `ucfirst`.
        Some(first) if first.is_ascii() => std::iter::once(first.to_ascii_lowercase())
            .chain(c)
            .collect(),
        _ => s.to_string(),
    }
}

/// Port of `number_format()` (`ext/standard/math.c`, PHP 8.3+).
///
/// An `int` argument takes `_php_math_number_format_long`: it never passes
/// through a double, so every digit of `PHP_INT_MAX` survives, and a negative
/// `$decimals` rounds the integer to a power of ten half away from zero — in a
/// width that can carry `PHP_INT_MAX` rounded up past `i64`. A `float` is
/// rounded to `$decimals` places first (negative places included) and only
/// then is `$decimals` clamped to zero for the formatting.
fn php_number_format(h: &host::PhpHost, args: &[Value]) -> String {
    let dec_arg = args.get(1).map(crate::host::long_of).unwrap_or(0);
    let dec = dec_arg.max(0) as usize;
    let dp = args
        .get(2)
        .map(|v| h.to_str(v))
        .unwrap_or_else(|| ".".to_string());
    let ts = args
        .get(3)
        .map(|v| h.to_str(v))
        .unwrap_or_else(|| ",".to_string());
    let (neg, int_part, frac_part) = match h.to_number(&arg(args, 0)) {
        Value::Int(n) => {
            let mut mag = (n as i128).abs();
            if dec_arg < 0 {
                // |n| < 10^19, so any power past 10^19 rounds it to zero.
                mag = match 10i128.checked_pow(dec_arg.unsigned_abs().min(20) as u32) {
                    Some(p) if dec_arg >= -19 => (mag + p / 2) / p * p,
                    _ => 0,
                };
            }
            (n < 0 && mag != 0, mag.to_string(), "0".repeat(dec))
        }
        v => {
            let num = v.to_float();
            // PHP rounds the value with _php_math_round (half away from zero,
            // with pre-rounding) before formatting, so 1.005 becomes "1.01".
            let rounded = php_round(
                num,
                dec_arg.clamp(i32::MIN as i64, i32::MAX as i64) as i32,
                1,
            )
            .abs();
            let formatted = format!("{:.*}", dec, rounded);
            let (i, f) = match formatted.split_once('.') {
                Some((i, f)) => (i.to_string(), f.to_string()),
                None => (formatted.clone(), String::new()),
            };
            let nonzero = i.chars().any(|c| c != '0') || f.chars().any(|c| c != '0');
            (num < 0.0 && nonzero, i, f)
        }
    };
    // Group the integer part into threes.
    let bytes: Vec<char> = int_part.chars().collect();
    let mut grouped = String::new();
    for (i, c) in bytes.iter().enumerate() {
        if i > 0 && (bytes.len() - i) % 3 == 0 {
            grouped.push_str(&ts);
        }
        grouped.push(*c);
    }
    let mut out = String::new();
    if neg {
        out.push('-');
    }
    out.push_str(&grouped);
    if dec > 0 {
        out.push_str(&dp);
        out.push_str(&frac_part);
    }
    out
}

// ── math helpers ─────────────────────────────────────────────────────────────

/// Port of PHP's `php_round_helper`: the tie-break the `$mode` argument
/// selects. Only a value exactly halfway between two integers is affected — every
/// other value rounds to nearest regardless of mode, which is why the mode can be
/// applied as a correction to `f64::round` rather than replacing it.
///
/// `f64::round` is already half-away-from-zero, so `PHP_ROUND_HALF_UP` (and any
/// unrecognised mode, as in the reference) needs no correction.
fn round_half(value: f64, mode: i64) -> f64 {
    let away = value.round();
    if (value - value.trunc()).abs() != 0.5 {
        return away;
    }
    let toward = value.trunc();
    match mode {
        PHP_ROUND_HALF_DOWN => toward,
        PHP_ROUND_HALF_EVEN => {
            if away % 2.0 == 0.0 {
                away
            } else {
                toward
            }
        }
        PHP_ROUND_HALF_ODD => {
            if away % 2.0 == 0.0 {
                toward
            } else {
                away
            }
        }
        _ => away,
    }
}

const PHP_ROUND_HALF_DOWN: i64 = 2;
const PHP_ROUND_HALF_EVEN: i64 = 3;
const PHP_ROUND_HALF_ODD: i64 = 4;

/// Port of PHP's `_php_math_round`. `mode` is one of the `PHP_ROUND_HALF_*`
/// constants and reaches every tie-break this function takes, including the ones
/// inside the pre-rounding step — applying it only to the final rounding would
/// give the right answer for `round(2.5, 0, …)` and the wrong one whenever
/// pre-rounding engages.
///
/// The pre-rounding step compensates for binary floating-point representation
/// error so decimal half-way values print the way PHP prints them — e.g.
/// `round(1.005, 2)` is `1.01`, not the `1.0` a naive `(x*100).round()/100`
/// yields because the nearest f64 to 1.005 is slightly below it.
pub(crate) fn php_round(value: f64, places: i32, mode: i64) -> f64 {
    if !value.is_finite() || value == 0.0 {
        return value;
    }
    // `_php_math_round`'s first act: pull `places` up off `INT_MIN`, because the
    // very next thing it does is take its absolute value and `abs(INT_MIN)` has
    // no answer. Without this, `round(1.5, PHP_INT_MIN)` panics.
    let places = places.max(i32::MIN + 1);
    // php_intlog10abs: floor(log10(|value|)).
    let precision_places = 14 - value.abs().log10().floor() as i32;
    let f1 = 10f64.powi(places.abs());
    let tmp_value = if precision_places > places && precision_places - 15 < places {
        let f2 = 10f64.powi(precision_places.abs());
        let mut t = if precision_places >= 0 {
            value * f2
        } else {
            value / f2
        };
        t = round_half(t, mode);
        let up = places - precision_places;
        let f3 = 10f64.powi(up.abs());
        t = if up >= 0 { t * f3 } else { t / f3 };
        round_half(t, mode)
    } else {
        let t = if places >= 0 { value * f1 } else { value / f1 };
        if t.abs() >= 1e15 {
            return value;
        }
        round_half(t, mode)
    };
    // `_php_math_round`'s last step. Simple division is only used while the
    // scale factor is still finite; past `|places| >= 23` the reference formats
    // the mantissa and the exponent into a string and re-parses it, because
    // `tmp_value * exponent` would be `0 * INF` — a NaN — for a saturated
    // `$precision`.
    if places.abs() < 23 {
        if places > 0 {
            tmp_value / f1
        } else {
            tmp_value * f1
        }
    } else {
        format!("{:15.6}e{}", tmp_value, -i64::from(places))
            .trim()
            .parse::<f64>()
            .unwrap_or(tmp_value)
    }
}

/// The host borrow is taken for the coercion and RELEASED before the
/// deprecation check, which takes its own — holding one across the other panics
/// the `RefCell`.
fn php_pow(args: &[Value]) -> Value {
    let (an, bn) = with_host(|h| (h.to_number(&arg(args, 0)), h.to_number(&arg(args, 1))));
    deprecate_zero_base_negative_exponent(&an, &bn);
    match (an, bn) {
        (Value::Int(x), Value::Int(y)) if y >= 0 => match checked_ipow(x, y as u32) {
            Some(v) => Value::int(v),
            None => Value::float((x as f64).powf(y as f64)),
        },
        (an, bn) => Value::float(an.to_float().powf(bn.to_float())),
    }
}

fn php_intdiv(args: &[Value]) -> Result<Value, String> {
    let (a, b) = (arg(args, 0), arg(args, 1));
    // The `int` parameters were checked, and a lossy float deprecated, by
    // `argtypes::check_call` before the call got here; what is left is the
    // narrowing itself, which must not report a second time.
    let (x, y) = with_host(|h| (h.to_number(&a).to_int(), h.to_number(&b).to_int()));
    // Both of these are tagged rather than thrown directly, so the call goes out
    // through `call_builtin`'s error path and picks up the trace frame for the
    // call itself. `intdiv(1, 0)` inside `f()` is reported by the reference as
    //
    //   #0 t.php(2): intdiv(1, 0)
    //   #1 t.php(3): f()
    //
    // and throwing here without the tag dropped frame #0. The zero-divisor
    // OPERATORS (`1/0`, `1%0`) are the contrast: no function is being called, so
    // the reference shows no such frame and they still throw directly.
    if y == 0 {
        return Err(throws("DivisionByZeroError", "Division by zero"));
    }
    // `intdiv` has to answer an int, so the one quotient that does not fit is an
    // error rather than the float `/` widens to. It is an `ArithmeticError`, the
    // parent of `DivisionByZeroError` — a `catch (DivisionByZeroError)` does NOT
    // see it, so the two cannot share an arm.
    if x == i64::MIN && y == -1 {
        return Err(throws(
            "ArithmeticError",
            "Division of PHP_INT_MIN by -1 is not an integer",
        ));
    }
    Ok(Value::int(x / y))
}

// ── array helpers (added stdlib wave) ────────────────────────────────────────

/// Whether normalized keys form the list 0,1,2,… (so JSON/`array_merge` treat it
/// as a sequential array rather than a map).
fn is_list(pairs: &[(Value, Value)]) -> bool {
    pairs
        .iter()
        .enumerate()
        .all(|(i, (k, _))| matches!(k, Value::Int(n) if *n == i as i64))
}

fn php_array_merge(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let all: Vec<Vec<(Value, Value)>> = args.iter().filter_map(|a| h.array_pairs(a)).collect();
    let out = h.new_array();
    for pairs in all {
        for (k, v) in pairs {
            match k {
                // Integer keys are renumbered; string keys overwrite.
                Value::Int(_) => h.arr_push_auto(&out, v),
                _ => h.arr_set_key(&out, &k, v),
            }
        }
    }
    out
}

/// Whether `cb` names or holds something callable — a non-empty function-name
/// string or a closure handle. A non-callable callback drives the "identity"
/// paths of `array_map`/`array_filter`.
fn is_callable_arg(cb: &Value) -> bool {
    match cb {
        Value::Str(s) => !s.is_empty(),
        // `host::callable_method` covers the forms a closure check misses:
        // `[$obj, "m"]`, `["C", "m"]`, and an object whose class has `__invoke`.
        // Missing them here did not raise an error — `array_map` treated the
        // callback as absent and returned its input unmapped, which is a WRONG
        // ANSWER rather than a failure, and `array_filter` kept every element.
        v => with_host(|h| h.is_closure(v)) || host::callable_method(v).is_some(),
    }
}

fn php_array_map(args: &[Value]) -> Result<Value, String> {
    let cb = arg(args, 0);
    let callable = is_callable_arg(&cb);

    // Single-array form preserves keys; the callback (or identity) maps values.
    if args.len() <= 2 {
        let arr = arg(args, 1);
        let pairs = with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
        let mut mapped: Vec<(Value, Value)> = Vec::with_capacity(pairs.len());
        for (k, v) in pairs {
            let out = if callable {
                host::call_value(cb.clone(), vec![v])?
            } else {
                v
            };
            // A callback that threw stops the walk; the pending exception unwinds
            // through the `array_map(...)` call site.
            if host::unwinding() {
                return Ok(Value::Undef);
            }
            mapped.push((k, out));
        }
        return Ok(with_host(|h| {
            let out = h.new_array();
            for (k, v) in mapped {
                h.arr_set_key(&out, &k, v);
            }
            out
        }));
    }

    // Multi-array form: iterate up to the longest input by position (keys are
    // dropped, 0-based). With a null callback the rows are zipped into arrays.
    let arrays: Vec<Vec<Value>> = args[1..]
        .iter()
        .map(|a| {
            with_host(|h| h.array_pairs(a))
                .unwrap_or_default()
                .into_iter()
                .map(|(_, v)| v)
                .collect()
        })
        .collect();
    let len = arrays.iter().map(|a| a.len()).max().unwrap_or(0);
    let mut result: Vec<Value> = Vec::with_capacity(len);
    for i in 0..len {
        let row: Vec<Value> = arrays
            .iter()
            .map(|a| a.get(i).cloned().unwrap_or(Value::Undef))
            .collect();
        if callable {
            let out = host::call_value(cb.clone(), row)?;
            if host::unwinding() {
                return Ok(Value::Undef);
            }
            result.push(out);
        } else {
            // Null callback: zip each position into a sub-array.
            result.push(with_host(|h| {
                let sub = h.new_array();
                for v in row {
                    h.arr_push_auto(&sub, v);
                }
                sub
            }));
        }
    }
    Ok(with_host(|h| {
        let out = h.new_array();
        for v in result {
            h.arr_push_auto(&out, v);
        }
        out
    }))
}

/// `array_filter($array, $callback = null, $mode = 0)`.
///
/// `$mode` selects what the callback receives: the value (0), the value and the
/// key (`ARRAY_FILTER_USE_BOTH` == 1), or the key alone
/// (`ARRAY_FILTER_USE_KEY` == 2). It used to be ignored, so a `USE_KEY`
/// callback was handed the VALUE and `array_filter($a, fn($k) => $k == "a",
/// ARRAY_FILTER_USE_KEY)` dropped every element.
fn php_array_filter(args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    let cb = arg(args, 1);
    let mode = with_host(|h| h.to_number(&arg(args, 2))).to_int();
    let pairs = with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
    let callable = is_callable_arg(&cb);
    let mut kept: Vec<(Value, Value)> = Vec::new();
    for (k, v) in pairs {
        let keep = if callable {
            let cb_args = match mode {
                host::ARRAY_FILTER_USE_KEY => vec![k.clone()],
                host::ARRAY_FILTER_USE_BOTH => vec![v.clone(), k.clone()],
                _ => vec![v.clone()],
            };
            let r = host::call_value(cb.clone(), cb_args)?;
            if host::unwinding() {
                return Ok(Value::Undef);
            }
            with_host(|h| h.is_truthy(&r))
        } else {
            with_host(|h| h.is_truthy(&v))
        };
        if keep {
            kept.push((k, v));
        }
    }
    Ok(with_host(|h| {
        let out = h.new_array();
        for (k, v) in kept {
            h.arr_set_key(&out, &k, v);
        }
        out
    }))
}

fn php_array_reduce(args: &[Value]) -> Result<Value, String> {
    let arr = arg(args, 0);
    let cb = arg(args, 1);
    let init = arg(args, 2);
    let pairs = with_host(|h| h.array_pairs(&arr)).unwrap_or_default();
    if !is_callable_arg(&cb) {
        return Ok(init);
    }
    let mut acc = init;
    for (_, v) in pairs {
        acc = host::call_value(cb.clone(), vec![acc, v])?;
        if host::unwinding() {
            return Ok(Value::Undef);
        }
    }
    Ok(acc)
}

fn php_array_slice(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let arr = arg(args, 0);
    let pairs = h.array_pairs(&arr).unwrap_or_default();
    let n = pairs.len() as i64;
    let mut off = host::long_of(&arg(args, 1));
    if off < 0 {
        off = (n + off).max(0);
    }
    let off = off.min(n).max(0) as usize;
    let len = match args.get(2) {
        Some(v) if !matches!(v, Value::Undef) => {
            let l = v.to_int();
            if l < 0 {
                (n - off as i64 + l).max(0) as usize
            } else {
                l as usize
            }
        }
        _ => pairs.len() - off,
    };
    let preserve = args.get(3).map(|v| h.is_truthy(v)).unwrap_or(false);
    let end = (off + len).min(pairs.len());
    let out = h.new_array();
    for (k, v) in &pairs[off..end] {
        match k {
            Value::Int(_) if !preserve => h.arr_push_auto(&out, v.clone()),
            _ => h.arr_set_key(&out, k, v.clone()),
        }
    }
    out
}

fn php_array_reverse(h: &mut host::PhpHost, args: &[Value]) -> Value {
    let arr = arg(args, 0);
    let pairs = h.array_pairs(&arr).unwrap_or_default();
    let preserve = args.get(1).map(|v| h.is_truthy(v)).unwrap_or(false);
    let out = h.new_array();
    for (k, v) in pairs.into_iter().rev() {
        match k {
            Value::Int(_) if !preserve => h.arr_push_auto(&out, v),
            _ => h.arr_set_key(&out, &k, v),
        }
    }
    out
}

/// `array_sum` / `array_product` — port of `php_array_binop` (php-src 8.5
/// `ext/standard/array.c:6493`).
///
/// Upstream runs the real `+`/`*` on each entry and recovers from the `TypeError`
/// it may raise, so an entry that cannot take part is not silently zero: an
/// array or an object with no numeric cast contributes NOTHING and warns
/// `"<op> is not supported on type <type>"`, while a non-numeric STRING keeps the
/// pre-8 behaviour of counting as `0` — which is why `array_product([2, "a"])` is
/// `0` rather than `2`. A leading-numeric string such as `"2abc"` is a normal
/// coercion and raises `"A non-numeric value encountered"` instead.
fn php_array_fold(h: &mut host::PhpHost, arr: &Value, product: bool) -> Value {
    let op_name = if product {
        "Multiplication"
    } else {
        "Addition"
    };
    let fname = if product {
        "array_product"
    } else {
        "array_sum"
    };
    let mut pairs = h.array_pairs(arr).unwrap_or_default();
    // Resolve every entry to the number it contributes (or drop it), raising the
    // diagnostics in element order, BEFORE the fold picks an integer or float path.
    let mut terms: Vec<Value> = Vec::with_capacity(pairs.len());
    for (_, v) in pairs.drain(..) {
        let n = match host::classify_arith(&v) {
            host::ArithOperand::Numeric(n) => n,
            host::ArithOperand::Leading(n) => {
                h.warn("A non-numeric value encountered");
                n
            }
            host::ArithOperand::Unsupported => {
                let ty = host::arith_type_name(h, &v);
                h.warn(format!(
                    "{fname}(): {op_name} is not supported on type {ty}"
                ));
                match v {
                    Value::Str(_) => Value::int(0),
                    _ => continue,
                }
            }
        };
        terms.push(n);
    }
    let pairs: Vec<(Value, Value)> = terms.into_iter().map(|n| (Value::Undef, n)).collect();
    let all_int = pairs
        .iter()
        .all(|(_, v)| matches!(h.to_number(v), Value::Int(_)));
    if all_int {
        // An integer fold that overflows WIDENS to float rather than wrapping —
        // the same rule `+` and `*` follow — so `array_sum([PHP_INT_MAX, 1])` is
        // 9.2233720368547758E+18 and not a negative int. `wrapping_*` silently
        // produced the wrong VALUE here, with no diagnostic to notice.
        let mut acc: i64 = if product { 1 } else { 0 };
        for (_, v) in &pairs {
            let n = h.to_number(v).to_int();
            let stepped = if product {
                acc.checked_mul(n)
            } else {
                acc.checked_add(n)
            };
            match stepped {
                Some(next) => acc = next,
                // Redo the whole fold in floating point from the start: resuming
                // from `acc` would keep the already-rounded partial sum.
                None => return fold_as_float(h, &pairs, product),
            }
        }
        Value::int(acc)
    } else {
        fold_as_float(h, &pairs, product)
    }
}

/// The floating-point half of [`php_array_fold`], also used when an all-integer
/// fold overflows partway through.
fn fold_as_float(h: &host::PhpHost, pairs: &[(Value, Value)], product: bool) -> Value {
    let mut acc: f64 = if product { 1.0 } else { 0.0 };
    for (_, v) in pairs {
        let n = h.to_number(v).to_float();
        if product {
            acc *= n;
        } else {
            acc += n;
        }
    }
    Value::float(acc)
}

fn php_array_flip(h: &mut host::PhpHost, arr: &Value) -> Value {
    let pairs = h.array_pairs(arr).unwrap_or_default();
    let out = h.new_array();
    for (k, v) in pairs {
        // value becomes key, key becomes value (host normalizes the new key).
        // `PHP_FUNCTION(array_flip)` takes only an int or a string as a key.
        if !matches!(v, Value::Int(_) | Value::Str(_)) {
            h.warn("array_flip(): Can only flip string and integer values, entry skipped");
            continue;
        }
        h.arr_set_key(&out, &v, k);
    }
    out
}

/// `PHP_FUNCTION(array_unique)` (`ext/standard/array.c`).
///
/// `SORT_STRING`, the default, keeps the first element of each string form,
/// converting with the conversion's own diagnostics (an array element warns
/// `Array to string conversion`). Every other flag sorts `(element, position)`
/// pairs with `zend_sort` under the flag's comparison, then walks the sorted run
/// dropping each element equal to the last one kept, keeping whichever of the
/// two came first in the input. Equality here is the comparison's answer, so
/// `SORT_REGULAR` dedupes `"10"` against `1e1` and an object against an
/// equal-property instance of its class.
/// Whether `array_unique` runs under SORT_STRING (its default) over an
/// element that is an object with `__toString`.
fn unique_needs_tostring(args: &[Value]) -> bool {
    with_host(|h| {
        let string_mode = match args.get(1) {
            Some(v) if !matches!(v, Value::Undef) => v.to_int() == 2,
            _ => true,
        };
        string_mode
            && h.array_pairs(&arg(args, 0))
                .unwrap_or_default()
                .iter()
                .any(|(_, v)| is_stringable_object(h, v))
    })
}

fn php_array_unique(h: &mut host::PhpHost, args: &[Value]) -> Value {
    const SORT_STRING: i64 = 2;
    let pairs = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let flags = match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => v.to_int(),
        _ => SORT_STRING,
    };
    let out = h.new_array();
    if flags == SORT_STRING {
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        for (k, v) in pairs {
            if seen.insert(h.to_str_diag(&v)) {
                h.arr_set_key(&out, &k, v);
            }
        }
        return out;
    }
    let cmp = |h: &host::PhpHost, a: &Value, b: &Value| -> i32 {
        let ord = sort_flag_compare(h, a, b, flags);
        // `php_array_data_compare_unstable_i`'s enum arm: two enum cases are
        // uncomparable, so they are grouped by identity instead, and an enum
        // case sorts before anything else.
        if ord != 1 || flags & !8 != 0 || h.enum_case_of(b).is_none() {
            return ord;
        }
        match (a, b) {
            (Value::Obj(x), Value::Obj(y)) if h.enum_case_of(a).is_some() => sign(x.cmp(y)) as i32,
            _ => -1,
        }
    };
    let mut order: Vec<usize> = (0..pairs.len()).collect();
    crate::stdlib::zsort::zend_sort(&mut order, &mut |&i, &j| cmp(h, &pairs[i].1, &pairs[j].1));
    let mut keep = vec![true; pairs.len()];
    let mut last = order.first().copied();
    for &cur in order.iter().skip(1) {
        let Some(kept) = last else { break };
        if cmp(h, &pairs[kept].1, &pairs[cur].1) != 0 {
            last = Some(cur);
        } else if kept > cur {
            keep[kept] = false;
            last = Some(cur);
        } else {
            keep[cur] = false;
        }
    }
    for ((k, v), kept) in pairs.into_iter().zip(keep) {
        if kept {
            h.arr_set_key(&out, &k, v);
        }
    }
    out
}

fn php_array_key_exists(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let mut key = arg(args, 0);
    let arr = arg(args, 1);
    // `php_array_key_exists`: an array or object key is the container-offset
    // `TypeError`, and a null key has a deprecation of its own wording.
    if h.is_array(&arr) {
        if let Some(t) = h.bad_offset_type(&key) {
            return Err(throws(
                "TypeError",
                format!("Cannot access offset of type {t} on array"),
            ));
        }
        if matches!(key, Value::Undef) {
            h.deprecated(
                "Using null as the key parameter for array_key_exists() is deprecated, use an \
                 empty string instead",
            );
            key = Value::str("");
        }
    }
    if let Some(found) = h.array_has_key(&arr, &key) {
        return Ok(Value::bool(found));
    }
    // Not an array: an object receiver falls back to matching its property
    // names, which is what the reference does for `ArrayObject`/`stdClass`.
    let want = h.to_str(&key);
    let found = h
        .array_pairs(&arr)
        .unwrap_or_default()
        .iter()
        .any(|(k, _)| h.to_str(k) == want);
    Ok(Value::bool(found))
}

fn php_array_search(h: &host::PhpHost, args: &[Value]) -> Value {
    let needle = arg(args, 0);
    let arr = arg(args, 1);
    let strict = args.get(2).map(|v| h.is_truthy(v)).unwrap_or(false);
    for (k, v) in h.array_pairs(&arr).unwrap_or_default() {
        let hit = if strict {
            strict_eq(h, &needle, &v)
        } else {
            loose_eq(h, &needle, &v)
        };
        if hit {
            return k;
        }
    }
    Value::bool(false)
}

/// `sort`/`rsort` — sorts by value in place and re-indexes (keys 0..n), returning
/// `true`, like PHP. Arrays are reference handles here, so mutating the handle's
/// target is visible through the caller's `$var`.
/// Compare two values under a `SORT_*` flag from the sort family's second
/// argument.
///
/// `SORT_FLAG_CASE` (8) is a bit that combines with `SORT_STRING` or
/// `SORT_NATURAL` to fold case; the remaining bits select the comparison.
/// Anything unrecognised falls back to `SORT_REGULAR`, PHP's standard
/// comparison.
/// The `SORT_*` flags argument of the sort family (position 1), defaulting to
/// `SORT_REGULAR`.
fn sort_flags(args: &[Value]) -> i64 {
    match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => v.to_int(),
        _ => 0,
    }
}

fn sort_flag_compare(h: &host::PhpHost, a: &Value, b: &Value, flags: i64) -> i32 {
    const SORT_FLAG_CASE: i64 = 8;
    let fold_case = flags & SORT_FLAG_CASE != 0;
    match flags & !SORT_FLAG_CASE {
        // SORT_NUMERIC — compare both operands as floats.
        1 => cmp_f64(h.to_number(a).to_float(), h.to_number(b).to_float()),
        // SORT_STRING / SORT_LOCALE_STRING — byte comparison of the string forms.
        // There is no locale support, so both behave as the C locale.
        2 | 5 => {
            let (x, y) = (h.to_str(a), h.to_str(b));
            if fold_case {
                strcmp_i32(&ascii_lower(&x), &ascii_lower(&y))
            } else {
                strcmp_i32(&x, &y)
            }
        }
        // SORT_NATURAL — `natsort`'s digit-run-aware ordering.
        6 => sign(crate::stdlib::arrays::nat_cmp(
            &h.to_str(a),
            &h.to_str(b),
            fold_case,
        )) as i32,
        // SORT_REGULAR and anything unknown.
        _ => php_compare(h, a, b),
    }
}

fn php_sort(h: &mut host::PhpHost, arr: &Value, reverse: bool, flags: i64) -> Value {
    let mut vals: Vec<Value> = h
        .array_pairs(arr)
        .unwrap_or_default()
        .into_iter()
        .map(|(_, v)| v)
        .collect();
    // Reverse by inverting the comparator, not by reversing after the fact:
    // PHP sorts are stable, so equal elements must keep their original order in
    // `rsort` too (`rsort([1, "1"])` leaves `1` before `"1"`).
    crate::stdlib::zsort::zend_sort_stable(&mut vals, |a, b| {
        let r = sort_flag_compare(h, a, b, flags);
        // `php_array_reverse_*`: the forward answer negated, not the
        // operands swapped — the two differ for a mixed-type pair.
        if reverse {
            -r
        } else {
            r
        }
    });
    h.arr_set_reindexed(arr, vals);
    Value::bool(true)
}

/// `asort`/`arsort` — sorts by value in place, preserving keys; returns `true`.
fn php_asort(h: &mut host::PhpHost, arr: &Value, reverse: bool, flags: i64) -> Value {
    let mut pairs = h.array_pairs(arr).unwrap_or_default();
    // Stable reverse: invert the comparator rather than reversing the result.
    crate::stdlib::zsort::zend_sort_stable(&mut pairs, |(_, a), (_, b)| {
        let r = sort_flag_compare(h, a, b, flags);
        // `php_array_reverse_*`: the forward answer negated, not the
        // operands swapped — the two differ for a mixed-type pair.
        if reverse {
            -r
        } else {
            r
        }
    });
    h.arr_set_pairs(arr, pairs);
    Value::bool(true)
}

/// `ksort`/`krsort` — sorts by key in place, preserving keys; returns `true`.
fn php_ksort(h: &mut host::PhpHost, arr: &Value, reverse: bool, flags: i64) -> Value {
    let mut pairs = h.array_pairs(arr).unwrap_or_default();
    // Stable reverse: invert the comparator rather than reversing the result.
    crate::stdlib::zsort::zend_sort_stable(&mut pairs, |(a, _), (b, _)| {
        let r = sort_flag_compare(h, a, b, flags);
        // `php_array_reverse_*`: the forward answer negated, not the
        // operands swapped — the two differ for a mixed-type pair.
        if reverse {
            -r
        } else {
            r
        }
    });
    h.arr_set_pairs(arr, pairs);
    Value::bool(true)
}

/// `array_fill($start_index, $count, $value)`.
///
/// Ported from `PHP_FUNCTION(array_fill)` in `ext/standard/array.c`, whose four
/// outcomes are all distinguishable and all reachable: a negative `$count` is a
/// ValueError, a `$count` past `INT_MAX` is a different ValueError, a zero
/// `$count` is an empty array, and a `$start_index` so high that the last key
/// would pass `PHP_INT_MAX` is the same `Error` an ordinary `$a[] =` raises.
/// The order matters — the range check is made BEFORE any element is written,
/// so the failure leaves nothing behind.
fn php_array_fill(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let start = host::long_of(&arg(args, 0));
    let count = host::long_of(&arg(args, 1));
    let val = arg(args, 2);
    if count < 0 {
        return Err(throws(
            "ValueError",
            "array_fill(): Argument #2 ($count) must be greater than or equal to 0",
        ));
    }
    if count > i64::from(i32::MAX) {
        return Err(throws(
            "ValueError",
            "array_fill(): Argument #2 ($count) is too large",
        ));
    }
    let out = h.new_array();
    if count == 0 {
        return Ok(out);
    }
    if start > i64::MAX - count + 1 {
        return Err(throws_bare("Error", host::NEXT_ELEMENT_OCCUPIED));
    }
    for i in 0..count {
        h.arr_set_key(&out, &Value::int(start + i), val.clone());
    }
    Ok(out)
}

fn php_array_combine(h: &mut host::PhpHost, args: &[Value]) -> Result<Value, String> {
    let keys = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let vals = h.array_pairs(&arg(args, 1)).unwrap_or_default();
    if keys.len() != vals.len() {
        return Err(throws(
            "ValueError",
            "array_combine(): Argument #1 ($keys) and argument #2 ($values) \
             must have the same number of elements",
        ));
    }
    let out = h.new_array();
    for ((_, k), (_, v)) in keys.into_iter().zip(vals) {
        let k = string_key(h, k);
        h.arr_set_key(&out, &k, v);
    }
    Ok(out)
}

/// How `array_combine` and `array_fill_keys` turn a value into a key: an int
/// stays an int, anything else goes through its STRING form
/// (`zval_get_tmp_string`, then `zend_symtable_update`), so `1.5` is the key
/// `"1.5"`, `true` the key `1` and `null` the key `""`, with no offset
/// diagnostics.
pub(crate) fn string_key(h: &mut host::PhpHost, k: Value) -> Value {
    match k {
        Value::Int(_) | Value::Str(_) => k,
        other => Value::str(h.to_str_diag(&other)),
    }
}

/// `array_diff` (`intersect=false`) / `array_intersect` (`intersect=true`) over
/// the first array against the rest, compared by string form (PHP's default).
fn php_array_diff(h: &mut host::PhpHost, args: &[Value], intersect: bool) -> Value {
    let first = h.array_pairs(&arg(args, 0)).unwrap_or_default();
    let others: Vec<std::collections::HashSet<String>> = args[1.min(args.len())..]
        .iter()
        .map(|a| {
            h.array_pairs(a)
                .unwrap_or_default()
                .into_iter()
                .map(|(_, v)| h.to_str(&v))
                .collect()
        })
        .collect();
    let out = h.new_array();
    for (k, v) in first {
        let s = h.to_str(&v);
        let in_all = others.iter().all(|set| set.contains(&s));
        let in_any = others.iter().any(|set| set.contains(&s));
        let keep = if intersect { in_all } else { !in_any };
        if keep {
            h.arr_set_key(&out, &k, v);
        }
    }
    out
}

// ── var_export / json_encode ─────────────────────────────────────────────────

/// A string as `var_export` writes it: single-quoted with `\` and `'` escaped, and
/// every NUL byte, which no quoted literal can carry, spliced in as a
/// double-quoted `"\0"` between concatenated halves.
fn export_string(s: &str) -> String {
    let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
    format!("'{}'", escaped.replace('\0', "' . \"\\0\" . '"))
}

/// `var_export` of one value.
///
/// A circular structure is not fatal here either: the reference warns
/// `var_export does not handle circular references` — once per repeat it meets —
/// and emits `NULL` in that position, so the output stays syntactically valid
/// PHP even though it no longer rebuilds the original.
fn php_var_export(
    h: &mut host::PhpHost,
    v: &Value,
    depth: usize,
    seen: &mut host::Visiting,
) -> String {
    if (h.is_array(v) || h.is_object(v)) && !seen.enter(v) {
        h.warn("var_export does not handle circular references");
        return "NULL".to_string();
    }
    let out = php_var_export_body(h, v, depth, seen);
    if h.is_array(v) || h.is_object(v) {
        seen.leave();
    }
    out
}

fn php_var_export_body(
    h: &mut host::PhpHost,
    v: &Value,
    depth: usize,
    seen: &mut host::Visiting,
) -> String {
    match v {
        Value::Undef => "NULL".to_string(),
        Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
        // `ZEND_LONG_MIN` has no literal of its own: the reference spells it
        // `-9223372036854775807-1`, which reads back as an int.
        Value::Int(i64::MIN) => "-9223372036854775807-1".to_string(),
        Value::Int(n) => n.to_string(),
        // var_export prints floats at serialize_precision and guarantees the
        // result reads back as a float, so a whole number gains a ".0" tail
        // (`var_export(1.0, true)` is `"1.0"`, not `"1"`). NAN/INF are exempt.
        Value::Float(f) => {
            let s = crate::stdlib::types::serialize_float(*f);
            if f.is_finite() && !s.contains('.') {
                format!("{s}.0")
            } else {
                s
            }
        }
        Value::Str(s) => export_string(s),
        // A closure or a generator exports like an object of its engine class with
        // no properties.
        Value::Obj(_) if h.is_object_value(v) => php_var_export_object(h, v, depth, seen),
        Value::Obj(_) if h.is_array(v) => {
            let pad = "  ".repeat(depth);
            let inner = "  ".repeat(depth + 1);
            let mut out = "array (\n".to_string();
            for (k, val) in h.array_pairs(v).unwrap_or_default() {
                let key = match k {
                    Value::Int(n) => n.to_string(),
                    other => export_string(&h.to_str(&other)),
                };
                out.push_str(&format!(
                    "{inner}{key} => {},\n",
                    var_export_item(h, &val, depth + 1, seen)
                ));
            }
            out.push_str(&format!("{pad})"));
            out
        }
        _ => "NULL".to_string(),
    }
}

/// A value in an item position (`key => value`). PHP keeps a scalar on the key's
/// line but breaks BEFORE a nested array or object and starts its block at the
/// item's own indent, which is why the two cannot share one renderer.
fn var_export_item(
    h: &mut host::PhpHost,
    v: &Value,
    depth: usize,
    seen: &mut host::Visiting,
) -> String {
    let body = php_var_export(h, v, depth, seen);
    // A cycle collapses to the scalar `NULL`, which stays on the key's line —
    // the break is for a real nested BLOCK, not for anything array-typed.
    if (h.is_array(v) || h.is_object_value(v)) && body != "NULL" {
        format!("\n{}{body}", "  ".repeat(depth))
    } else {
        body
    }
}

/// A `var_export` array key: an integer bare, a string quoted and escaped.
fn var_export_key(h: &host::PhpHost, k: &Value) -> String {
    match k {
        Value::Int(i) => i.to_string(),
        _ => format!(
            "'{}'",
            h.to_str(k).replace('\\', "\\\\").replace('\'', "\\'")
        ),
    }
}

/// `var_export` of an object. The reference emits code that would rebuild it:
/// `\Class::__set_state(array( ... ))` for a declared class, the `(object)` cast
/// of an array for a `stdClass`, and the case constant itself for an `enum`.
///
/// Object bodies indent one space deeper than array bodies — three per level
/// rather than two — which is the engine's own inconsistency, not a typo.
fn php_var_export_object(
    h: &mut host::PhpHost,
    v: &Value,
    depth: usize,
    seen: &mut host::Visiting,
) -> String {
    let class = h
        .object_class(v)
        .or_else(|| h.instance_class(v))
        .unwrap_or_else(|| "stdClass".to_string());
    if let Some((case, _)) = h.enum_case_of(v) {
        return format!("\\{class}::{case}");
    }
    let pad = "  ".repeat(depth);
    let inner = format!("{pad}   ");
    let std = class == "stdClass";
    let mut out = if std {
        "(object) array(\n".to_string()
    } else {
        format!("\\{class}::__set_state(array(\n")
    };
    let pairs: Vec<(String, Value)> = match spl_view(h, v) {
        Some(view) => view
            .into_iter()
            .map(|(k, val)| (var_export_key(h, &k), val))
            .collect(),
        None => h
            .object_props(v)
            .into_iter()
            .map(|(n, val)| match host::prop_key(&n) {
                Value::Int(i) => (i.to_string(), val),
                _ => (
                    format!("'{}'", n.replace('\\', "\\\\").replace('\'', "\\'")),
                    val,
                ),
            })
            .collect(),
    };
    for (name, val) in pairs {
        out.push_str(&format!(
            "{inner}{} => {},\n",
            name,
            var_export_item(h, &val, depth + 1, seen)
        ));
    }
    out.push_str(&format!("{pad}{}", if std { ")" } else { "))" }));
    out
}

/// `count($a, COUNT_RECURSIVE)` — every element at every depth. A nested array
/// counts as one element AND contributes its own contents, so `[1, [2, 3]]` is
/// 4 rather than 2.
///
/// Recursion is into ARRAYS only. A `Countable` nested inside counts as a single
/// element and its own `count()` is never consulted — `count([new C], …)` is 1
/// however large `C` says it is — and a plain object is likewise one element.
/// A self-referential array does not make `count()` fail: the reference warns
/// `count(): Recursion detected` and stops descending at the repeat, counting
/// the offending element once like any other.
fn count_recursive(h: &mut host::PhpHost, v: &Value) -> i64 {
    count_recursive_seen(h, v, &mut host::Visiting::default())
}

fn count_recursive_seen(h: &mut host::PhpHost, v: &Value, seen: &mut host::Visiting) -> i64 {
    if !seen.enter(v) {
        h.warn("count(): Recursion detected");
        return 0;
    }
    let total = h
        .array_pairs(v)
        .unwrap_or_default()
        .iter()
        .map(|(_, val)| {
            if h.is_array(val) {
                1 + count_recursive_seen(h, val, seen)
            } else {
                1
            }
        })
        .sum();
    seen.leave();
    total
}

/// Whether `v` contains a NAN or INF anywhere, including nested in arrays and
/// object properties.
/// Whether any string in `v` — a value or a key — carries bytes that are not
/// UTF-8 (see `crate::bytes`).
fn has_invalid_utf8(h: &host::PhpHost, v: &Value) -> bool {
    match v {
        Value::Str(s) => !crate::bytes::is_utf8(s),
        Value::Obj(_) if h.is_object(v) => h
            .object_props(v)
            .iter()
            .any(|(k, val)| !crate::bytes::is_utf8(k) || has_invalid_utf8(h, val)),
        Value::Obj(_) => h.array_pairs(v).unwrap_or_default().iter().any(|(k, val)| {
            matches!(k, Value::Str(s) if !crate::bytes::is_utf8(s)) || has_invalid_utf8(h, val)
        }),
        _ => false,
    }
}

fn has_nonfinite_float(h: &host::PhpHost, v: &Value) -> bool {
    match v {
        Value::Float(f) => !f.is_finite(),
        Value::Obj(_) if h.is_object(v) => h
            .object_props(v)
            .iter()
            .any(|(_, val)| has_nonfinite_float(h, val)),
        Value::Obj(_) => h
            .array_pairs(v)
            .unwrap_or_default()
            .iter()
            .any(|(_, val)| has_nonfinite_float(h, val)),
        _ => false,
    }
}

/// Resolve every object in `v` down to the plain data `json_encode` can render,
/// recursively. Runs BEFORE the encoder and outside the host borrow, because two
/// of its cases execute PHP.
///
/// The reference's rules, in the order it applies them:
/// * A `JsonSerializable` encodes whatever `jsonSerialize()` returns, and that
///   result is resolved in turn (it may itself contain objects).
/// * A backed `enum` case encodes as its backing value; a pure one has no
///   representation at all and fails the whole encode with
///   `JSON_ERROR_NON_BACKED_ENUM`.
/// * Any other object encodes its PUBLIC properties only, which is why it is
///   rebuilt here as a fresh `stdClass` holding just those — private and
///   protected state never reaches the encoder.
///
/// `Err(code)` is a `JSON_ERROR_*` code: the encode yields `false`.
///
/// Under `JSON_PARTIAL_OUTPUT_ON_ERROR` nothing fails. Each value the encoder
/// cannot spell is replaced where it stands, exactly as `php_json_encode_zval`
/// (ext/json/json_encoder.c) writes it — a cycle as `null`, a non-finite float
/// and a pure enum case as a bare `0` — and the LAST such error, in document
/// order, is what `json_last_error()` reports afterwards. Non-finite floats are
/// resolved here, not in the encoder, so that one walk sees every error in the
/// order the reference meets them.
fn json_prepare(v: &Value, partial: bool) -> (Result<Value, i64>, i64) {
    let mut prep = JsonPrep {
        seen: host::Visiting::default(),
        partial,
        last_error: 0,
    };
    let out = json_prepare_seen(v, &mut prep);
    (out, prep.last_error)
}

/// The state one [`json_prepare`] walk threads through its recursion.
struct JsonPrep {
    /// The cycle guard. It lives HERE rather than in the encoder because this
    /// pass is what deep-copies the structure: by the time the encoder runs it
    /// is walking an acyclic copy.
    seen: host::Visiting,
    /// `JSON_PARTIAL_OUTPUT_ON_ERROR`: substitute instead of failing.
    partial: bool,
    /// The last `JSON_ERROR_*` substituted under `partial`, `0` for none.
    last_error: i64,
}

impl JsonPrep {
    /// Fail with `code`, or — under `JSON_PARTIAL_OUTPUT_ON_ERROR` — record it
    /// and stand `substitute` in for the value.
    fn refuse(&mut self, code: i64, substitute: Value) -> Result<Value, i64> {
        if self.partial {
            self.last_error = code;
            Ok(substitute)
        } else {
            Err(code)
        }
    }
}

fn json_prepare_seen(v: &Value, prep: &mut JsonPrep) -> Result<Value, i64> {
    if let Value::Float(f) = v {
        if !f.is_finite() && prep.partial {
            return prep.refuse(crate::stdlib::json::JSON_ERROR_INF_OR_NAN, Value::int(0));
        }
    }
    if with_host(|h| h.is_stream(v)) {
        // `php_json_encode_zval`'s default arm: a resource has no JSON
        // spelling, and partial output writes `null` in its place.
        return prep.refuse(
            crate::stdlib::json::JSON_ERROR_UNSUPPORTED_TYPE,
            Value::Undef,
        );
    }
    if with_host(|h| h.is_array(v)) {
        if !prep.seen.enter(v) {
            return prep.refuse(crate::stdlib::json::JSON_ERROR_RECURSION, Value::Undef);
        }
        let pairs = with_host(|h| h.array_pairs(v)).unwrap_or_default();
        let mut out = Vec::with_capacity(pairs.len());
        for (k, val) in pairs {
            out.push((k, json_prepare_seen(&val, prep)?));
        }
        prep.seen.leave();
        return Ok(with_host(|h| {
            let arr = h.new_array();
            h.arr_set_pairs(&arr, out);
            arr
        }));
    }
    if !with_host(|h| h.is_object(v)) {
        return Ok(v.clone());
    }
    if !prep.seen.enter(v) {
        return prep.refuse(crate::stdlib::json::JSON_ERROR_RECURSION, Value::Undef);
    }
    let class = with_host(|h| h.object_class(v)).unwrap_or_default();
    // `php_json_encode_zval` asks JsonSerializable first: an enum that
    // implements it encodes as its `jsonSerialize()` answer.
    if with_host(|h| h.class_is_a_pub(&class, "JsonSerializable")) {
        let produced = host::call_method(&class, "jsonSerialize", Some(v.clone()), Vec::new())
            .map_err(|_| crate::stdlib::json::JSON_ERROR_NON_BACKED_ENUM)?;
        let out = json_prepare_seen(&produced, prep);
        prep.seen.leave();
        return out;
    }
    if with_host(|h| h.is_enum_class(&class)) {
        prep.seen.leave();
        return match with_host(|h| h.enum_case_of(v)) {
            Some((_, Some(backing))) => Ok(backing),
            _ => prep.refuse(
                crate::stdlib::json::JSON_ERROR_NON_BACKED_ENUM,
                Value::int(0),
            ),
        };
    }
    let mut out = Vec::new();
    if let Some(pairs) = with_host(|h| spl_storage_pairs(h, v)) {
        // ArrayObject / ArrayIterator encode as their wrapped array.
        for (k, val) in pairs {
            let name = with_host(|h| h.to_str(&k));
            out.push((name, json_prepare_seen(&val, prep)?));
        }
        prep.seen.leave();
        return Ok(with_host(|h| h.new_transient_object(out)));
    }
    for (name, val) in with_host(|h| h.object_props(v)) {
        if with_host(|h| h.prop_visibility(&class, &name)).is_some() {
            continue;
        }
        let name = with_host(|h| h.to_str(&host::prop_key(&name)));
        out.push((name, json_prepare_seen(&val, prep)?));
    }
    prep.seen.leave();
    Ok(with_host(|h| h.new_transient_object(out)))
}

/// `json_encode` flags this encoder honours.
const JSON_UNESCAPED_SLASHES: i64 = 64;
/// What to do with a byte that is not UTF-8: drop it, or write U+FFFD.
const JSON_INVALID_UTF8_IGNORE: i64 = 1_048_576;
const JSON_INVALID_UTF8_SUBSTITUTE: i64 = 2_097_152;
/// Emit every array as a JSON OBJECT, even one whose keys are already `0..n`.
const JSON_FORCE_OBJECT: i64 = 16;
const JSON_PRETTY_PRINT: i64 = 128;
const JSON_UNESCAPED_UNICODE: i64 = 256;
/// The four HTML-safety flags, each escaping one character that is legal in JSON
/// but hostile inside a `<script>` block or an HTML attribute.
const JSON_HEX_TAG: i64 = 1;
const JSON_HEX_AMP: i64 = 2;
const JSON_HEX_APOS: i64 = 4;
const JSON_HEX_QUOT: i64 = 8;
/// Encode a NUMERIC STRING as the number it reads as.
const JSON_NUMERIC_CHECK: i64 = 32;
/// Substitute for a value that cannot be encoded instead of failing the encode.
const JSON_PARTIAL_OUTPUT_ON_ERROR: i64 = 512;
/// Spell an integral float with a `.0` so it decodes back as a float.
const JSON_PRESERVE_ZERO_FRACTION: i64 = 1024;
/// Leave U+2028/U+2029 raw under `JSON_UNESCAPED_UNICODE`; without it they are
/// still escaped, because they end a line in JavaScript.
const JSON_UNESCAPED_LINE_TERMINATORS: i64 = 2048;

/// A finite float as JSON spells it: `serialize_precision`, lowercase exponent,
/// and — under `JSON_PRESERVE_ZERO_FRACTION` — a `.0` appended when the digits
/// carry neither a fraction nor an exponent, as `smart_str_append_double`
/// (Zend/zend_smart_str.c) does with `zero_frac` set.
fn json_float(f: f64, flags: i64) -> String {
    let mut s = crate::stdlib::types::serialize_float(f).replace('E', "e");
    if flags & JSON_PRESERVE_ZERO_FRACTION != 0 && f.is_finite() && !s.contains(['.', 'e']) {
        s.push_str(".0");
    }
    s
}

/// `JSON_NUMERIC_CHECK`'s rendering of `s`, or `None` when the string is not
/// numeric and must be encoded as a string after all.
///
/// The test is PHP's own `is_numeric_string`, so leading AND trailing whitespace
/// are allowed (`" 5"`, `"5 "`, `"\n5"`) while `"0x1A"`, `"0b1"` and `"1_0"` are
/// not numeric. A string that reads as a non-finite double (`"1e999"`) has no
/// JSON spelling and stays a string, which is the reference's own guard.
///
/// The number is rendered by the same path a real float takes ([`json_float`]),
/// so an integral value loses its fractional part unless
/// `JSON_PRESERVE_ZERO_FRACTION` is set: `json_encode(["1e3"], JSON_NUMERIC_CHECK)`
/// is `[1000]`, matching `json_encode([1000.0])`, and `["1.0"]` under both flags
/// is `[1.0]`.
fn json_numeric_check(s: &str, flags: i64) -> Option<String> {
    match host::parse_php_number_full(s)? {
        Value::Int(n) => Some(n.to_string()),
        Value::Float(f) if f.is_finite() => Some(json_float(f, flags)),
        _ => None,
    }
}

/// Encode `v` as JSON. `depth` is the current nesting level, used only for
/// `JSON_PRETTY_PRINT` indentation (four spaces per level, as PHP emits).
fn php_json_encode(h: &host::PhpHost, v: &Value, flags: i64, depth: usize) -> String {
    let pretty = flags & JSON_PRETTY_PRINT != 0;
    match v {
        Value::Undef => "null".to_string(),
        Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
        Value::Int(n) => n.to_string(),
        // JSON uses serialize_precision too, but spells the exponent lowercase
        // (`1.0e+100`, where var_dump/serialize print `1.0E+100`).
        Value::Float(f) => json_float(*f, flags),
        Value::Str(s) => match (flags & JSON_NUMERIC_CHECK != 0)
            .then(|| json_numeric_check(s, flags))
            .flatten()
        {
            Some(n) => n,
            // Only partial output reaches here with bad bytes and no flag
            // for them: the string is `null`.
            None if !crate::bytes::is_utf8(s)
                && flags & (JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE) == 0 =>
            {
                "null".to_string()
            }
            None => json_string(s, flags),
        },
        Value::Obj(_) => {
            // A closure or a generator is an object with no properties: `{}`.
            let object = h.is_object_value(v);
            let pairs = if object {
                h.object_props(v)
                    .into_iter()
                    .map(|(k, val)| (host::prop_key(&k), val))
                    .collect()
            } else {
                h.array_pairs(v).unwrap_or_default()
            };
            // A real object always encodes as a JSON object, even with no
            // properties — `json_encode(new stdClass())` is `{}`, not `[]`.
            let as_list = is_list(&pairs) && !object && flags & JSON_FORCE_OBJECT == 0;
            let (open, close) = if as_list { ('[', ']') } else { ('{', '}') };
            if pairs.is_empty() {
                return format!("{open}{close}");
            }
            let items: Vec<String> = pairs
                .iter()
                .map(|(k, val)| {
                    let encoded = php_json_encode(h, val, flags, depth + 1);
                    if as_list {
                        encoded
                    } else {
                        let key = json_string(&h.to_str(k), flags);
                        let sep = if pretty { ": " } else { ":" };
                        format!("{key}{sep}{encoded}")
                    }
                })
                .collect();
            if pretty {
                let inner = "    ".repeat(depth + 1);
                let outer = "    ".repeat(depth);
                format!(
                    "{open}\n{inner}{}\n{outer}{close}",
                    items.join(&format!(",\n{inner}"))
                )
            } else {
                format!("{open}{}{close}", items.join(","))
            }
        }
        _ => "null".to_string(),
    }
}

/// The encoder writes decoded text (`JSON_UNESCAPED_UNICODE` copies a character
/// through), so its document is stored as text.
fn json_text(doc: String) -> Value {
    Value::str(crate::bytes::from_text(&doc).into_owned())
}

/// JSON-escape `s`. By default PHP escapes `/` as `\/` and every non-ASCII
/// character as a `\uXXXX` sequence (surrogate pairs above the BMP);
/// `JSON_UNESCAPED_SLASHES` and `JSON_UNESCAPED_UNICODE` turn those off.
///
/// The four `JSON_HEX_*` flags each escape one more character, and they spell
/// their hex digits in UPPER case where the control and unicode escapes spell
/// theirs in lower — `json_encode(["<é\x1f"], JSON_HEX_TAG)` is
/// `["\u003C\u00e9\u001f"]`, verified against the reference.
fn json_string(s: &str, flags: i64) -> String {
    let escape_slashes = flags & JSON_UNESCAPED_SLASHES == 0;
    let escape_unicode = flags & JSON_UNESCAPED_UNICODE == 0;
    let escape_terminators = flags & JSON_UNESCAPED_LINE_TERMINATORS == 0;
    // The decoded characters, with `None` for each invalid unit as
    // `php_next_utf8_char` groups them (substituted or dropped below).
    let units: Vec<Option<char>> = if crate::bytes::has_raw(s) {
        crate::bytes::php_utf8_units(s)
    } else {
        s.chars().map(Some).collect()
    };
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for unit in units {
        let Some(c) = unit else {
            if flags & JSON_INVALID_UTF8_SUBSTITUTE != 0 {
                out.push_str(if escape_unicode {
                    "\\ufffd"
                } else {
                    "\u{FFFD}"
                });
            }
            continue;
        };
        match c {
            '<' if flags & JSON_HEX_TAG != 0 => out.push_str("\\u003C"),
            '>' if flags & JSON_HEX_TAG != 0 => out.push_str("\\u003E"),
            '&' if flags & JSON_HEX_AMP != 0 => out.push_str("\\u0026"),
            '\'' if flags & JSON_HEX_APOS != 0 => out.push_str("\\u0027"),
            '"' if flags & JSON_HEX_QUOT != 0 => out.push_str("\\u0022"),
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            '/' if escape_slashes => out.push_str("\\/"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            '\u{2028}' if escape_terminators => out.push_str("\\u2028"),
            '\u{2029}' if escape_terminators => out.push_str("\\u2029"),
            c if escape_unicode && !c.is_ascii() => {
                // Above the BMP JSON needs an explicit UTF-16 surrogate pair.
                let mut buf = [0u16; 2];
                for unit in c.encode_utf16(&mut buf) {
                    out.push_str(&format!("\\u{unit:04x}"));
                }
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// `INCLUDE`: `include`/`require` and their `_once` forms. Stack `[path, kind]`.
fn b_include(vm: &mut VM, _: u8) -> Value {
    let kind = crate::ast::IncludeKind::from_code(vm.pop().to_int());
    let path = vm.pop();
    mark_frame_line(vm);
    match host::run_include(kind, &path) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `EVAL`: `eval($code)`. Stack `[code]`.
fn b_eval(vm: &mut VM, _: u8) -> Value {
    let code = vm.pop();
    mark_frame_line(vm);
    match host::run_eval(&code) {
        Ok(v) => bubbled(vm, v),
        Err(e) => fail_or_throw(vm, e),
    }
}

/// `%f`, `%g` and `%G` print the `LC_NUMERIC` decimal point (see
/// `php_sprintf_appenddouble`); `%F`, `%e`, `%h` and `%H` always print `.`.
fn locale_point(num: String, localized: bool) -> String {
    if !localized {
        return num;
    }
    match crate::stdlib::system::locale_decimal_point() {
        '.' => num,
        dp => num.replacen('.', &dp.to_string(), 1),
    }
}

/// Whether `++`/`--` took an int past `PHP_INT_MAX`/`PHP_INT_MIN` into a float.
fn overflowed_to_float(old: &Value, new: &Value) -> bool {
    matches!((old, new), (Value::Int(_), Value::Float(_)))
}

/// `zend_incdec_typed_prop`: an int property that `++`/`--` would overflow
/// into a float is refused unless its type admits `float`
/// (`zend_throw_incdec_prop_error`), and keeps its value. `true` once thrown.
fn incdec_overflow_refused(
    vm: &mut VM,
    owner: &str,
    name: &str,
    ty: &crate::ast::TypeHint,
    inc: bool,
) -> bool {
    if ty
        .parts
        .iter()
        .any(|p| p.eq_ignore_ascii_case("float") || p.eq_ignore_ascii_case("mixed"))
    {
        return false;
    }
    let parent = with_host(|h| h.class_parent(owner))
        .map(|p| with_host(|h| h.class_display_name(&p.to_ascii_lowercase())));
    let shown = ty.declared(owner, parent.as_deref());
    let (verb, bound) = if inc {
        ("increment", "maximal")
    } else {
        ("decrement", "minimal")
    };
    mark_frame_line(vm);
    throw_php(
        vm,
        "TypeError",
        &format!("Cannot {verb} property {owner}::${name} of type {shown} past its {bound} value"),
    );
    true
}

/// A write to `$recv->name` checked against the property's declared type
/// (`zend_verify_property_type`): the value to store — coerced in the
/// coercive mode — or `None` once the `TypeError` is thrown.
fn typed_prop_value(vm: &mut VM, recv: &Value, name: &str, val: Value) -> Option<Value> {
    let declared = with_host(|h| h.object_class(recv).and_then(|c| h.prop_type(&c, name)));
    match declared {
        Some((owner, ty)) => check_prop_type(vm, &owner, name, &ty, val),
        None => Some(val),
    }
}

fn check_prop_type(
    vm: &mut VM,
    owner: &str,
    name: &str,
    ty: &crate::ast::TypeHint,
    val: Value,
) -> Option<Value> {
    let parent = with_host(|h| h.class_parent(owner));
    let scope = host::TypeScope {
        self_class: Some(owner.to_string()),
        parent: parent.clone(),
        static_class: None,
    };
    match host::verify_type(val, ty, &scope) {
        Ok(v) => Some(v),
        Err(given) => {
            let parent_shown =
                parent.map(|p| with_host(|h| h.class_display_name(&p.to_ascii_lowercase())));
            let shown = ty.declared(owner, parent_shown.as_deref());
            mark_frame_line(vm);
            throw_php(
                vm,
                "TypeError",
                &format!("Cannot assign {given} to property {owner}::${name} of type {shown}"),
            );
            None
        }
    }
}