node-js 0.1.13

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
//! Builtin op handlers (compiler-emitted `CallBuiltin` ids) plus the JS standard
//! library (`console`, `Math`, `JSON`, `Object`, array/string methods) reachable
//! from the host. Handlers pop their arguments off the VM operand stack and
//! return the result value, which the VM pushes back.

use crate::host::{self, ops, with_host, FuncVal, JsObj, ObjKind};
use fusevm::{NumOp, Value, VM};
use indexmap::IndexMap;

/// Register every node-js builtin id on a VM.
pub fn install(vm: &mut VM) {
    vm.register_builtin(ops::GETLOCAL, b_getlocal);
    vm.register_builtin(ops::SETLOCAL, b_setlocal);
    vm.register_builtin(ops::SETLOCAL_STRICT, b_setlocal_strict);
    vm.register_builtin(ops::DECLARE, b_declare);
    vm.register_builtin(ops::DECLARE_CONST, b_declare_const);
    vm.register_builtin(ops::MARK_HOLE, b_mark_hole);
    vm.register_builtin(ops::DELNAME, b_delname);
    vm.register_builtin(ops::GETATTR, b_getattr);
    vm.register_builtin(ops::SETATTR, b_setattr);
    vm.register_builtin(ops::GETITEM, b_getitem);
    vm.register_builtin(ops::SETITEM, b_setitem);
    vm.register_builtin(ops::DELITEM, b_delitem);
    vm.register_builtin(ops::MKSTR, b_mkstr);
    vm.register_builtin(ops::MKARR, b_mkarr);
    vm.register_builtin(ops::MKOBJ, b_mkobj);
    vm.register_builtin(ops::CALL, b_call);
    vm.register_builtin(ops::CALL_METHOD, b_call_method);
    vm.register_builtin(ops::CALL_VALUE, b_call_value);
    vm.register_builtin(ops::NEW, b_new);
    vm.register_builtin(ops::TRUTHY, b_truthy);
    vm.register_builtin(ops::TOSTR, b_tostr);
    vm.register_builtin(ops::MKFUNC, b_mkfunc);
    vm.register_builtin(ops::GETITER, b_getiter);
    vm.register_builtin(ops::FORITER, b_foriter);
    vm.register_builtin(ops::FORIN_KEYS, b_forin_keys);
    vm.register_builtin(ops::FORIN_ALIVE, b_forin_alive);
    vm.register_builtin(ops::HOIST_TDZ, b_hoist_tdz);
    vm.register_builtin(ops::NEW_SPREAD, b_new_spread);
    vm.register_builtin(ops::SUPER_CALL_SPREAD, b_super_call_spread);
    vm.register_builtin(ops::CONTAINS, b_contains);
    vm.register_builtin(ops::SIG_RETURN, b_sig_return);
    vm.register_builtin(ops::BINOP, b_binop);
    vm.register_builtin(ops::UNARY, b_unary);
    vm.register_builtin(ops::STRICT_EQ, b_strict_eq);
    vm.register_builtin(ops::LOOSE_EQ, b_loose_eq);
    vm.register_builtin(ops::TYPEOF, b_typeof);
    vm.register_builtin(ops::LOAD_NULL, b_load_null);
    vm.register_builtin(ops::THROW, b_throw);
    vm.register_builtin(ops::TRY, b_try);
    vm.register_builtin(ops::NULLISH, b_nullish);
    vm.register_builtin(ops::UNPACK, b_unpack);
    vm.register_builtin(ops::BUILD_ARGS, b_build_args);
    vm.register_builtin(ops::THIS, b_this);
    vm.register_builtin(ops::INSTANCEOF, b_instanceof);
    vm.register_builtin(ops::DELPROP_NAME, b_delprop_name);
    vm.register_builtin(ops::APPLY, b_apply);
    vm.register_builtin(ops::APPLY_METHOD, b_apply_method);
    vm.register_builtin(ops::OBJ_REST, b_obj_rest);
    vm.register_builtin(ops::DIV, b_div);
    vm.register_builtin(ops::POW, b_pow);
    vm.register_builtin(ops::MKCLASS, b_mkclass);
    vm.register_builtin(ops::DEF_MEMBER, b_def_member);
    vm.register_builtin(ops::DEF_FIELD, b_def_field);
    vm.register_builtin(ops::SUPER_CALL, b_super_call);
    vm.register_builtin(ops::SUPER_GET, b_super_get);
    vm.register_builtin(ops::YIELD, b_yield);
    vm.register_builtin(ops::PROPKEY, b_propkey);
    vm.register_builtin(ops::NEW_TARGET, b_new_target);
    vm.register_builtin(ops::AWAIT, b_await);
    vm.register_builtin(ops::DEF_ACCESSOR, b_def_accessor);
    vm.register_builtin(ops::DBG_LINE, b_dbg_line);
    vm.register_builtin(ops::MKBIGINT, b_mkbigint);
    vm.register_builtin(ops::MKREGEX, b_mkregex);
    vm.register_builtin(ops::TAG_TMPL, b_tag_tmpl);
    vm.register_builtin(ops::GET_ASYNC_ITER, b_get_async_iter);
    vm.register_builtin(ops::ASYNC_STEP, b_async_step);
    vm.register_builtin(ops::NUM_STEP, b_num_step);
    vm.register_builtin(ops::ITER_CLOSE, b_iter_close);
    vm.register_builtin(ops::TYPEOF_NAME, b_typeof_name);
    vm.register_builtin(ops::SIG_BREAK, b_sig_break);
    vm.register_builtin(ops::SIG_CONTINUE, b_sig_continue);
    vm.register_builtin(ops::SIG_UNWIND, b_sig_unwind);
    vm.register_builtin(ops::PUSH_SCOPE, b_push_scope);
    vm.register_builtin(ops::POP_SCOPE, b_pop_scope);
    vm.register_builtin(ops::COPY_SCOPE, b_copy_scope);
    vm.register_builtin(ops::DECLARE_VAR, b_declare_var);
    vm.register_builtin(ops::HOIST_VAR, b_hoist_var);
    vm.register_builtin(ops::NAMED_EVAL, b_named_eval);
}

/// `ITER_CLOSE`: close the iterator on the stack (a for-of `break`). A generator
/// runs its pending `finally`; a user iterator object gets its `.return()` called
/// if present; a plain materialized iterator just drops. Returns `undefined`.
/// `IteratorClose` (7.4.9): resume a generator with a forced return so its
/// pending `finally` runs, or invoke a user iterator's `.return()`. A value that
/// is neither is left alone.
pub(crate) fn close_iterator(it: &Value) -> Result<(), String> {
    if with_host(|h| h.is_generator_val(it)) {
        host::gen_return(it, Value::Undef)?;
        return Ok(());
    }
    if matches!(with_host(|h| h.get(it).cloned()), Some(JsObj::Object(_))) {
        if let Some(f) = with_host(|h| host::lookup_chain(h, it, "return")) {
            if with_host(|h| host::is_callable(h, &f)) {
                host::invoke(&f, Vec::new(), Some(it.clone()))?;
            }
        }
    }
    Ok(())
}

fn b_iter_close(vm: &mut VM, _: u8) -> Value {
    let it = vm.pop();
    // A `finally` may print or yield, but the loop is done either way; an error
    // it raises still propagates.
    match close_iterator(&it) {
        Ok(()) => Value::Undef,
        Err(e) => abort(vm, e),
    }
}

/// `NUM_STEP`: the `++`/`--` core. Pops `old` and the step `tag` (`+1`/`-1`),
/// pushes `ToNumeric(old)` (a BigInt stays a BigInt, else a Number), and returns
/// `old ± 1` in the SAME numeric type — so `x++` on a BigInt neither coerces to
/// Number nor throws the mix error.
fn b_num_step(vm: &mut VM, _: u8) -> Value {
    let old = vm.pop();
    let tag = match vm.pop() {
        Value::Int(n) => n,
        Value::Float(f) => f as i64,
        _ => 1,
    };
    if with_host(|h| h.is_bigint_val(&old)) {
        let b = with_host(|h| h.as_bigint(&old)).unwrap();
        let old_n = with_host(|h| h.new_bigint(b.clone()));
        let new = with_host(|h| h.new_bigint(b + num_bigint::BigInt::from(tag)));
        vm.push(old_n);
        new
    } else {
        let n = with_host(|h| h.to_number(&old));
        vm.push(Value::Float(n));
        Value::Float(n + tag as f64)
    }
}

/// `ASYNC_STEP`: one step of a `for await` loop — returns a Promise of the
/// `{value, done}` record (see `host::async_step`).
fn b_async_step(vm: &mut VM, _: u8) -> Value {
    let iter = vm.pop();
    let r = host::async_step(&iter);
    finish(vm, r)
}

/// `MKBIGINT`: pop the canonical decimal digit string constant, allocate the heap
/// BigInt. The lexer already validated the digits, so parsing cannot fail here.
fn b_mkbigint(vm: &mut VM, _: u8) -> Value {
    let digits = sval(&vm.pop());
    match digits.parse::<num_bigint::BigInt>() {
        Ok(b) => with_host(|h| h.new_bigint(b)),
        Err(_) => abort(vm, host::type_error("invalid BigInt literal")),
    }
}

/// `TAG_TMPL`: invoke a tagged template. The compiler emits the operands as
/// `[tag, n, m, cooked×n, raw×n, values×m]` (see `compile_tagged_template`).
/// Builds the `strings` array (carrying its `.raw` array) and calls
/// `tag(strings, ...values)`.
/// Reject a non-callable where node's scheduling entry points demand one.
///
/// Every one of them validates SYNCHRONOUSLY — `try { queueMicrotask(1) }
/// catch` catches an `ERR_INVALID_ARG_TYPE` in node. Here the value was queued
/// unchecked and the failure surfaced from the event loop instead, as an
/// uncaught `1 is not a function` that killed the process past any `try` around
/// the call.
fn require_callback(cb: &Value) -> Result<(), String> {
    if with_host(|h| host::is_callable(h, cb)) {
        return Ok(());
    }
    Err(host::invalid_arg_type(
        "callback", "argument", "function", cb,
    ))
}

fn b_tag_tmpl(vm: &mut VM, argc: u8) -> Value {
    // The chunk holding this site, read before the operands are popped and
    // before any host borrow: together with the compiler's per-site ordinal it
    // names the Parse Node whose template object 13.2.8.4 caches.
    let chunk = vm.chunk.op_hash;
    let mut all = pop_n(vm, argc as usize);
    let int_of = |v: &Value| match v {
        Value::Int(n) => *n as usize,
        Value::Float(f) => *f as usize,
        _ => 0,
    };
    let this = all.remove(0);
    let tag = all.remove(0);
    let n = int_of(&all.remove(0));
    let mcount = int_of(&all.remove(0));
    let site = int_of(&all.remove(0)) as u64;
    let cooked: Vec<Value> = all.drain(0..n.min(all.len())).collect();
    let raw: Vec<Value> = all.drain(0..n.min(all.len())).collect();
    let values: Vec<Value> = all.drain(0..mcount.min(all.len())).collect();
    // GetTemplateObject caches by Parse Node, so a site evaluated twice hands
    // back the SAME object — the whole point of the caching, since a tag that
    // memoizes on the strings array (lit-html, graphql-tag) re-parses its
    // template on every call without it.
    let key = (chunk, site);
    let strings = match with_host(|h| h.template_object(key)) {
        Some(cached) => cached,
        None => {
            // strings = cooked array; strings.raw = raw array.
            let strings = with_host(|h| h.new_array(cooked));
            let raw_arr = with_host(|h| h.new_array(raw));
            // `raw` is an own property that is neither writable, enumerable, nor
            // configurable, so it stays out of `Object.keys(strings)` while
            // `getOwnPropertyNames` still reports it.
            with_host(|h| {
                h.set_fn_prop(&strings, "raw", raw_arr.clone());
                h.set_prop_attrs(
                    &strings,
                    "raw",
                    host::PropAttrs {
                        writable: false,
                        enumerable: false,
                        configurable: false,
                    },
                );
                // Steps 12-13 run SetIntegrityLevel(frozen) on the raw array and
                // then on the template object itself. Without them a tag could
                // write through its own strings array and corrupt every later
                // evaluation of the site — which is exactly what caching makes
                // reachable, so the freeze and the cache belong together.
                h.seal_object(&raw_arr, true);
                h.seal_object(&strings, true);
                h.set_template_object(key, strings.clone());
            });
            strings
        }
    };
    let mut call_args = vec![strings];
    call_args.extend(values);
    let this = match this {
        Value::Undef => None,
        v => Some(v),
    };
    let r = host::invoke(&tag, call_args, this);
    finish(vm, r)
}

/// `GET_ASYNC_ITER`: obtain an async iterator for `for await (… of …)`. If the
/// value has a `Symbol.asyncIterator`, use it; otherwise fall back to its sync
/// iterator (each yielded value is awaited). Returns the iterator object/handle.
fn b_get_async_iter(vm: &mut VM, _: u8) -> Value {
    let src = vm.pop();
    let r = host::get_async_iterator(&src).map_err(|e| {
        // `for await` names the source AND says ASYNC: `for await (const x of
        // o)` is `o is not async iterable`. Built here rather than through
        // `name_call_site`, whose suffix table has no entry that composes.
        match host::call_site_text(vm) {
            Some(t) if e.ends_with(" is not iterable") => {
                host::type_error(&format!("{t} is not async iterable"))
            }
            _ => e,
        }
    });
    finish(vm, r)
}

/// `MKREGEX`: pop `(pattern, flags)`, translate the JS pattern to a Rust `regex`,
/// and allocate a `RegExp`. A pattern using a JS feature Rust `regex` cannot
/// express (backreference/lookaround) throws a `SyntaxError` here.
fn b_mkregex(vm: &mut VM, _: u8) -> Value {
    let flags = sval(&vm.pop());
    let pattern = sval(&vm.pop());
    match crate::regexp::build_regexp(&pattern, &flags) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}

/// DAP per-statement marker (`node --dap` only; the compiler emits this before
/// each statement under `debug`). Pops the source line pushed by the preceding
/// `LoadInt` and fires the debugger line hook, which pauses at breakpoints/step
/// targets. Returns `undefined` (the compiler pops it). A no-op unless a debug
/// session is active.
fn b_dbg_line(vm: &mut VM, _: u8) -> Value {
    let line = match vm.pop() {
        Value::Int(n) => n as u32,
        _ => 0,
    };
    crate::dap::on_debug_line(line);
    Value::Undef
}

/// Install an object-literal getter/setter on an object (`kind` is `member::GET`
/// or `member::SET`). Keeps the object on the stack.
fn b_def_accessor(vm: &mut VM, _: u8) -> Value {
    let func = vm.pop();
    let kind = match vm.pop() {
        Value::Int(n) => n,
        _ => 0,
    };
    let name = sval(&vm.pop());
    let obj = vm.pop();
    with_host(|h| {
        if kind == host::member::SET {
            h.set_accessor(&obj, &name, None, Some(func));
        } else {
            h.set_accessor(&obj, &name, Some(func), None);
        }
    });
    obj
}

fn b_await(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    match host::await_value(v) {
        Ok(r) => r,
        Err(e) => abort(vm, e),
    }
}

// ── classes / super / generators / property keys (compiler-emitted ops) ──────

fn b_mkclass(vm: &mut VM, argc: u8) -> Value {
    // The fourth argument, when present, is the FuncDef carrying the class's
    // source span.
    let source_def = match argc {
        4 => match vm.pop() {
            Value::Int(n) => Some(n as usize),
            _ => None,
        },
        _ => None,
    };
    let ctor = vm.pop();
    let parent = vm.pop();
    let name = sval(&vm.pop());
    host::build_class(&name, parent, ctor, source_def)
}

fn b_def_member(vm: &mut VM, _: u8) -> Value {
    let func = vm.pop();
    let is_static = matches!(vm.pop(), Value::Bool(true));
    let kind = match vm.pop() {
        Value::Int(n) => n,
        _ => 0,
    };
    let name = sval(&vm.pop());
    let class_val = vm.pop();
    host::define_member(&class_val, &name, kind, is_static, func);
    class_val
}

fn b_def_field(vm: &mut VM, _: u8) -> Value {
    // `name_anon`: the initializer was an anonymous function definition, so
    // 15.7.10 NamedEvaluation names its result after the field. Syntactic —
    // decided by the compiler, not re-derived from the produced value.
    let name_anon = matches!(vm.pop(), Value::Bool(true));
    let thunk = vm.pop();
    let name = sval(&vm.pop());
    let class_val = vm.pop();
    host::define_field(&class_val, &name, thunk, name_anon);
    class_val
}

/// `super(...args)` in a derived constructor: run the parent constructor on the
/// current `this`, then this class's field initializers.
/// `SUPER_CALL_SPREAD` — `super(...xs)`, where the argument list is built at
/// run time. Shares everything below with the fixed-arity form; only where the
/// arguments come from differs.
fn b_super_call_spread(vm: &mut VM, _: u8) -> Value {
    let arr = vm.pop();
    let args = host::iter_all(&arr).unwrap_or_default();
    super_call_with(vm, args)
}

fn b_super_call(vm: &mut VM, argc: u8) -> Value {
    let args = pop_n(vm, argc as usize);
    super_call_with(vm, args)
}

fn super_call_with(vm: &mut VM, args: Vec<Value>) -> Value {
    let this = with_host(|h| h.current_this());
    let this = match this {
        Some(t) => t,
        None => return abort(vm, host::type_error("'super' keyword unexpected here")),
    };
    // The class whose constructor is running = the running method's home class.
    let (parent, fields) = with_host(|h| h.super_context());
    let (parent, fields) = match parent {
        Some(p) => (p, fields),
        None => return abort(vm, host::type_error("'super' keyword unexpected here")),
    };
    let nt = with_host(|h| h.current_new_target()).unwrap_or_else(|| this.clone());
    let this = match host::super_construct(&parent, args, &this, &nt) {
        Err(e) => return abort(vm, e),
        // The parent returned an object of its own: 15.7.15 makes THAT the
        // instance, so `this` is rebound to it for the rest of the constructor
        // and it is what `new` hands back.
        Ok(Some(replacement)) => {
            with_host(|h| h.set_current_this(replacement.clone()));
            replacement
        }
        Ok(None) => this,
    };
    if !with_host(|h| h.bind_super_this()) {
        return abort(
            vm,
            "ReferenceError: Super constructor may only be called once".to_string(),
        );
    }
    // Run this (derived) class's own instance-field initializers after super.
    for (name, thunk, name_anon) in fields {
        if let Err(e) = host::init_one_field(&this, &name, &thunk, name_anon) {
            return abort(vm, e);
        }
    }
    Value::Undef
}

/// `super.name` — a method from the parent's prototype, or a getter's result.
fn b_super_get(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    match with_host(|h| h.super_resolve(&name)) {
        host::SuperRef::Data(v) => v,
        host::SuperRef::Getter(getter) => {
            let this = with_host(|h| h.current_this());
            match host::invoke(&getter, Vec::new(), this) {
                Ok(v) => v,
                Err(e) => abort(vm, e),
            }
        }
    }
}

/// Close every loop iterator parked on `vm`'s stack at the op now executing,
/// innermost first. Called where a chunk is about to be halted abruptly, since
/// the code that would ordinarily close them is being jumped over.
///
/// A close runs user code (a generator's `finally`), which can itself throw; the
/// error is deliberately dropped, because it must not replace the completion
/// that caused the unwind.
fn close_parked_iters(vm: &mut VM) {
    let n = host::parked_iters(vm);
    if n == 0 {
        return;
    }
    // The completion that caused the unwind is already pending on the host.
    // Closing an iterator resumes ANOTHER generator, which settles its own
    // signal/error state, so the pending one is saved across the close and put
    // back — otherwise the outer `.return()` would be lost.
    let saved = with_host(|h| (h.signal.take(), h.error.take()));
    for _ in 0..n {
        let it = vm.pop();
        let _ = close_iterator(&it);
    }
    with_host(|h| {
        h.signal = saved.0;
        h.error = saved.1;
    });
}

fn b_yield(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    match host::gen_yield(v) {
        Ok(sent) => {
            // A `.return()`/`.throw()` injected on resume sets a pending Return
            // signal (or error); halt the chunk so the body unwinds through any
            // enclosing `try/finally`, exactly like a source `return`/`throw`.
            if with_host(|h| h.error.is_some() || h.signal.is_some()) {
                // Halting jumps past the loop exits, so the `for…of` / `yield*`
                // iterators parked on this chunk's stack would be abandoned
                // still-suspended. They sit directly beneath the yielded value
                // (innermost last), and the compiler recorded how many are
                // there for this exact op.
                close_parked_iters(vm);
                vm.ip = vm.chunk.ops.len();
            }
            sent
        }
        // An injected `.throw()` comes back as an error rather than a signal,
        // and abandons the parked iterators the same way. The thrown value is
        // already on the host as `exc`; `close_parked_iters` puts back whatever
        // it saves, so the close cannot swallow it.
        Err(e) => {
            close_parked_iters(vm);
            abort(vm, e)
        }
    }
}

/// `PROPKEY` — ToPropertyKey (7.1.19) for an object literal's COMPUTED key.
///
/// It called `JsHost::property_key` directly, which is the primitive-only half
/// of the conversion, so an object key never ran `ToPrimitive`:
/// `{ [{toString(){return "TS"}}]: 1 }` keyed on `"[object Object]"` while the
/// member form `a[o] = 1` — which does go through `host::to_property_key` —
/// keyed on `"TS"`. The two forms are the same abstract operation and now share
/// the same implementation.
fn b_propkey(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    match host::to_property_key(&v) {
        Ok(k) => with_host(|h| h.new_str(k)),
        Err(e) => abort(vm, e),
    }
}

fn b_new_target(_vm: &mut VM, _: u8) -> Value {
    with_host(|h| h.current_new_target().unwrap_or(Value::Undef))
}

/// `a / b` with JS/IEEE-754 semantics. fusevm's native `Op::Div` returns `Undef`
/// for a zero divisor (so a frontend whose `/` differs must lower to a builtin —
/// its own documented guidance), but JavaScript requires `x/0 === ±Infinity` and
/// `0/0 === NaN`, so `/` is lowered here instead.
///
/// Being a builtin rather than a native op means it does NOT reach the numeric
/// hook, so `/` was the one arithmetic operator that never ran `ToPrimitive`:
/// `({valueOf(){return 7}}) / 2` was `NaN` where every other operator gave
/// `3.5`, and `new Date(2) / 1` was `NaN` instead of `2`. It goes through the
/// hook now, so `/` coerces exactly as `*` and `-` do.
fn b_div(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let r = numeric_hook(NumOp::Div, &a, &b);
    finish(vm, r)
}

/// `a ** b`. Same reason `/` is a builtin: fusevm's native `Op::Pow` is IEEE-754
/// `pow`, which returns 1 for `(-1) ** Infinity` and for `1 ** NaN` where the
/// spec says NaN. Routing through the numeric hook also keeps BigInt `**` on the
/// one code path that already handles it.
fn b_pow(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let r = numeric_hook(NumOp::Pow, &a, &b);
    finish(vm, r)
}

/// `{ ...rest } = obj`: a new object of `obj`'s own keys minus the excluded set.
fn b_obj_rest(vm: &mut VM, _: u8) -> Value {
    let excluded = vm.pop();
    let obj = vm.pop();
    // The excluded keys are normalized exactly as a property READ normalizes
    // them, not merely stringified: a symbol key lives on the object under its
    // internal `@@sym:<id>` spelling, and `str_of` renders it `Symbol(k)`, which
    // matches no key at all — so `const { [sym]: v, ...rest } = o` left the
    // symbol-keyed property in `rest`.
    let excl: Vec<String> = with_host(|h| h.iter_vec(&excluded))
        .unwrap_or_default()
        .iter()
        .filter_map(|v| host::to_property_key(v).ok())
        .collect();
    // CopyDataProperties (ECMA-262 7.3.25) copies the own ENUMERABLE keys,
    // symbol-keyed ones included. `own_enum_key_names` is what `Object.keys`
    // uses, so an ACCESSOR is in the list — reading the property map directly
    // missed one entirely, and `const { ...r } = { get g() {…} }` produced an
    // object with no `g` and never ran the getter.
    // A PROXY answers from its traps — `ownKeys`, then a
    // `getOwnPropertyDescriptor` per key to test enumerability — which
    // `own_enum_key_names` cannot see. Rest over one produced an empty object
    // and ran no traps at all.
    if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
        let keys = match crate::proxy::own_keys(&obj) {
            Ok(k) => k.unwrap_or_default(),
            Err(e) => return abort(vm, e),
        };
        let mut pairs: Vec<(String, Value)> = Vec::new();
        for k in keys {
            if excl.contains(&k) {
                continue;
            }
            // The enumerability test and the READ interleave per key, as node's
            // trap log shows — testing every key first and then reading them
            // all produced the right object through the wrong trap sequence.
            match crate::proxy::own_enumerable(&obj, &k) {
                Ok(false) => continue,
                Ok(true) => {}
                Err(e) => return abort(vm, e),
            }
            match get_property(&obj, &k) {
                Ok(v) => pairs.push((k, v)),
                Err(e) => return abort(vm, e),
            }
        }
        return with_host(|h| h.new_object(pairs.into_iter().collect()));
    }
    let keys: Vec<String> = with_host(|h| {
        // `own_enum_key_names` is the STRING half — the same list `Object.keys`
        // gives, so an accessor is in it. The symbol-keyed half lives in the
        // property map under the internal `@@sym:` spelling and has to be
        // collected separately, since `Object.keys` deliberately omits it.
        let mut ks = h.own_enum_key_names(&obj);
        if let Some(JsObj::Object(m)) = h.get(&obj) {
            for k in m.keys() {
                if host::is_symbol_key(k) && h.prop_attrs(&obj, k).enumerable {
                    ks.push(k.clone());
                }
            }
        }
        ks
    })
    .into_iter()
    .filter(|k| {
        // An internal slot (`@@native`, `@@bytes`, …) or a private class field
        // is not a property; a SYMBOL key shares the `@@` prefix but is one, so
        // the two cases cannot be told apart by the prefix alone.
        !excl.contains(k)
            && (host::is_symbol_key(k) || !(k.starts_with("@@") || k.starts_with('#')))
    })
    .collect();
    // Each value is read through `[[Get]]`, OUTSIDE the host borrow: a getter is
    // user code and re-entering the VM under the borrow aborts the process.
    let mut pairs: Vec<(String, Value)> = Vec::with_capacity(keys.len());
    for k in keys {
        match get_property(&obj, &k) {
            Ok(v) => pairs.push((k, v)),
            Err(e) => return abort(vm, e),
        }
    }
    with_host(|h| {
        let props: IndexMap<String, Value> = pairs.into_iter().collect();
        h.new_object(props)
    })
}

// ── helpers ──────────────────────────────────────────────────────────────────

fn pop_n(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
}

/// Read a compiler-internal name string (native `Value::Str` or heap `str`).
fn sval(v: &Value) -> String {
    if let Value::Str(s) = v {
        return (**s).clone();
    }
    with_host(|h| h.as_str(v)).unwrap_or_default()
}

/// The same string, without `sval`'s deep copy. Every identifier the compiler
/// emits is a `Value::Str` constant, so a variable read or write that went
/// through `sval` heap-allocated and memcpy'd the NAME once per access — on the
/// hot path of every loop. `Value::Str` is an `Arc<String>`, so cloning the
/// handle is a refcount bump instead.
fn sname(v: &Value) -> std::sync::Arc<String> {
    match v {
        Value::Str(s) => s.clone(),
        _ => std::sync::Arc::new(sval(v)),
    }
}

fn abort(vm: &mut VM, e: String) -> Value {
    with_host(|h| h.error = Some(e));
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// Halt the chunk if a call left an error or non-local signal pending.
fn finish(vm: &mut VM, r: Result<Value, String>) -> Value {
    match r {
        Ok(v) => {
            if with_host(|h| h.error.is_some() || h.signal.is_some()) {
                vm.ip = vm.chunk.ops.len();
            }
            v
        }
        Err(e) => abort(vm, e),
    }
}

// ── name handlers ─────────────────────────────────────────────────────────────

/// The value a bare global identifier resolves to, or `None` if unbound.
///
/// Shared by `b_getlocal` (the `x` form) and the `globalThis.x` property read,
/// which must agree: a name reachable one way and not the other is exactly the
/// discrepancy that left `globalThis.process` undefined while `process` worked.
pub(crate) fn global_binding(name: &str) -> Option<Value> {
    global_binding_from(name, false)
}

/// [`global_binding`] restricted to what the GLOBAL OBJECT really holds.
///
/// A `globalThis.x` read falls back to the same lazy binding a bare `x` gets,
/// which is what makes `globalThis.Math` and `globalThis.process` work — but
/// the bare-identifier lookup walks the SCOPE CHAIN, so while any function was
/// running its locals were readable off `globalThis`: `function f() { let zzq =
/// 2; return typeof globalThis.zzq }` answered for a name the global object has
/// never heard of. Only the globals map and the lazy builtins below may answer
/// here.
pub(crate) fn global_object_binding(name: &str) -> Option<Value> {
    global_binding_from(name, true)
}

fn global_binding_from(name: &str, object_only: bool) -> Option<Value> {
    let bound = with_host(|h| {
        if object_only {
            h.read_global(name)
        } else {
            h.read_name(name)
        }
    });
    if let Some(v) = bound {
        return Some(v);
    }
    // Globals bound lazily: numeric sentinels + builtin namespaces.
    match name {
        "undefined" => return Some(Value::Undef),
        "NaN" => return Some(Value::Float(f64::NAN)),
        "Infinity" => return Some(Value::Float(f64::INFINITY)),
        // One object, not a fresh one per read: `globalThis === globalThis` is
        // `true` in JS, and `globalThis.x = 1` is readable back as
        // `globalThis.x`. Both were false while each read minted a new object.
        // `global` is Node's alias for the same object.
        "globalThis" | "global" => return Some(with_host(|h| h.global_object())),
        // The WHATWG `crypto` global IS `require('crypto').webcrypto`, not the
        // node-flavoured module: `globalThis.crypto.randomUUID` exists while
        // `globalThis.crypto.createHash` does not.
        "crypto" => return Some(with_host(|h| h.alloc(JsObj::Builtin("webcrypto".into())))),
        _ => {}
    }
    if is_namespace(name) || is_known_builtin(name) {
        return Some(with_host(|h| h.alloc(JsObj::Builtin(name.to_string()))));
    }
    None
}

fn b_getlocal(vm: &mut VM, _: u8) -> Value {
    let name = sname(&vm.pop());
    // A module-top-level dead zone is tracked by NAME rather than by a parked
    // marker, so that the marker is never reachable as `globalThis.<name>`. It
    // only applies when nothing on the scope chain SHADOWS the name — a class's
    // own inner binding for its name does exactly that while its static
    // initializers run.
    if with_host(|h| h.is_tdz_global(&name) && h.read_name(&name).is_none()) {
        return abort(vm, host::tdz_error(&name));
    }
    match global_binding(&name) {
        // The binding EXISTS but has not reached its declaration yet.
        Some(v) if with_host(|h| h.is_tdz(&v)) => abort(vm, host::tdz_error(&name)),
        Some(v) => v,
        None => abort(vm, host::ref_error(&name)),
    }
}

/// `HOIST_TDZ` — declare one `let`/`const`/`class` name as uninitialized at the
/// top of the scope that declares it.
fn b_hoist_tdz(vm: &mut VM, _: u8) -> Value {
    let name = sname(&vm.pop());
    with_host(|h| h.hoist_tdz(&name));
    Value::Undef
}

/// The three global VALUE properties that are `{writable: false}` (19.1.1-19.1.3).
/// Assigning to one is a silent no-op in sloppy code and a `TypeError` in strict
/// code — and, either way, never rebinds the name.
const READONLY_GLOBALS: [&str; 3] = ["undefined", "NaN", "Infinity"];

fn readonly_global_error(name: &str) -> String {
    host::type_error(&format!(
        "Cannot assign to read only property '{name}' of object '#<Object>'"
    ))
}

fn b_setlocal(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sname(&vm.pop());
    // Sloppy assignment to a non-writable global is DISCARDED, not applied:
    // `undefined = 1` used to rebind the name and make every later `undefined`
    // read back as `1`.
    if READONLY_GLOBALS.contains(&name.as_str()) && !with_host(|h| h.has_name(&name)) {
        return val;
    }
    // Assigning to a binding still in its temporal dead zone throws too —
    // `{ x = 1; let x }` is a ReferenceError, not an initialization.
    if with_host(|h| match h.read_name(&name) {
        Some(v) => h.is_tdz(&v),
        None => h.is_tdz_global(&name),
    }) {
        return abort(vm, host::tdz_error(&name));
    }
    // An assignment to a `const` binding throws (8.5.2 SetMutableBinding on an
    // immutable binding). This used to succeed silently.
    if !with_host(|h| h.set_name(&name, val.clone())) {
        return abort(vm, host::type_error("Assignment to constant variable."));
    }
    val
}

/// Strict-mode `x = v` (6.2.5.6 `PutValue` with an unresolvable reference):
/// where sloppy code silently creates a global, strict code throws
/// `ReferenceError: x is not defined`.
///
/// A separate opcode rather than a runtime flag: strictness is a static property
/// of the code, so the compiler already knows which of the two an assignment is
/// and sloppy code — everything in a CommonJS module without the directive —
/// keeps the exact instruction it had.
fn b_setlocal_strict(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sname(&vm.pop());
    if !binding_exists(&name) {
        return abort(vm, host::ref_error(&name));
    }
    if READONLY_GLOBALS.contains(&name.as_str()) && !with_host(|h| h.has_name(&name)) {
        return abort(vm, readonly_global_error(&name));
    }
    if !with_host(|h| h.set_name(&name, val.clone())) {
        return abort(vm, host::type_error("Assignment to constant variable."));
    }
    val
}

/// Whether `name` resolves to anything — a scope binding, a global, or a lazily
/// materialised builtin namespace. `global_binding` answers the same question
/// but ALLOCATES the namespace object to do it, which an assignment then throws
/// away.
fn binding_exists(name: &str) -> bool {
    if with_host(|h| h.has_name(name)) {
        return true;
    }
    matches!(
        name,
        "undefined" | "NaN" | "Infinity" | "globalThis" | "global"
    ) || is_namespace(name)
        || is_known_builtin(name)
}

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

/// `const x = …`: like `DECLARE`, but the binding is immutable, so a later
/// assignment to the name throws instead of overwriting it.
fn b_declare_const(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sname(&vm.pop());
    with_host(|h| h.declare_const_name(&name, val.clone()));
    val
}

/// `var x = …` / a hoisted `function f(){}`: bind at function scope, skipping any
/// open block scopes, so the name outlives the block it was written in.
/// `var` hoisting: create the binding as `undefined` unless it already exists.
fn b_hoist_var(vm: &mut VM, _: u8) -> Value {
    let name = sname(&vm.pop());
    with_host(|h| h.hoist_var_name(&name));
    Value::Undef
}

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

fn b_push_scope(_: &mut VM, _: u8) -> Value {
    with_host(|h| h.push_scope());
    Value::Undef
}

fn b_pop_scope(_: &mut VM, _: u8) -> Value {
    with_host(|h| h.pop_scope());
    Value::Undef
}

fn b_copy_scope(_: &mut VM, _: u8) -> Value {
    with_host(|h| h.copy_scope());
    Value::Undef
}

fn b_delname(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    with_host(|h| h.del_name(&name));
    Value::Bool(true)
}

fn b_this(vm: &mut VM, _: u8) -> Value {
    if with_host(|h| h.this_state()) == host::ThisState::Pending {
        return abort(vm, host::this_before_super_error());
    }
    with_host(|h| h.current_this().unwrap_or(Value::Undef))
}

fn b_load_null(_vm: &mut VM, _: u8) -> Value {
    with_host(|h| h.null())
}

// ── attribute / item handlers ─────────────────────────────────────────────────

fn b_getattr(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    let recv = vm.pop();
    match get_property(&recv, &name) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}

/// Read `recv.name` (also the computed-key path for string keys). Walks own
/// properties, accessors, and the prototype chain (class methods / getters).
/// Read one small piece out of `recv`'s heap cell under a short borrow.
///
/// The closure must not call back into the host (`with_host` is a `RefCell`
/// borrow and re-entering panics) — which is exactly why it hands back only the
/// value needed: the caller re-enters freely afterwards. This replaces the old
/// `h.get(recv).cloned()` habit, which deep-copied a whole `Vec`/`IndexMap`/
/// `String` just to look at it.
fn peek<R>(recv: &Value, f: impl FnOnce(&JsObj) -> Option<R>) -> Option<R> {
    with_host(|h| h.get(recv).and_then(f))
}

/// The nearest `[[Prototype]]` link of `recv` that is a Proxy, when the chain
/// reaches it without a closer link already owning `name`.
///
/// A proxy prototype answers only from the position it occupies in the chain: a
/// nearer prototype that owns the key (as a data property or an accessor) still
/// wins, exactly as `OrdinaryGet` walks one link at a time.
pub(crate) fn proxy_proto_link(recv: &Value, name: &str) -> Option<Value> {
    with_host(|h| {
        let mut cur = h.proto_of(recv);
        for _ in 0..100 {
            let p = cur?;
            match h.get(&p) {
                Some(JsObj::Proxy { .. }) => return Some(p),
                Some(JsObj::Object(props)) if props.contains_key(name) => return None,
                _ => {}
            }
            if h.own_accessor(&p, name).is_some() {
                return None;
            }
            cur = h.proto_of(&p);
        }
        None
    })
}

/// The CommonJS wrapper's parameters. They are function locals in Node, not
/// global-object properties, so `globalThis.require` is `undefined` and
/// `Object.getOwnPropertyDescriptor(globalThis, 'module')` reports no property —
/// even though the bare `require` and `module` both work.
const CJS_WRAPPER_LOCALS: &[&str] = &[
    "require",
    "module",
    "exports",
    "__filename",
    "__dirname",
    "__cjs_require",
    "__cjs_resolve",
];

/// The globals node exposes as ENUMERABLE own properties of the global object —
/// the timer family and the WHATWG additions, measured on v26.8.1. Everything
/// else (`Math`, `parseInt`, the constructors) is non-enumerable.
const ENUMERABLE_GLOBALS: &[&str] = &[
    "global",
    "clearImmediate",
    "setImmediate",
    "clearInterval",
    "clearTimeout",
    "setInterval",
    "setTimeout",
    "queueMicrotask",
    "structuredClone",
    "atob",
    "btoa",
    "performance",
    "fetch",
    "crypto",
    "navigator",
    "sessionStorage",
];

pub fn get_property(recv: &Value, name: &str) -> Result<Value, String> {
    // A `#`-prefixed key is a PRIVATE name. `[[PrivateGet]]` (7.3.31) throws
    // when the receiver carries no such private element — it does NOT read back
    // as `undefined`, which is what `C.prototype.method.call({})` used to do.
    if name.starts_with('#') && !with_host(|h| h.has_private(recv, name)) {
        return Err(private_brand_message(name, false));
    }
    get_property_recv(recv, name, recv)
}

/// The `TypeError` a failed private brand check raises. Node words it two ways:
/// a private METHOD or accessor names the class the receiver should have been an
/// instance of, while a private FIELD names the member.
pub fn private_brand_message(name: &str, writing: bool) -> String {
    if with_host(|h| h.is_private_method(name)) {
        if let Some(class) = with_host(|h| h.current_home_class_name()) {
            return host::type_error(&format!("Receiver must be an instance of class {class}"));
        }
    }
    let verb = if writing { "write" } else { "read" };
    let prep = if writing { "to" } else { "from" };
    host::type_error(&format!(
        "Cannot {verb} private member {name} {prep} an object whose class did not declare it"
    ))
}

/// `[[Get]](name, receiver)` — 10.1.8. `receiver` is the object the read STARTED
/// from and is what a getter sees as `this`; it differs from `recv` only when the
/// read was forwarded down a prototype chain, which is why `Reflect.get(t, k, r)`
/// and a Proxy `get` trap's third argument both need it. Every ordinary read
/// passes `recv` itself.
/// Re-format an error's `.stack` header on its first read, the way V8 does.
///
/// The constructor could only stamp the name it was called with, so a subclass
/// that sets `this.name` after `super()` — or any `e.name = …` / `e.message = …`
/// before the first read — left a stale header. Node re-reads both properties at
/// format time, including one inherited from the prototype (`E.prototype.name`).
///
/// It is formatted ONCE: node caches the string, so renaming AFTER a read does
/// not change what later reads return. `@@stackRaw` is the not-yet-formatted
/// marker and is dropped here; an explicit `e.stack = …` drops it too, so an
/// assignment is never clobbered by a later read.
/// The key of node's DEFAULT `Error.prepareStackTrace`. Recognised by name so
/// the ordinary stack path can skip the hook round-trip when nothing custom is
/// installed.
pub const DEFAULT_PREPARE: &str = "ErrorPrepareStackTrace";

pub fn materialize_stack(recv: &Value) {
    let Some(frames) = with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get("@@stackRaw").cloned(),
        _ => None,
    }) else {
        return;
    };
    // A custom `Error.prepareStackTrace` replaces the string entirely (V8's
    // stack-introspection hook, which every source-map library installs). It was
    // honoured only by `Error.captureStackTrace`, so an ordinary `err.stack`
    // read bypassed it and handed back the default text.
    let prep = with_host(|h| h.builtin_static("Error", "prepareStackTrace"));
    if let Some(f) = prep.filter(|f| {
        // The default hook produces exactly what the fast path below produces,
        // so it is skipped rather than called.
        !matches!(
            with_host(|h| h.get(f).cloned()),
            Some(JsObj::Builtin(ref n)) if n == DEFAULT_PREPARE
        ) && matches!(
            with_host(|h| h.get(f).cloned()),
            Some(JsObj::Func(_)) | Some(JsObj::Builtin(_)) | Some(JsObj::BoundFunc { .. })
        )
    }) {
        // Clear the raw marker FIRST: the hook may read `.stack` itself, and a
        // second materialization would re-enter this path forever.
        with_host(|h| {
            if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                p.shift_remove("@@stackRaw");
            }
        });
        let limit = with_host(|h| h.stack_trace_limit());
        if let Ok(sites) = crate::module::callsite_stack(limit) {
            if let Ok(out) = host::invoke(&f, vec![recv.clone(), sites], None) {
                with_host(|h| {
                    if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                        p.insert("stack".into(), out);
                    }
                });
                return;
            }
        }
    }
    with_host(|h| {
        let frames = h.str_of(&frames);
        let name = host::lookup_chain(h, recv, "name")
            .map(|v| h.str_of(&v))
            .unwrap_or_else(|| "Error".to_string());
        let message = host::lookup_chain(h, recv, "message")
            .map(|v| h.str_of(&v))
            .unwrap_or_default();
        let header = if message.is_empty() {
            name
        } else {
            format!("{name}: {message}")
        };
        let sv = h.new_str(format!("{header}{frames}"));
        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
            p.insert("stack".into(), sv);
            p.shift_remove("@@stackRaw");
        }
    });
}

pub fn get_property_recv(recv: &Value, name: &str, receiver: &Value) -> Result<Value, String> {
    // `[[Get]]` on a Proxy: the handler's `get` trap, or a forward to the
    // target. Checked before anything else so no ordinary-object shortcut can
    // read past the handler.
    if let Some(v) = crate::proxy::get(recv, name, receiver)? {
        return Ok(v);
    }
    if with_host(|h| h.is_nullish(recv)) {
        return Err(host::type_error(&format!(
            "Cannot read properties of {} (reading '{name}')",
            with_host(|h| h.str_of(recv))
        )));
    }
    if name == "stack" {
        materialize_stack(recv);
    }
    // A `DOMException`'s `name`/`message`/`code` are prototype accessors over
    // internal slots, so they resolve here rather than out of a property map.
    if let Some(v) = dom_exception_slot(recv, name) {
        return Ok(v);
    }
    // A read off `globalThis` for a name the object does not own falls back to
    // the same lazy global binding the bare identifier gets. Without it the
    // global object was an empty bag: `globalThis.process`, `.console`, `.Math`
    // and `.JSON` were all `undefined`, so `process === globalThis.process` was
    // `false` and any `globalThis.X` feature probe reported the feature missing.
    if with_host(|h| h.is_global_object(recv)) {
        let own = with_host(|h| match h.get(recv) {
            Some(JsObj::Object(p)) => p.contains_key(name),
            _ => false,
        });
        // The CommonJS wrapper's parameters are function locals in Node, not
        // global-object properties: `typeof globalThis.require` is `undefined`
        // there even though the bare `require` works.
        if !own && !CJS_WRAPPER_LOCALS.contains(&name) {
            if let Some(v) = global_object_binding(name) {
                return Ok(v);
            }
        }
    }
    // Accessor (own or inherited getter) takes precedence over the chain walk.
    // The getter runs with the RECEIVER as `this`, not the object that owns it.
    if let Some((getter, _)) = with_host(|h| host::lookup_accessor(h, recv, name)) {
        return match getter {
            Some(g) => host::invoke(&g, Vec::new(), Some(receiver.clone())),
            None => Ok(Value::Undef), // set-only property reads as undefined
        };
    }
    // `Symbol.toStringTag` read as an ordinary property. The builtins that carry
    // one expose it to a plain read, not just to `Object.prototype.toString` —
    // `new Uint8Array(1)[Symbol.toStringTag]` is `'Uint8Array'`, and a `Buffer`
    // inherits `'Uint8Array'` from the typed-array prototype it now really has.
    // Anything the receiver's own chain provides wins (a class may define its
    // own getter), so this is only the fallback.
    if name == "@@toStringTag" && with_host(|h| host::lookup_chain(h, recv, name)).is_none() {
        if let Some(tag) = with_host(|h| well_known_tag(h, recv)) {
            return Ok(with_host(|h| h.new_str(tag)));
        }
    }
    // `constructor`: a user class/function sets it on the prototype chain, and
    // that wins; otherwise every builtin instance reports its native
    // constructor (so `[].constructor`, `new Map().constructor`,
    // `Promise.resolve(1).constructor`, `(5).constructor` match Node).
    if name == "constructor" {
        if let Some(v) = with_host(|h| {
            match h.get(recv) {
                Some(JsObj::Object(p)) => p.get("constructor").cloned(),
                _ => None,
            }
            .or_else(|| host::lookup_chain(h, recv, "constructor"))
        }) {
            return Ok(v);
        }
        // An intrinsic prototype the receiver's CHAIN reaches owns a
        // `constructor` too, and it wins over the receiver's own kind:
        // `Object.create(Map.prototype).constructor` is `Map`, not `Object`.
        // Deciding from the kind alone also mis-named the receiver in every
        // message that renders one — the brand-check errors say `#<Map>`.
        if let Some(c) = chain_intrinsic_ctors(recv)
            .into_iter()
            .find(|c| is_builtin_ctor(c))
        {
            return Ok(with_host(|h| h.alloc(JsObj::Builtin(c.to_string()))));
        }
        if let Some(cn) = with_host(|h| default_ctor_name(h, recv)) {
            return Ok(with_host(|h| h.alloc(JsObj::Builtin(cn.to_string()))));
        }
    }
    // `__proto__` (Annex B B.2.2.1) is an accessor on `Object.prototype`, so it
    // answers for EVERY object that inherits from it, not only plain ones —
    // `[].__proto__` is `Array.prototype`. Only the plain-object arm handled it,
    // so an array, function or builtin instance read `undefined`. An object with
    // a null prototype inherits no such accessor and reads `undefined`, which is
    // why this is skipped there rather than answering `null`.
    if name == "__proto__"
        && !with_host(|h| h.has_null_proto(recv))
        && peek(recv, |o| match o {
            JsObj::Object(p) => Some(p.contains_key("__proto__")),
            _ => Some(false),
        }) != Some(true)
    {
        return Ok(prototype_of(recv));
    }
    // An ACCESSOR member read off the intrinsic prototype ITSELF is not a
    // method: it RUNS the getter with that prototype as `this`, and all but two
    // of `RegExp.prototype`'s then fail their brand check and throw. Every one
    // answered `undefined`, so both the value and the failure were invisible.
    // Both representations of a prototype reach here — the namespace handles
    // and the real objects (`Symbol.prototype`, `String.prototype`).
    if let Some(ctor) = intrinsic_proto_of(recv) {
        if is_proto_accessor(&ctor, name) {
            return proto_getter_call(&ctor, name, recv);
        }
    }
    let kind = with_host(|h| h.kind_of(recv));
    #[allow(unused_mut)]
    let mut out = match kind {
        Some(ObjKind::Object) => {
            let numeric = !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit());
            // A view over a DETACHED buffer reports zero extent. Its own
            // `length`/`byteLength`/`byteOffset` properties still hold the old
            // numbers — the buffer does not know its views, so it cannot rewrite
            // them — and reading them straight back made a detached view still
            // look eight bytes long.
            if matches!(name, "length" | "byteLength" | "byteOffset")
                && crate::stdlib::typedarray::view_detached(recv)
            {
                match crate::stdlib::native_tag(recv).as_deref() {
                    Some("TypedArray") => return Ok(Value::Float(0.0)),
                    // A DataView THROWS where a typed array answers zero — its
                    // extent accessors are brand-checked and node reports the
                    // getter by name.
                    Some("DataView") => {
                        return Err(crate::stdlib::typedarray::detached_error(
                            "get DataView.prototype",
                            name,
                            false,
                        ))
                    }
                    _ => {}
                }
            }
            // Typed-array element read (`ta[i]`): elements live in a hidden
            // `@@elems`, not as own numeric props, so intercept integer keys.
            if numeric && crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray") {
                if let Some(v) = crate::stdlib::typedarray::elem_get(recv, name) {
                    return Ok(v);
                }
            }
            // `buf[i]`: a Buffer's bytes live in a hidden `@@bytes` array, not as
            // own numeric props, so integer keys read through to it.
            if numeric
                && peek(recv, |o| match o {
                    JsObj::Object(p) => Some(p.contains_key("@@bytes")),
                    _ => None,
                })
                .unwrap_or(false)
            {
                return Ok(crate::stdlib::buffer::byte_get(recv, name));
            }
            if let Some(v) = peek(recv, |o| match o {
                JsObj::Object(p) => p.get(name).cloned(),
                _ => None,
            }) {
                v
            } else if let Some(link) = proxy_proto_link(recv, name) {
                // A Proxy sitting in the prototype chain. `OrdinaryGet` (10.1.8.1
                // step 4) forwards to the parent's `[[Get]]` with the ORIGINAL
                // receiver, so the trap sees the child as `receiver` and `this`
                // inside a trap-served getter resolves to the child, not the
                // proxy. `lookup_chain` cannot do this: it reads property maps,
                // and a proxy has none.
                return Ok(crate::proxy::get(&link, name, recv)?.expect("link is a proxy"));
            } else if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
                // A method / data property inherited from the prototype chain.
                v
            } else if crate::stdlib::native_tag(recv)
                .map(|tag| crate::stdlib::instance_has_method(&tag, name))
                .unwrap_or(false)
            {
                // A native instance method read as a property (`server.listen`) →
                // a bound method, dispatched via `instance_call` when invoked.
                bound_method(recv, name)
            } else if is_object_method(name) && !with_host(|h| h.has_null_proto(recv)) {
                // `Object.create(null)` inherits nothing, so `toString`/`valueOf`
                // read as `undefined` there — which is also what makes
                // `Object.create(null) + 1` the spec `TypeError` instead of a
                // silent `"[object Object]1"`.
                bound_method(recv, name)
            } else {
                Value::Undef
            }
        }
        Some(ObjKind::Class) | Some(ObjKind::Func) | Some(ObjKind::BoundFunc) => {
            function_property(recv, name)
        }
        // A method READ off an instance (`[].slice`, `new Map().get`) is a bound
        // thunk here. It is a function value, so it answers the function
        // properties: `[].slice.name` was `undefined` where node reports
        // `slice`, and `String([].slice)` fell through to
        // `Object.prototype.toString`.
        Some(ObjKind::BoundMethod) => bound_method_property(recv, name),
        Some(ObjKind::Symbol) => match name {
            "description" => {
                match peek(recv, |o| match o {
                    JsObj::Symbol { desc, .. } => desc.clone(),
                    _ => None,
                }) {
                    Some(d) => with_host(|h| h.new_str(d)),
                    None => Value::Undef,
                }
            }
            "toString" => bound_method(recv, name),
            // Anything else a symbol answers, it inherits from
            // `Symbol.prototype`. The arm used to stop at `undefined`, so
            // `Symbol('x')[Symbol.toPrimitive]` and `Symbol('x').valueOf` read
            // as absent even though the prototype defines both — a symbol is an
            // ordinary object for the purpose of a property LOOKUP, only its
            // methods are branded.
            _ => with_host(|h| {
                h.ensure_wrapper_protos();
                h.native_proto("Symbol")
            })
            .and_then(|p| with_host(|h| host::lookup_chain(h, &p, name)))
            .unwrap_or(Value::Undef),
        },
        Some(ObjKind::BigInt) => {
            if matches!(
                name,
                "toString" | "valueOf" | "toLocaleString" | "constructor"
            ) {
                bound_method(recv, name)
            } else {
                Value::Undef
            }
        }
        Some(ObjKind::RegExp) => {
            // A RegExp holds no collection, so cloning the compiled pattern here
            // does not scale with any input size; `regexp_property` re-enters the
            // host to allocate `source`/`flags`, so it cannot run under a borrow.
            let r = peek(recv, |o| match o {
                JsObj::RegExp(r) => Some(r.clone()),
                _ => None,
            });
            match r {
                Some(r) => crate::regexp::regexp_property(&r, name).unwrap_or_else(|| {
                    // An OWN property beats the prototype method of the same
                    // name, which is ordinary resolution order. It mattered once
                    // the symbol-keyed methods existed: `re[Symbol.match] =
                    // false` disowns the regexp label (7.2.8), and the method
                    // was shadowing the assignment so the value never took.
                    if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
                        return v;
                    }
                    if crate::regexp::is_regexp_method(name) {
                        bound_method(recv, name)
                    } else {
                        Value::Undef
                    }
                }),
                None => Value::Undef,
            }
        }
        // A WeakMap/WeakSet has NO `size` (its contents are not observable), so
        // the read must be `undefined` rather than a live count.
        Some(ObjKind::Map) => {
            let (len, weak) = peek(recv, |o| match o {
                JsObj::Map { entries, weak } => Some((entries.len(), *weak)),
                _ => None,
            })
            .unwrap_or((0, false));
            match name {
                "size" if !weak => Value::Float(len as f64),
                "@@iterator" => bound_method(recv, name),
                _ if is_map_method(name) => bound_method(recv, name),
                _ => with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef),
            }
        }
        Some(ObjKind::Set) => {
            let (len, weak) = peek(recv, |o| match o {
                JsObj::Set { entries, weak } => Some((entries.len(), *weak)),
                _ => None,
            })
            .unwrap_or((0, false));
            match name {
                "size" if !weak => Value::Float(len as f64),
                "@@iterator" => bound_method(recv, name),
                _ if is_set_method(name) => bound_method(recv, name),
                _ => with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef),
            }
        }
        Some(ObjKind::Generator) => {
            // A generator IS its own iterator, so it answers for the matching
            // symbol — `@@asyncIterator` for an async one, `@@iterator` for a
            // sync one. Neither was advertised, so `ag()[Symbol.asyncIterator]`
            // was `undefined` even though `for await` over it worked through a
            // different path.
            let want = if with_host(|h| h.is_async_gen_val(recv)) {
                "@@asyncIterator"
            } else {
                "@@iterator"
            };
            if name == want || is_generator_method(name) || crate::stdlib::iterator::is_helper(name)
            {
                bound_method(recv, name)
            } else {
                with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef)
            }
        }
        Some(ObjKind::Promise) => {
            if matches!(name, "then" | "catch" | "finally") {
                bound_method(recv, name)
            } else {
                with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef)
            }
        }
        Some(ObjKind::Iter) => {
            if matches!(name, "next" | "return" | "@@iterator")
                || crate::stdlib::iterator::is_helper(name)
            {
                bound_method(recv, name)
            } else {
                with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef)
            }
        }
        Some(ObjKind::Array) => {
            if name == "length" {
                let n = peek(recv, |o| match o {
                    JsObj::Array(items) => Some(items.len()),
                    _ => None,
                })
                .unwrap_or(0);
                Value::Float(n as f64)
            } else if let Ok(i) = name.parse::<usize>() {
                peek(recv, |o| match o {
                    JsObj::Array(items) => items.get(i).cloned(),
                    _ => None,
                })
                // An index PAST an `arguments` object's length is an ordinary
                // own property in the side table, since adding one must not
                // move `length`. The array read alone could not see it, so the
                // write was invisible to every later read.
                .or_else(|| with_host(|h| h.fn_prop(recv, name)))
                .unwrap_or(Value::Undef)
            } else if name == "@@iterator"
                || is_object_method(name)
                // An `arguments` object is array-BACKED here but is not an
                // Array: node's exposes no `Array.prototype` method, which is
                // exactly why the idiom is `Array.prototype.slice.call(args)`.
                // Exposing them made `arguments.map` a function.
                || (is_array_method(name) && !is_arguments(recv))
            {
                bound_method(recv, name)
            } else if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
                // Extra own props attached to an array (e.g. `RegExp.exec` result's
                // `.index`/`.input`/`.groups`).
                v
            } else {
                Value::Undef
            }
        }
        Some(ObjKind::Str) => {
            // `.length` and `s[i]` count UTF-16 code units, not code points.
            if name == "length" {
                let n = peek(recv, |o| match o {
                    JsObj::Str(s) => Some(crate::utf16::len(s)),
                    _ => None,
                })
                .unwrap_or(0);
                Value::Float(n as f64)
            } else if let Ok(i) = name.parse::<usize>() {
                match peek(recv, |o| match o {
                    JsObj::Str(s) => crate::utf16::Units::of(s).unit_str(i),
                    _ => None,
                }) {
                    Some(c) => with_host(|h| h.new_str(c)),
                    None => Value::Undef,
                }
            } else if name == "@@iterator" || is_string_method(name) {
                bound_method(recv, name)
            } else {
                Value::Undef
            }
        }
        Some(ObjKind::Builtin) => {
            let ns = peek(recv, |o| match o {
                JsObj::Builtin(ns) => Some(ns.clone()),
                _ => None,
            })
            .unwrap_or_default();
            let v = namespace_property(&ns, name);
            // `Function.prototype`'s methods READ off a builtin function. The
            // CALL forms (`Math.max.call(null, 1, 2)`) already dispatched, but
            // the read answered `undefined` — so `typeof Math.max.bind` was
            // `"undefined"`, and `String(Math.max)` found no `toString` to
            // invoke and fell back to `Object.prototype.toString`'s
            // `[object Function]` where node reports the native-code form.
            if matches!(v, Value::Undef)
                && is_function_method(name)
                && host::builtin_is_callable(&ns)
            {
                return Ok(bound_method(recv, name));
            }
            v
        }
        _ => {
            // Primitive numbers/booleans: method access -> bound method.
            if matches!(recv, Value::Float(_) | Value::Int(_)) && is_number_method(name) {
                bound_method(recv, name)
            } else {
                Value::Undef
            }
        }
    };
    // Every object INHERITS the `Object.prototype` methods, and each kind's
    // read arm above knows only its OWN. So `typeof new Map().toString`,
    // `typeof f.hasOwnProperty` and `typeof /a/.propertyIsEnumerable` all
    // answered `undefined` — for Map the CALL already worked, which is the
    // read and the dispatch disagreeing about the same method.
    //
    // Which prototype owns the name is decided by the same helper the `in`
    // operator uses, so the two cannot drift, and the result is the SHARED
    // intrinsic rather than a per-read thunk.
    // `arguments.callee` (and `.caller`) is a POISON PILL in strict code — the
    // accessor throws rather than answering, which is how a strict function
    // keeps its caller unreachable. It read back as `undefined` here, which a
    // feature probe reads as "not supported" rather than "forbidden".
    // Measured: on an ARGUMENTS object only `callee` is poisoned (`caller` is
    // simply absent and reads `undefined`); on a strict FUNCTION both `caller`
    // and `arguments` are.
    if name == "callee" && is_arguments(recv) && with_host(|h| h.current_strict()) {
        return Err(host::type_error(POISON_PILL));
    }
    if matches!(name, "caller" | "arguments")
        && matches!(
            with_host(|h| h.kind_of(recv)),
            Some(ObjKind::Func) | Some(ObjKind::Class)
        )
    {
        return poison_pill_read(recv);
    }
    // `arguments.callee` in SLOPPY code is the running function — the
    // pre-`class` self-reference idiom. It read back `undefined`.
    if name == "callee" && is_arguments(recv) {
        if let Some(f) = with_host(|h| h.fn_prop(recv, "@@callee")) {
            return Ok(f);
        }
    }
    // A method SYNTHESIZED from the receiver's kind is only reachable while the
    // receiver's intrinsic prototype is still on its chain. `Object
    // .setPrototypeOf(a, {})` must make `a.join` `undefined`; the kind arm
    // above answers from the kind alone and cannot know the link changed. Only
    // a synthesized value is dropped — the two shapes a method read produces —
    // and only when the receiver does not own the name itself.
    if matches!(
        with_host(|h| h.get(&out).cloned()),
        Some(JsObj::BoundMethod { .. })
    ) || matches!(
        with_host(|h| h.get(&out).cloned()),
        Some(JsObj::Builtin(ns)) if ns.starts_with("@proto:")
    ) {
        // The kind arms synthesize their OWN kind's methods, so that is the
        // prototype whose reachability decides. Clearing the value here lets
        // the `inherited_method_owner` fallback below re-supply the
        // `Object.prototype` form where one exists — which is why
        // `a.toString` stays a function after the link is replaced while
        // `a.join` does not.
        if !own_intrinsic_reachable(recv) && !has_own_for_shadow(recv, name) {
            out = Value::Undef;
        }
    }
    // A key the receiver does not OWN is looked up on its prototype chain. The
    // exotic arms above answer from their own storage and stop, so an array
    // given a prototype inherited nothing through a read: with
    // `Object.setPrototypeOf(a, {1: 'q'})`, `a[1]` was `undefined` at an elided
    // index and at one past the end, while `1 in a` already answered true —
    // the two views of the same question disagreeing. An accessor was found
    // (`lookup_accessor` walks), so only DATA properties went missing.
    //
    // A plain object's arm already consults the chain, and an array with no
    // explicit prototype has no links to walk, so this changes neither.
    if !name.starts_with('#') && !name.starts_with("@@") && !has_own_for_shadow(recv, name) {
        if matches!(out, Value::Undef) {
            if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
                return Ok(v);
            }
        }
        // Then a monkey-patched intrinsic prototype member, which shadows the
        // synthesized one: after `Array.prototype.join = f`, `[1, 2].join` must
        // BE `f`. An explicitly-set prototype above wins over it, as the chain
        // order requires.
        if let Some(v) = inherited_builtin_static(recv, name) {
            return Ok(v);
        }
    }
    if matches!(out, Value::Undef) && !name.starts_with('#') {
        if let Some(owner) = inherited_method_owner(recv, name) {
            // An INHERITED accessor runs, it does not hand back a thunk, and
            // its brand check is about the receiver's internal slot rather than
            // its chain — `Object.create(Map.prototype).size` throws in node
            // even though `Map.prototype` is right there above it. This
            // answered `undefined`, which is the value a real Map would never
            // give and a plain object should never reach.
            if is_proto_accessor(owner, name) && !getter_in_flight(owner, name) {
                return proto_getter_call(owner, name, recv);
            }
            let key = format!("@proto:{owner}:{name}");
            if builtin_meta(&key).is_some() {
                return Ok(with_host(|h| h.alloc(JsObj::Builtin(key))));
            }
            // A DATA member of the prototype — `Array.prototype[Symbol
            // .unscopables]` is an object, not a method, so it is in neither
            // function table. Read it off the prototype itself rather than
            // answering `undefined`: an instance inherits it.
            let v = namespace_property(&format!("{owner}.prototype"), name);
            if !matches!(v, Value::Undef) {
                return Ok(v);
            }
        }
    }
    Ok(out)
}

/// The namespace name of the `require.cache` view. A `Builtin` rather than an
/// object literal because the module cache is the single source of truth: a
/// populated copy would answer reads correctly and silently ignore a `delete`,
/// which is the operation the property exists for.
pub const REQUIRE_CACHE: &str = "__cjs_cache";

/// The builtin constructor name for a value with no own/inherited `constructor`
/// property, so `x.constructor` (and thus `x.constructor.name`) matches Node for
/// arrays, plain objects, Map/Set, promises, iterators, functions, and boxed
/// primitives. `None` ⇒ leave `.constructor` as `undefined` (e.g. generators,
/// whose `.constructor.name` is `""` in Node — not worth modelling).
fn default_ctor_name(h: &host::JsHost, recv: &Value) -> Option<&'static str> {
    match h.get(recv) {
        Some(JsObj::Array(_)) => Some("Array"),
        Some(JsObj::Object(props)) => {
            // A native instance reports its own constructor, not Object — e.g.
            // `qs` does `buf.constructor.isBuffer(buf)`, so a Buffer's
            // `.constructor` must be `Buffer` (which carries `isBuffer`). Read
            // the `@@native` tag off the already-borrowed host (calling
            // `native_tag`, which re-enters `with_host`, would double-borrow).
            match props.get("@@native").map(|t| h.str_of(t)).as_deref() {
                Some("Buffer") => Some("Buffer"),
                Some("URL") => Some("URL"),
                Some("Date") => Some("Date"),
                Some("WeakRef") => Some("WeakRef"),
                Some("FinalizationRegistry") => Some("FinalizationRegistry"),
                Some("TextEncoder") => Some("TextEncoder"),
                Some("TextDecoder") => Some("TextDecoder"),
                Some("EventEmitter") => Some("EventEmitter"),
                Some("Timeout") => Some("Timeout"),
                Some("Immediate") => Some("Immediate"),
                _ => Some("Object"),
            }
        }
        Some(JsObj::Map { weak, .. }) => Some(if *weak { "WeakMap" } else { "Map" }),
        Some(JsObj::Set { weak, .. }) => Some(if *weak { "WeakSet" } else { "Set" }),
        Some(JsObj::Promise { .. }) => Some("Promise"),
        Some(JsObj::Str(_)) => Some("String"),
        Some(JsObj::Symbol { .. }) => Some("Symbol"),
        Some(JsObj::BigInt(_)) => Some("BigInt"),
        Some(JsObj::RegExp(_)) => Some("RegExp"),
        Some(JsObj::Iter { .. }) => Some("Iterator"),
        Some(JsObj::Func(f)) => {
            // A generator or async function is NOT an ordinary function: its
            // `[[Prototype]]` is `GeneratorFunction.prototype` (or the async
            // variants'), and so is its `constructor`. All three reported plain
            // `Function`, so `g.constructor.name` was `Function` where node
            // says `GeneratorFunction`.
            Some(match h.funcs.get(f.def_id) {
                Some(d) if d.is_generator && d.is_async => "AsyncGeneratorFunction",
                Some(d) if d.is_generator => "GeneratorFunction",
                Some(d) if d.is_async => "AsyncFunction",
                _ => "Function",
            })
        }
        Some(JsObj::Class(_)) | Some(JsObj::BoundFunc { .. }) => Some("Function"),
        _ => match recv {
            Value::Float(_) | Value::Int(_) => Some("Number"),
            Value::Bool(_) => Some("Boolean"),
            _ => None,
        },
    }
}

/// The builtin constructor *functions*, so `Ctor.name` is the constructor name.
/// Excludes the non-callable namespaces (`Math`, `JSON`, `console`, `Reflect`,
/// `process`), whose `.name` is `undefined` in Node.
///
/// Most are also globals, but not all: `Timeout`/`Immediate` are unexposed in
/// Node (`typeof Timeout === 'undefined'`) yet still name themselves through a
/// handle's `.constructor.name`, so they belong here and not in `GLOBALS`.
/// The builtins that expose a `Symbol.species` accessor. Each returns `this`,
/// so a subclass is its own species unless it overrides the getter.
fn has_species(name: &str) -> bool {
    matches!(
        name,
        "Array" | "Map" | "Set" | "WeakMap" | "WeakSet" | "Promise" | "RegExp" | "ArrayBuffer"
    ) || crate::stdlib::typedarray::is_ctor(name)
}

fn is_builtin_ctor(name: &str) -> bool {
    matches!(
        name,
        "Array"
            | "Object"
            | "Number"
            | "String"
            | "Boolean"
            | "Symbol"
            | "Function"
            | "Map"
            | "Set"
            | "WeakMap"
            | "WeakSet"
            | "Promise"
            | "BigInt"
            | "Iterator"
            | "RegExp"
            | "Date"
            | "ArrayBuffer"
            | "DataView"
            | "Uint8Array"
            | "Int8Array"
            | "Uint8ClampedArray"
            | "Int16Array"
            | "Uint16Array"
            | "Int32Array"
            | "Uint32Array"
            | "Float32Array"
            | "Float64Array"
            | "BigInt64Array"
            | "BigUint64Array"
            | "WeakRef"
            | "FinalizationRegistry"
            | "TextEncoder"
            | "TextDecoder"
            | "IncomingMessage"
            | "ServerResponse"
            | "EventEmitter"
            | "Buffer"
            | "URL"
            | "URLSearchParams"
            | "Timeout"
            | "Immediate"
    ) || host::ERROR_NAMES.contains(&name)
        // The stream base classes are constructors too, and `require('stream')`
        // IS `Stream`, so `require('stream').name` has to answer.
        || crate::stdlib::stream::is_class(name)
}

/// The intrinsic key of the method `<instance>.<method>` resolves to, so a bound
/// thunk can look its `name`/`length` up in the same table a
/// `<Ctor>.prototype.<method>` thunk uses. `None` when the receiver has no
/// builtin constructor to name (a native stdlib instance, whose methods are
/// node's own JS and have no specified arity).
fn bound_method_key(recv: &Value, method: &str) -> Option<String> {
    let ctor = with_host(|h| default_ctor_name(h, recv))?;
    Some(format!("@proto:{ctor}:{method}"))
}

/// `[[Get]]` on a bound method thunk. It is a function, so `name`, `length` and
/// the `Function.prototype` methods all answer; `length` only when the intrinsic
/// table knows the method, because inventing an arity is worse than the
/// `undefined` a caller can test for.
fn bound_method_property(recv: &Value, name: &str) -> Value {
    let method = peek(recv, |o| match o {
        JsObj::BoundMethod { name, .. } => Some(name.clone()),
        _ => None,
    })
    .unwrap_or_default();
    let key = peek(recv, |o| match o {
        JsObj::BoundMethod { recv, .. } => Some(recv.clone()),
        _ => None,
    })
    .and_then(|inner| bound_method_key(&inner, &method));
    let meta = key.as_deref().and_then(builtin_meta);
    match name {
        "name" => {
            let n = meta.map(|(n, _)| n.to_string()).unwrap_or(method);
            with_host(|h| h.new_str(n))
        }
        "length" => match meta {
            Some((_, len)) => Value::Float(len as f64),
            None => Value::Undef,
        },
        _ if is_function_method(name) => bound_method(recv, name),
        _ => with_host(|h| h.fn_prop(recv, name)).unwrap_or(Value::Undef),
    }
}

fn bound_method(recv: &Value, name: &str) -> Value {
    // An ECMAScript intrinsic is ONE function object shared by every instance:
    // `[1].push === Array.prototype.push` and `[1].push === [2].push` are both
    // true. Reading one off an instance used to mint a fresh thunk bound to that
    // instance, so every such comparison answered false — and a detached method
    // kept working on the receiver it was read off, where node throws because it
    // has no `this` at all.
    if let Some(key) = bound_method_key(recv, name) {
        if builtin_meta(&key).is_some() {
            return with_host(|h| h.alloc(JsObj::Builtin(key)));
        }
    }
    with_host(|h| {
        h.alloc(JsObj::BoundMethod {
            recv: recv.clone(),
            name: name.to_string(),
        })
    })
}

/// `Object.prototype` methods reachable on any object.
fn is_object_method(name: &str) -> bool {
    matches!(
        name,
        "hasOwnProperty"
            | "isPrototypeOf"
            | "propertyIsEnumerable"
            | "toString"
            | "toLocaleString"
            | "valueOf"
            | "constructor"
            | "__defineGetter__"
            | "__defineSetter__"
            | "__lookupGetter__"
            | "__lookupSetter__"
    )
}

/// The `Object.prototype` methods installed as thunks on the real
/// `Object.prototype` object, so `Object.prototype.toString.call(x)` and a class
/// prototype's inherited `hasOwnProperty` both resolve through the chain.
pub const OBJECT_PROTO_METHODS: &[&str] = &[
    "hasOwnProperty",
    "isPrototypeOf",
    "propertyIsEnumerable",
    "toString",
    "toLocaleString",
    "valueOf",
    "__defineGetter__",
    "__defineSetter__",
    "__lookupGetter__",
    "__lookupSetter__",
];

/// A typed array with elements cannot be frozen or sealed: its indices are
/// non-configurable by construction, so making them non-writable would violate
/// the invariant, and node refuses outright rather than half-applying it. An
/// EMPTY view and a `DataView` are both fine.
/// `TestIntegrityLevel` (7.3.16) — `Object.isFrozen` / `Object.isSealed`.
///
/// Over a PROXY it is a sequence of traps (`isExtensible`, `ownKeys`, then a
/// `getOwnPropertyDescriptor` per key), not a question for the host: the proxy
/// OBJECT was being inspected, so a frozen proxy answered false and the handler
/// never saw the query.
fn integrity_level(v: &Value, freeze: bool) -> Result<Value, String> {
    if with_host(|h| h.kind_of(v)) != Some(ObjKind::Proxy) {
        return Ok(Value::Bool(with_host(|h| h.is_sealed(v, freeze))));
    }
    // An EXTENSIBLE object is neither sealed nor frozen, whatever its keys say.
    if crate::proxy::is_extensible(v)?.unwrap_or(true) {
        return Ok(Value::Bool(false));
    }
    for key in crate::proxy::own_keys(v)?.unwrap_or_default() {
        let Some(d) = crate::proxy::get_own_descriptor(v, &key)? else {
            continue;
        };
        let flag = |name: &str| {
            with_host(|h| match h.get(&d) {
                Some(JsObj::Object(p)) => p.get(name).map(|x| h.truthy(x)).unwrap_or(false),
                _ => false,
            })
        };
        let is_data = with_host(
            |h| matches!(h.get(&d), Some(JsObj::Object(p)) if !p.contains_key("get") && !p.contains_key("set")),
        );
        if flag("configurable") || (freeze && is_data && flag("writable")) {
            return Ok(Value::Bool(false));
        }
    }
    Ok(Value::Bool(true))
}

/// `SetIntegrityLevel` (7.3.15) over a PROXY, which is a sequence of TRAPS —
/// `preventExtensions`, then `ownKeys`, then a `getOwnPropertyDescriptor` and a
/// `defineProperty` per key. It ran none of them: the host sealed the proxy
/// OBJECT, so the handler never saw the operation and the target was untouched.
///
/// Returns false for a non-proxy, which takes the ordinary path.
fn seal_proxy(v: &Value, freeze: bool) -> Result<bool, String> {
    if with_host(|h| h.kind_of(v)) != Some(ObjKind::Proxy) {
        return Ok(false);
    }
    if !crate::proxy::prevent_extensions(v)? {
        return Err(host::type_error("Object.freeze called on non-object"));
    }
    let keys = crate::proxy::own_keys(v)?.unwrap_or_default();
    for key in keys {
        // SEALING asks for no descriptor at all — it only strips
        // `configurable`, which is the same for a data property and an
        // accessor. FREEZING has to know which it is, because only a data
        // property has a `writable` to strip, and that is the one extra trap
        // call node makes.
        let accessor = if freeze {
            let Some(cur) = crate::proxy::get_own_descriptor(v, &key)? else {
                continue;
            };
            with_host(
                |h| matches!(h.get(&cur), Some(JsObj::Object(p)) if p.contains_key("get") || p.contains_key("set")),
            )
        } else {
            false
        };
        let desc = with_host(|h| {
            let mut m: IndexMap<String, Value> = IndexMap::new();
            m.insert("configurable".into(), Value::Bool(false));
            if freeze && !accessor {
                m.insert("writable".into(), Value::Bool(false));
            }
            h.new_object(m)
        });
        if !crate::proxy::define_property(v, &key, &desc)? {
            return Err(host::type_error(&format!(
                "'defineProperty' on proxy: trap returned falsish for property '{key}'"
            )));
        }
    }
    Ok(true)
}

fn reject_sealing_a_view(v: &Value, verb: &str) -> Result<(), String> {
    let has_elements = matches!(
        crate::stdlib::native_tag(v).as_deref(),
        Some("TypedArray") | Some("Buffer")
    ) && !crate::stdlib::typedarray::elem_values(v).is_empty();
    if has_elements {
        return Err(host::type_error(&format!(
            "Cannot {verb} array buffer views with elements"
        )));
    }
    Ok(())
}

pub fn is_object_builtin_method(name: &str) -> bool {
    matches!(
        name,
        "hasOwnProperty"
            | "isPrototypeOf"
            | "propertyIsEnumerable"
            | "toString"
            | "toLocaleString"
            | "valueOf"
            | "__defineGetter__"
            | "__defineSetter__"
            | "__lookupGetter__"
            | "__lookupSetter__"
    )
}

/// The `Symbol.toStringTag` STRING on `recv`'s chain, if any — steps 16-17 of
/// 20.1.3.6, the hook by which a class names its own brand.
///
/// A Proxy has no chain to probe: the step is an unconditional
/// `Get(O, @@toStringTag)`, so its `get` trap decides. Probing first (as an
/// ordinary receiver does, to keep the read off objects that carry no tag)
/// would always miss and brand every tagged proxy `[object Object]`.
///
/// The read runs OUTSIDE the host borrow so a getter-valued tag can be invoked.
fn to_string_tag(recv: &Value) -> Result<Option<String>, String> {
    let tagged = with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy)
        || with_host(|h| {
            host::lookup_chain(h, recv, "@@toStringTag").is_some()
                || host::lookup_accessor(h, recv, "@@toStringTag").is_some()
        });
    if !tagged {
        return Ok(None);
    }
    let t = get_property(recv, "@@toStringTag")?;
    Ok(with_host(|h| h.as_str(&t)))
}

/// Dispatch an `Object.prototype` builtin method on an object/instance.
pub fn object_builtin_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        // Annex B B.2.2.2-B.2.2.5. Legacy, but still present in node and still
        // reached by pre-`defineProperty` libraries; all four were missing, so
        // `o.__defineGetter__` threw "is not a function".
        "__defineGetter__" | "__defineSetter__" => {
            let getter = name == "__defineGetter__";
            let f = args.get(1).cloned().unwrap_or(Value::Undef);
            if !with_host(|h| host::is_callable(h, &f)) {
                return Err(host::type_error(&format!(
                    "Object.prototype.{name}: Expecting function"
                )));
            }
            let key = host::to_property_key(&arg0(&args))?;
            let desc = with_host(|h| {
                let mut m: IndexMap<String, Value> = IndexMap::new();
                m.insert(if getter { "get" } else { "set" }.into(), f);
                m.insert("enumerable".into(), Value::Bool(true));
                m.insert("configurable".into(), Value::Bool(true));
                h.new_object(m)
            });
            apply_descriptor(recv, &key, &desc)?;
            Ok(Value::Undef)
        }
        "__lookupGetter__" | "__lookupSetter__" => {
            let want_get = name == "__lookupGetter__";
            let key = host::to_property_key(&arg0(&args))?;
            // Walks the prototype chain, unlike `getOwnPropertyDescriptor`.
            let found = with_host(|h| host::lookup_accessor(h, recv, &key));
            Ok(match found {
                Some((g, st)) => {
                    let side = if want_get { g } else { st };
                    side.unwrap_or(Value::Undef)
                }
                None => Value::Undef,
            })
        }
        "hasOwnProperty" => {
            let k = host::to_property_key(&arg0(&args))?;
            // The global object OWNS its lazily-bound builtins and every global
            // a script created; neither lives in its property map.
            if with_host(|h| h.is_global_object(recv))
                && !CJS_WRAPPER_LOCALS.contains(&k.as_str())
                && global_object_binding(&k).is_some()
            {
                return Ok(Value::Bool(true));
            }
            // A builtin namespace/prototype receiver (`Map.prototype`) reports
            // ownership via `has_property` (its methods resolve as thunks).
            if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Builtin) {
                return Ok(Value::Bool(has_property(recv, &k)?));
            }
            // `HasOwnProperty` (7.3.12) is `[[GetOwnProperty]]`, so on a Proxy it
            // is the `getOwnPropertyDescriptor` trap — NOT the `has` trap and not
            // the target's property map.
            if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
                let d = crate::proxy::get_own_descriptor(recv, &k)?.unwrap_or(Value::Undef);
                return Ok(Value::Bool(!matches!(d, Value::Undef)));
            }
            // A Buffer's / typed array's own keys are its element indices: the
            // `length`/`byteLength` slots are internal bookkeeping, and V8
            // reports `hasOwnProperty('length')` as false for a typed array.
            // Shared with the `in` operator so the two cannot drift apart.
            if let Some(hit) = crate::stdlib::typedarray::has_index(recv, &k) {
                return Ok(Value::Bool(hit));
            }
            // A function's `length`/`name`/`prototype` and a RegExp's
            // `lastIndex` are SYNTHESIZED own properties: they read back but
            // own no map entry, so this answered false where node says true.
            if synthesized_own_descriptor(recv, &k).is_some() {
                return Ok(Value::Bool(true));
            }
            if uses_side_table(recv) {
                return Ok(Value::Bool(with_host(|h| h.fn_prop(recv, &k).is_some())));
            }
            let has = with_host(|h| match h.get(recv) {
                Some(JsObj::Object(p)) => p.contains_key(&k) || h.own_accessor(recv, &k).is_some(),
                Some(JsObj::Array(items)) => {
                    k == "length"
                        || k.parse::<usize>()
                            .map(|i| i < items.len() && !h.is_hole(recv, i))
                            .unwrap_or(false)
                }
                _ => false,
            });
            Ok(Value::Bool(has))
        }
        "isPrototypeOf" => {
            let target = arg0(&args);
            // The ARGUMENT is what gets walked, so a proxy there needs its
            // `getPrototypeOf` trap for the FIRST hop: `proto_of` reads a link a
            // proxy does not hold, which reported `false` for every proxy. From
            // the second hop on the chain is ordinary objects again, walked by
            // the recorded link exactly as before.
            let mut cur = match crate::proxy::get_prototype_of(&target)? {
                Some(p) => Some(p).filter(|p| !with_host(|h| h.is_null(p))),
                None => with_host(|h| h.proto_of(&target)),
            };
            while let Some(p) = cur {
                if with_host(|h| h.strict_eq(&p, recv)) {
                    return Ok(Value::Bool(true));
                }
                cur = with_host(|h| h.proto_of(&p));
            }
            Ok(Value::Bool(false))
        }
        "propertyIsEnumerable" => {
            let k = with_host(|h| h.str_of(&arg0(&args)));
            // Own *and* enumerable — a non-enumerable own slot reads false. On a
            // Proxy that question is `[[GetOwnProperty]]`, i.e. the descriptor
            // trap, since there is no property map to enumerate.
            if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
                let has = crate::proxy::own_enum_string_keys(recv)?.contains(&k);
                return Ok(Value::Bool(has));
            }
            let has = with_host(|h| h.own_enum_key_names(recv).contains(&k));
            Ok(Value::Bool(has))
        }
        "toString" => {
            // An instance with a custom `toString` up the chain is handled by
            // call_method before reaching here; this is the default — and the
            // default consults `Symbol.toStringTag` (20.1.3.6 steps 16-17).
            // Only the EXPLICIT `Object.prototype.toString.call(o)` did, so a
            // tagged object branded itself `[object T]` when asked one way and
            // `[object Object]` when converted the other (`String(o)`, `${o}`,
            // `o + ''`, `o.toString()`), which is the path ordinary code takes.
            if let Some(t) = to_string_tag(recv)? {
                return Ok(with_host(|h| h.new_str(format!("[object {t}]"))));
            }
            Ok(with_host(|h| {
                let s = h.str_of(recv);
                h.new_str(s)
            }))
        }
        // `Object.prototype.toLocaleString` (20.1.3.5) is defined as
        // `Invoke(this, "toString")` — no locale behavior of its own. It was
        // installed as a thunk on `Object.prototype` but had no dispatch arm, so
        // calling it threw `is not a function` on every plain object.
        "toLocaleString" => {
            let v = host::call_method(recv, "toString", Vec::new())?;
            Ok(v)
        }
        "valueOf" => Ok(recv.clone()),
        _ => Err(host::type_error(&format!("{name} is not a function"))),
    }
}

/// `Function.prototype` methods (`call`/`apply`/`bind`) plus `Symbol.prototype`/
/// generator handling done elsewhere. Returns `Ok(None)` if `name` is not one of
/// these (so the caller can try statics).
pub fn function_builtin_method(
    recv: &Value,
    name: &str,
    args: &[Value],
) -> Result<Option<Value>, String> {
    match name {
        "call" => {
            let this = args.first().cloned();
            let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
            Ok(Some(host::invoke(recv, rest, this)?))
        }
        "apply" => {
            let this = args.first().cloned();
            let arr = args.get(1).cloned().unwrap_or(Value::Undef);
            // `Function.prototype.apply` takes an ARRAY-LIKE, not an iterable
            // (10.2.4.3 → CreateListFromArrayLike): `f.apply(null, arguments)`
            // and `f.apply(null, {length: 2, 0: 'x', 1: 'y'})` are the shapes
            // this is written for, and both produced an empty list. A nullish
            // second argument means no arguments at all.
            let call_args = if matches!(arr, Value::Undef) || with_host(|h| h.is_null(&arr)) {
                Vec::new()
            } else {
                create_list_from_array_like(&arr)?
            };
            Ok(Some(host::invoke(recv, call_args, this)?))
        }
        "bind" => {
            let this = args.first().cloned().unwrap_or(Value::Undef);
            let pre = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
            Ok(Some(with_host(|h| {
                h.alloc(JsObj::BoundFunc {
                    target: recv.clone(),
                    this,
                    args: pre,
                })
            })))
        }
        "toString" => Ok(Some(with_host(|h| {
            let s = h.str_of(recv);
            h.new_str(s)
        }))),
        _ => Ok(None),
    }
}

fn is_function_method(name: &str) -> bool {
    matches!(name, "call" | "apply" | "bind" | "toString")
}
fn is_map_method(name: &str) -> bool {
    matches!(
        name,
        "get" | "set" | "has" | "delete" | "clear" | "forEach" | "keys" | "values" | "entries"
    )
}
fn is_set_method(name: &str) -> bool {
    matches!(
        name,
        "add"
            | "has"
            | "delete"
            | "clear"
            | "forEach"
            | "keys"
            | "values"
            | "entries"
            | "union"
            | "intersection"
            | "difference"
            | "symmetricDifference"
            | "isSubsetOf"
            | "isSupersetOf"
            | "isDisjointFrom"
    )
}
fn is_generator_method(name: &str) -> bool {
    matches!(name, "next" | "return" | "throw")
}

/// A property read on a function/class value: own fn-props (statics, name,
/// prototype, length) plus inherited statics and `call`/`apply`/`bind`.
fn function_property(recv: &Value, name: &str) -> Value {
    // A class static, inherited down the constructor chain.
    if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Class) {
        if let Some(v) = with_host(|h| h.class_static(recv, name)) {
            return v;
        }
        // A class's own `name` and `length` are its own, not the builtin
        // ancestor's: `class A extends Array {}` has `A.name === "A"` and
        // `A.length === 0`, but both were read off `Array`. Only a class that
        // WOULD fall through to an ancestor takes this path; a plain class keeps
        // the ordinary computation below.
        if matches!(name, "name" | "length")
            && with_host(|h| h.class_static(recv, name)).is_none()
            && with_host(|h| h.class_builtin_ancestor(recv))
                .is_some_and(|a| matches!(with_host(|h| h.kind_of(&a)), Some(ObjKind::Builtin)))
        {
            if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
                return v;
            }
            if name == "name" {
                let n = with_host(|h| h.callable_name(recv));
                return with_host(|h| h.new_str(n));
            }
            // The class's own constructor decides its arity; with no explicit
            // one the implicit `constructor(...args)` has length 0.
            let ctor = with_host(|h| match h.get(recv) {
                Some(JsObj::Class(c)) => c.ctor.clone(),
                _ => None,
            });
            return match ctor {
                Some(c) => get_property(&c, "length").unwrap_or(Value::Float(0.0)),
                None => Value::Float(0.0),
            };
        }
        // `Symbol.species` is an accessor returning `this`, so a subclass that
        // does not override it IS its own species. Reading it off the builtin
        // ancestor below would answer with the ancestor — `A[Symbol.species]`
        // came back as `Array`, which sent every derived result to a plain
        // array.
        if name == "@@species"
            && with_host(|h| h.class_static(recv, "@@species")).is_none()
            && with_host(|h| h.class_builtin_ancestor(recv))
                .is_some_and(|a| matches!(with_host(|h| h.kind_of(&a)), Some(ObjKind::Builtin)))
        {
            return recv.clone();
        }
        // The chain may bottom out in a BUILTIN constructor (`class D extends
        // Array {}`), whose statics `class_static` cannot see — it only walks
        // `ClassVal.parent` links between user classes. Finish the lookup with an
        // ordinary read on that ancestor so `D.from` inherits `Array.from`.
        if let Some(anc) = with_host(|h| h.class_builtin_ancestor(recv)) {
            if let Ok(v) = get_property(&anc, name) {
                if !matches!(v, Value::Undef) {
                    return v;
                }
            }
        }
    } else if let Some(v) = with_host(|h| h.fn_prop(recv, name)) {
        return v;
    }
    // A method inherited via the function's [[Prototype]] chain (set with
    // `Object.setPrototypeOf(fn, proto)` — the `router` package makes each router
    // *function* inherit `route`/`use`/`get`/… from `Router.prototype` this way).
    if let Some(v) = with_host(|h| host::lookup_chain(h, recv, name)) {
        return v;
    }
    match name {
        "name" => with_host(|h| {
            let n = h.callable_name(recv);
            h.new_str(n)
        }),
        "length" => Value::Float(with_host(|h| h.func_arity(recv)) as f64),
        "prototype" => ensure_fn_prototype(recv),
        _ if is_function_method(name) => bound_method(recv, name),
        _ => Value::Undef,
    }
}

/// The `.prototype` of a function value, auto-created on first access (as Node
/// does for every non-arrow function) with `.constructor` linking back. Arrow
/// functions have no `prototype`.
fn ensure_fn_prototype(recv: &Value) -> Value {
    if let Some(p) = with_host(|h| h.fn_prop(recv, "prototype")) {
        return p;
    }
    // Only a constructor gets one: an arrow, a method definition and an async
    // function are not constructors, and a class sets its own (10.2.5).
    if with_host(|h| h.kind_of(recv)) != Some(ObjKind::Func) {
        return Value::Undef;
    }
    if !with_host(|h| h.owns_prototype(recv)) {
        return Value::Undef;
    }
    with_host(|h| {
        let proto = h.new_object(IndexMap::new());
        if let Some(JsObj::Object(p)) = h.get_mut(&proto) {
            p.insert("constructor".to_string(), recv.clone());
        }
        h.hide_prop(&proto, "constructor");
        h.set_fn_prop(recv, "prototype", proto.clone());
        proto
    })
}

/// The numeric constants a core namespace owns, in the order node reports them
/// under `getOwnPropertyNames`. ONE table rather than a value match plus a name
/// list: the enumeration and the read have to agree, and they did not — every
/// one of these read correctly while `Object.getOwnPropertyNames(Math)` omitted
/// all eight of Math's, so a member that plainly exists was invisible to any
/// reflective copy of the namespace.
///
/// Each is `{ writable: false, enumerable: false, configurable: false }`, which
/// is what separates them from the methods alongside them.
pub fn namespace_constants(ns: &str) -> &'static [(&'static str, f64)] {
    const MATH: &[(&str, f64)] = &[
        ("E", std::f64::consts::E),
        ("LN10", std::f64::consts::LN_10),
        ("LN2", std::f64::consts::LN_2),
        ("LOG10E", std::f64::consts::LOG10_E),
        ("LOG2E", std::f64::consts::LOG2_E),
        ("PI", std::f64::consts::PI),
        ("SQRT1_2", std::f64::consts::FRAC_1_SQRT_2),
        ("SQRT2", std::f64::consts::SQRT_2),
    ];
    const NUMBER: &[(&str, f64)] = &[
        ("MAX_VALUE", f64::MAX),
        // The smallest positive value a Number can hold, which is the
        // smallest SUBNORMAL double (`5e-324`), not Rust's
        // `f64::MIN_POSITIVE` — that is the smallest *normal* double,
        // `2.2250738585072014e-308`, ~256 binary orders of magnitude too
        // large.
        // The literal, not `f64::from_bits(1)`: that is only const-callable from
        // Rust 1.83 and this crate's MSRV is 1.80. It parses to the same
        // bit pattern — the smallest positive subnormal.
        ("MIN_VALUE", 5e-324),
        ("NaN", f64::NAN),
        ("NEGATIVE_INFINITY", f64::NEG_INFINITY),
        ("POSITIVE_INFINITY", f64::INFINITY),
        ("MAX_SAFE_INTEGER", 9007199254740991.0),
        ("MIN_SAFE_INTEGER", -9007199254740991.0),
        ("EPSILON", f64::EPSILON),
    ];
    match ns {
        "Math" => MATH,
        "Number" => NUMBER,
        _ => &[],
    }
}

/// The descriptor of `<ns>.<key>`, whose attributes fall into four groups —
/// measured on node v26.8.1:
///
/// ```text
/// Math.PI, Number.MAX_SAFE_INTEGER, Number.prototype   w=false e=false c=false
/// Math.max.name, Math.max.length                       w=false e=false c=true
/// Math.floor, Array.from, Array.prototype.slice        w=true  e=false c=true
/// require('path').join                                 w=true  e=true  c=true
/// ```
///
/// So: a constant (and a constructor's `prototype`) is frozen, a function's own
/// `name`/`length` is read-only but configurable, and everything else is an
/// ordinary method — enumerable exactly when the namespace enumerates it, which
/// is what separates a core module's exports from an ECMAScript namespace's.
fn builtin_member_descriptor(ns: &str, key: &str, value: Value) -> Value {
    let frozen = namespace_constants(ns).iter().any(|(k, _)| *k == key)
        || key == "prototype"
        || (ns == "Symbol" && host::WELL_KNOWN_SYMBOLS.contains(&key));
    let own_fn_meta = matches!(key, "name" | "length") && host::builtin_is_callable(ns);
    // A key a SCRIPT assigned is an ordinary writable/enumerable/configurable
    // data property, whatever the namespace's built-in members look like — the
    // synthesized answer reported it non-enumerable, so a monkey-patched member
    // described itself as one of the intrinsics.
    let assigned = !intrinsic_proto_member(ns, key)
        && !crate::stdlib::namespace_keys(ns).iter().any(|k| k == key)
        && with_host(|h| h.builtin_static(ns, key).is_some());
    let enumerable = assigned
        || (!frozen && !own_fn_meta && crate::stdlib::namespace_keys(ns).iter().any(|k| k == key));
    with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        m.insert("value".into(), value);
        m.insert(
            "writable".into(),
            Value::Bool(assigned || (!frozen && !own_fn_meta)),
        );
        m.insert("enumerable".into(), Value::Bool(enumerable));
        m.insert("configurable".into(), Value::Bool(assigned || !frozen));
        h.new_object(m)
    })
}

/// Whether `<ns>.<key>` may be deleted — the `configurable` half of
/// [`builtin_member_descriptor`], split out so `delete` can ask without
/// building a descriptor object.
/// Whether `key` is one of the members the intrinsic prototype namespace `ns`
/// really defines — as opposed to a name a script added. An assignment over one
/// of these is a `[[Set]]` and leaves its attributes alone.
fn intrinsic_proto_member(ns: &str, key: &str) -> bool {
    intrinsic_proto_members(ns).is_some_and(|members| {
        members
            .iter()
            .any(|m| m.strip_prefix('+').unwrap_or(m) == key)
    })
}

fn builtin_member_configurable(ns: &str, key: &str) -> bool {
    !(namespace_constants(ns).iter().any(|(k, _)| *k == key)
        || key == "prototype"
        || (ns == "Symbol" && host::WELL_KNOWN_SYMBOLS.contains(&key)))
}

/// The value of `<ns>.<name>` when it is one of those constants.
fn namespace_constant(ns: &str, name: &str) -> Option<f64> {
    namespace_constants(ns)
        .iter()
        .find(|(k, _)| *k == name)
        .map(|(_, v)| *v)
}

/// Whether `ctor` is a WebIDL interface, whose prototype members are plain
/// assigned — and so ENUMERABLE — rather than the non-enumerable ones an
/// ECMAScript builtin defines. The generated member table records the same
/// distinction with its `+` prefix.
fn is_webidl_proto(ctor: &str) -> bool {
    intrinsic_proto_members(&format!("{ctor}.prototype"))
        .is_some_and(|ms| ms.iter().any(|m| m.starts_with('+')))
}

/// The intrinsic constructor a value's own kind implies — the prototype it
/// inherits with no explicit link.
pub(crate) fn own_ctor_name(h: &host::JsHost, v: &Value) -> Option<&'static str> {
    default_ctor_name(h, v)
}

/// Whether `ctor.prototype` defines `key` as a NON-WRITABLE data property, so
/// an object inheriting it refuses an assignment to that name.
pub(crate) fn is_proto_readonly(ctor: &str, key: &str) -> bool {
    crate::arity::PROTO_READONLY
        .binary_search_by(|(k, _)| (*k).cmp(ctor))
        .ok()
        .is_some_and(|i| crate::arity::PROTO_READONLY[i].1.contains(&key))
}

/// Whether `ctor.prototype` defines `key` as an ACCESSOR rather than a data
/// property or a method.
pub(crate) fn is_proto_accessor(ctor: &str, key: &str) -> bool {
    crate::arity::PROTO_ACCESSORS
        .binary_search_by(|(k, _)| (*k).cmp(ctor))
        .ok()
        .is_some_and(|i| crate::arity::PROTO_ACCESSORS[i].1.contains(&key))
}

/// The constructor whose `.prototype` IS `recv`, whichever of the two
/// representations it uses — a `Builtin` namespace handle or a real object.
pub(crate) fn intrinsic_proto_of(recv: &Value) -> Option<String> {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Builtin(ns)) => ns.strip_suffix(".prototype").map(str::to_string),
        _ => h.intrinsic_proto_ctor(recv).map(str::to_string),
    })
}

/// The getter function of an intrinsic prototype accessor, as a first-class
/// value — what `Object.getOwnPropertyDescriptor(Map.prototype, 'size').get`
/// hands back, and the form a library uses to borrow one.
fn proto_getter(ctor: &str, key: &str) -> Value {
    with_host(|h| h.alloc(JsObj::Builtin(format!("@protoget:{ctor}:{key}"))))
}

/// Whether `recv` carries the internal slot `ctor`'s accessor demands. This is
/// a BRAND check, not a chain walk: `Object.create(Map.prototype).size` throws
/// in node even though `Map.prototype` is right there on the chain.
fn brand_matches(recv: &Value, ctor: &str) -> bool {
    if let Some(tag) = crate::stdlib::native_tag(recv) {
        if tag == ctor || (ctor == "TypedArray" && tag == "TypedArray") {
            return true;
        }
    }
    match ctor {
        "TypedArray" => crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray"),
        "ArrayBuffer" => with_host(
            |h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@bytes")),
        ),
        _ => {
            let own = match wrapped_primitive(recv).as_ref().and_then(wrapper_ctor_of) {
                Some(c) => Some(c),
                None => with_host(|h| default_ctor_name(h, recv)),
            };
            own == Some(ctor)
        }
    }
}

thread_local! {
    /// The `(ctor, key)` prototype accessors whose tail read is in flight.
    ///
    /// A getter's last step reads the value off the receiver, and when the
    /// receiver does not STORE it that read walks the chain, finds the same
    /// accessor and runs it again: `new TextDecoder().fatal` recursed until the
    /// stack overflowed and aborted the process. An accessor already in flight
    /// answers `undefined` for its own key rather than re-entering — the value
    /// a missing internal slot has, and what node reports for one.
    static GETTERS_IN_FLIGHT: std::cell::RefCell<Vec<(String, String)>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Whether `ctor`'s `key` getter is already running further down the stack.
fn getter_in_flight(ctor: &str, key: &str) -> bool {
    GETTERS_IN_FLIGHT.with(|g| g.borrow().iter().any(|(c, k)| c == ctor && k == key))
}

/// Invoke an intrinsic prototype's getter against `recv` — the body behind the
/// `@protoget:` thunks.
///
/// Reading one OFF THE PROTOTYPE (`Map.prototype.size`) is the case that was
/// wrong: it answered `undefined` where node runs the getter, fails the brand
/// check and throws. `RegExp.prototype` is the documented exception — 22.2.6.10
/// and .13 return `"(?:)"` and `""` for it specifically, so the one receiver
/// that would otherwise throw for every flag reads two of them back.
pub(crate) fn proto_getter_call(ctor: &str, key: &str, recv: &Value) -> Result<Value, String> {
    let is_the_prototype = with_host(
        |h| matches!(h.get(recv), Some(JsObj::Builtin(ns)) if *ns == format!("{ctor}.prototype")),
    );
    if is_the_prototype && ctor == "RegExp" {
        // 22.2.6.x each carry the same step: when `this` IS `%RegExp.prototype%`
        // the getter returns rather than throwing. `source` and `flags` have
        // their own values there; every flag getter answers `undefined`.
        return Ok(match key {
            "source" => with_host(|h| h.new_str("(?:)".to_string())),
            "flags" => with_host(|h| h.new_str(String::new())),
            _ => Value::Undef,
        });
    }
    // `RegExp.prototype.flags` (22.2.6.5) is the one that is GENERIC: it reads
    // the individual flag properties off whatever object it is handed and
    // concatenates their letters, so a plain object answers `""` rather than
    // throwing, and one carrying `global`/`ignoreCase` answers `"gi"`.
    if ctor == "RegExp" && key == "flags" && !brand_matches(recv, ctor) {
        if !with_host(|h| is_object_like(h, recv)) {
            return Err(regexp_brand_error(key, recv));
        }
        let mut out = String::new();
        for (prop, letter) in REGEXP_FLAG_LETTERS {
            let v = get_property(recv, prop)?;
            if with_host(|h| h.truthy(&v)) {
                out.push(*letter);
            }
        }
        return Ok(with_host(|h| h.new_str(out)));
    }
    // `Function.prototype.arguments`/`caller` are POISON PILLS (10.2.4.1): both
    // the getter and the setter throw for every receiver, which is how a strict
    // function keeps its caller unreachable. They are not brand checks and do
    // not name the receiver.
    if ctor == "Function" && matches!(key, "arguments" | "caller") {
        return poison_pill_read(recv);
    }
    if !brand_matches(recv, ctor) {
        return Err(match ctor {
            "RegExp" => regexp_brand_error(key, recv),
            "Symbol" => {
                host::type_error("Symbol.prototype.description requires that 'this' be a Symbol")
            }
            _ => host::type_error(&format!(
                "Method get {ctor}.prototype.{key} called on incompatible receiver {}",
                brand_receiver_string(recv)
            )),
        });
    }
    // A native instance keeps an accessor's value in the hidden `@@<key>` slot,
    // so that the public name can be a getter on the prototype rather than an
    // own enumerable property. Read it straight: the chain walk below would
    // find this same accessor and run it again.
    if let Some(v) = with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.get(&format!("@@{key}")).cloned(),
        _ => None,
    }) {
        return Ok(v);
    }
    GETTERS_IN_FLIGHT.with(|g| g.borrow_mut().push((ctor.to_string(), key.to_string())));
    let out = get_property(recv, key);
    GETTERS_IN_FLIGHT.with(|g| {
        g.borrow_mut().pop();
    });
    out
}

/// `Function.prototype.arguments`/`caller` read against `recv`.
///
/// The pill is conditional and the condition is the RECEIVER, not the reading
/// code: a sloppy non-arrow function answers `null` (node stopped populating
/// these long ago but kept them readable), and everything else — an arrow, a
/// strict function, a non-function — throws. Keying it on the READER's
/// strictness, which is what this did, made `strictFn.arguments` answer
/// `undefined` from sloppy code and a sloppy function throw from strict code:
/// wrong in both directions.
pub(crate) fn poison_pill_read(recv: &Value) -> Result<Value, String> {
    if with_host(|h| h.fn_is_sloppy(recv)) {
        return Ok(with_host(|h| h.null()));
    }
    Err(host::type_error(POISON_PILL))
}

/// The message both halves of the `arguments`/`caller` poison pill throw.
pub(crate) const POISON_PILL: &str = "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them";

/// How a REJECTED receiver is rendered in a brand-check message.
///
/// `no_side_effects_string` answers for most of them, but two kinds differ:
/// an intrinsic PROTOTYPE renders `#<Map>` rather than `[object Map]`, and so
/// does an `ArrayBuffer`/`DataView` instance, which this host tags natively and
/// that function therefore brands. Node draws the line at whether the value is
/// one of the ES5-era classes (`Array`, `Date`, `RegExp` are `[object X]`); the
/// two cases here are the ones that fall on the other side of it.
fn brand_receiver_string(recv: &Value) -> String {
    if let Some(ctor) = intrinsic_proto_of(recv) {
        return format!("#<{ctor}>");
    }
    match crate::stdlib::native_tag(recv).as_deref() {
        Some(tag @ ("ArrayBuffer" | "DataView")) => format!("#<{tag}>"),
        _ => no_side_effects_string(recv),
    }
}

/// The flag properties `RegExp.prototype.flags` reads, in the order 22.2.6.5
/// concatenates their letters.
const REGEXP_FLAG_LETTERS: &[(&str, char)] = &[
    ("hasIndices", 'd'),
    ("global", 'g'),
    ("ignoreCase", 'i'),
    ("multiline", 'm'),
    ("dotAll", 's'),
    ("unicode", 'u'),
    ("unicodeSets", 'v'),
    ("sticky", 'y'),
];

/// `RegExp.prototype`'s flag getters word their brand failure their own way,
/// and `flags` distinguishes a non-object receiver from a non-RegExp one
/// because 22.2.6.5 reads the individual flags off any object it is given.
fn regexp_brand_error(key: &str, recv: &Value) -> String {
    if key == "flags" && !with_host(|h| matches!(recv, Value::Obj(_)) && !h.is_null(recv)) {
        return host::type_error(&format!(
            "RegExp.prototype.flags getter called on non-object {}",
            no_side_effects_string(recv)
        ));
    }
    host::type_error(&format!(
        "RegExp.prototype.{key} getter called on non-RegExp object"
    ))
}

/// A property on a builtin namespace object (`Math.PI`, `Number.MAX_SAFE_INTEGER`,
/// `console.log`).
pub fn namespace_property(ns: &str, name: &str) -> Value {
    // `require.cache[id]` — a LIVE view of the module cache, not a copy, so a
    // read sees whatever is loaded now and `delete` (see `delete_property`)
    // actually invalidates.
    if ns == REQUIRE_CACHE {
        return crate::module::cache_get(name).unwrap_or(Value::Undef);
    }
    // A property a SCRIPT assigned onto this namespace wins over everything
    // synthesized below, including a member the namespace really has. That is
    // what monkey-patching an intrinsic is: `Array.prototype.join = f` must make
    // `[1, 2].join()` call `f`, and a polyfill's `Array.prototype.at = impl` has
    // to read back at all. Only the two `Error` hooks consulted this table, so
    // every other assignment onto a builtin — the whole polyfill idiom — was
    // stored by `set_property` and then never read: the write appeared to
    // succeed, `Object.isExtensible` said true, and the value came back
    // `undefined`.
    if let Some(v) = with_host(|h| h.builtin_static(ns, name)) {
        return v;
    }
    // The ENTRY script's `require` is this builtin rather than the per-module
    // closure, so its `cache` has to be handed out here too.
    // `require.extensions` — the legacy loader map. Deprecated but still read
    // (and sometimes written) by tooling that hooks module loading, and it was
    // absent entirely. The three keys node ships are present; installing a
    // custom loader through them is NOT honoured by this runtime's loader, so
    // the map reports what it can serve rather than pretending otherwise.
    // `util.promisify.custom` — the registered symbol a module attaches to a
    // callback function to supply its own promisified form. It was `undefined`,
    // so the lookup that decides whether to use one always missed.
    if ns == "util.promisify" && name == "custom" {
        return with_host(|h| h.symbol_for("nodejs.util.promisify.custom"));
    }
    // `process.memoryUsage.rss()` — node's fast path for the one figure that
    // does not need the whole object built.
    if ns == "process.memoryUsage" && name == "rss" {
        return with_host(|h| h.alloc(JsObj::Builtin("process.memoryUsage.rss".to_string())));
    }
    if ns == "require" && name == "extensions" {
        return with_host(|h| {
            let mut m: IndexMap<String, Value> = IndexMap::new();
            for ext in [".js", ".json", ".node"] {
                let f = h.alloc(JsObj::Builtin(format!("@@extension:{ext}")));
                m.insert(ext.to_string(), f);
            }
            h.new_object(m)
        });
    }
    // `require.resolve.paths(spec)` — the directories a lookup would search:
    // `null` for a core module, the `node_modules` chain otherwise.
    if ns == "require.resolve" && name == "paths" {
        return with_host(|h| h.alloc(JsObj::Builtin("require.resolve.paths".to_string())));
    }
    if ns == "require" && name == "cache" {
        return with_host(|h| h.alloc(JsObj::Builtin(REQUIRE_CACHE.to_string())));
    }
    // The legacy numeric codes `DOMException` carries as statics
    // (`DOMException.ABORT_ERR` is 20), named by uppercasing the error name.
    if ns == "DOMException" {
        if let Some((_, code)) = DOM_EXCEPTION_CODES
            .iter()
            .find(|(n, _)| legacy_code_name(n) == name)
        {
            return Value::Float(*code);
        }
    }
    // Numeric constants.
    if let Some(k) = namespace_constant(ns, name) {
        return Value::Float(k);
    }
    // `Ctor.name` on a builtin constructor is the constructor name (`Array.name`
    // === "Array"); non-callable namespaces (`Math`/`JSON`) fall through to
    // `undefined`.
    // `GeneratorFunction.prototype` and the two async variants are REAL objects
    // in `native_protos`, not `Builtin("X.prototype")` namespace handles — they
    // sit on the prototype chain of every generator/async function, which a
    // handle cannot do. Without this the read fell through to `undefined`.
    if name == "prototype"
        && matches!(
            ns,
            "GeneratorFunction" | "AsyncFunction" | "AsyncGeneratorFunction"
        )
    {
        return with_host(|h| {
            h.ensure_native_protos();
            h.native_proto(ns).unwrap_or(Value::Undef)
        });
    }
    // `Error.prepareStackTrace` has a DEFAULT hook in node
    // (`ErrorPrepareStackTrace`), so a library probing `if
    // (Error.prepareStackTrace)` finds one. Reading `undefined` sent that probe
    // down the wrong branch. The default renders the header plus the frames,
    // which is what the fast path in `materialize_stack` already produces — it
    // recognises this exact builtin and skips the round trip.
    if ns == "Error" && name == "prepareStackTrace" {
        return with_host(|h| h.builtin_static("Error", "prepareStackTrace")).unwrap_or_else(
            || with_host(|h| h.alloc(JsObj::Builtin(DEFAULT_PREPARE.to_string()))),
        );
    }
    // `Error.stackTraceLimit` defaults to 10 and is settable; an assignment
    // lands in the builtin-static side table, which the read below consults
    // first. Without a default the READ was `undefined`, so a library doing
    // `const old = Error.stackTraceLimit` and restoring it later installed
    // `undefined` and disabled the limit permanently.
    if ns == "Error" && name == "stackTraceLimit" {
        return with_host(|h| h.builtin_static("Error", "stackTraceLimit"))
            .unwrap_or(Value::Float(10.0));
    }
    // `Ctor[Symbol.species]` is an accessor returning `this` on every builtin
    // that has one (23.1.2.5, 27.2.4.7, …). It was absent, so the species
    // protocol had nothing to read and every derived result came back a plain
    // builtin.
    if name == "@@species" && has_species(ns) {
        return with_host(|h| h.alloc(JsObj::Builtin(ns.to_string())));
    }
    if name == "name" && is_builtin_ctor(ns) {
        return with_host(|h| h.new_str(ns.to_string()));
    }
    // A well-known symbol (`Symbol.iterator`, `Symbol.toPrimitive`, …) used as a
    // computed property/method key.
    if ns == "Symbol" && host::WELL_KNOWN_SYMBOLS.contains(&name) {
        return with_host(|h| h.well_known_symbol(name));
    }
    // Non-function constants on a stdlib namespace (`path.sep`, `os.EOL`,
    // `buffer.Buffer`, `url.URL`).
    if let Some(v) = crate::stdlib::constant(ns, name) {
        return v;
    }
    // `Ctor.prototype` on a builtin constructor (`Object.prototype`,
    // `Array.prototype`, …): a prototype namespace whose methods are callable
    // thunks (`Object.prototype.toString.call(x)` is a load-time idiom in the
    // `get-intrinsic`/`function-bind` family).
    if name == "prototype" && is_builtin_ctor(ns) {
        // Same reasoning as the native prototypes below, for the error
        // hierarchy: `new Error(...)` links its `[[Prototype]]` to the REAL
        // `error_protos` object, so `Error.prototype` has to read back that same
        // object. It resolved to a fresh `Builtin("Error.prototype")` thunk
        // instead, which is a FUNCTION — so `Object.getPrototypeOf(new
        // Error("x")) === Error.prototype` was false, and `typeof
        // Error.prototype` was `"function"` where node says `"object"`.
        if host::ERROR_NAMES.contains(&ns) {
            if let Some(p) = with_host(|h| {
                h.ensure_error_protos();
                host::error_proto_of(h, ns)
            }) {
                return p;
            }
        }
        // `Buffer`/`Uint8Array` have real prototype *objects* — a Buffer's
        // `[[Prototype]]` points at one, so `Object.getPrototypeOf(buf) ===
        // Buffer.prototype` must compare equal, which a freshly-allocated
        // `Builtin` handle never can.
        if let Some(p) = with_host(|h| {
            h.ensure_native_protos();
            h.native_proto(ns)
        }) {
            return p;
        }
        let _ = ns;
        return with_host(|h| h.alloc(JsObj::Builtin(format!("{ns}.prototype"))));
    }
    // A NATIVE stdlib constructor's `.prototype` (`StringDecoder`, `Hash`,
    // `URLSearchParams`, …). These are absent from `is_builtin_ctor`, so the arm
    // above never fired and the read produced `undefined` — which broke the ES5
    // subclassing pattern libraries still ship. `iconv-lite`'s internal codec
    // reads `StringDecoder.prototype.end` at load, and threw
    // `Cannot read properties of undefined (reading 'end')`. Built from the same
    // instance-method table a method read consults, so the two cannot disagree.
    if name == "prototype" {
        if let Some(p) = with_host(|h| h.ensure_ctor_proto(ns)) {
            return p;
        }
    }
    // A method read off a builtin prototype namespace (`Array.prototype.slice`):
    // a `@proto:<Ctor>:<method>` thunk that, when invoked (typically via
    // `.call`/`.apply`), dispatches `method` against the invoke-time `this`.
    //
    // The thunk is minted only for a name the prototype REALLY carries. Minting
    // one unconditionally made every absent name answer with a function:
    // `Array.prototype.totallyBogus` was `[Function: totallyBogus]` where node
    // says `undefined`, and so was every well-known symbol a prototype does not
    // define — `Array.prototype[Symbol.toStringTag]` came back a function
    // instead of `undefined`, which is a value `Object.prototype.toString` and
    // every `typeof`/truthiness test downstream then read wrong.
    //
    // Existence is decided by the generated intrinsic table, which is read out
    // of the reference engine, so this cannot drift from what node defines.
    // A name the prototype does not define but `Object.prototype` does is
    // INHERITED, and node hands back Object.prototype's own function object
    // (`Map.prototype.toString === Object.prototype.toString` is `true`), so it
    // resolves to the `Object` thunk rather than a per-ctor one. That is also
    // what makes `String(Map.prototype)` print `[object Map]`: `Map.prototype`
    // has no own `toString`, and the inherited one is the generic tag reader,
    // not a Map method that rejects a non-Map `this`.
    if let Some(ctor) = ns.strip_suffix(".prototype") {
        // `Array.prototype[Symbol.unscopables]` (23.1.3.38) is a DATA property,
        // not an intrinsic function, so it is not in the arity table the lookup
        // above consults. It lists the methods a `with` block must NOT bring
        // into scope — the ones added after `with` existed, so old code using a
        // variable of the same name keeps working.
        if name == "@@unscopables" && ctor == "Array" {
            return with_host(|h| {
                let mut m: IndexMap<String, Value> = IndexMap::new();
                for k in [
                    "at",
                    "copyWithin",
                    "entries",
                    "fill",
                    "find",
                    "findIndex",
                    "findLast",
                    "findLastIndex",
                    "flat",
                    "flatMap",
                    "includes",
                    "keys",
                    "toReversed",
                    "toSorted",
                    "toSpliced",
                    "values",
                ] {
                    m.insert(k.to_string(), Value::Bool(true));
                }
                let o = h.new_object(m);
                let null = h.null();
                h.set_proto(&o, null);
                o
            });
        }
        if builtin_meta(&format!("@proto:{ctor}:{name}")).is_some() {
            return with_host(|h| h.alloc(JsObj::Builtin(format!("@proto:{ctor}:{name}"))));
        }
        if ctor != "Object" && builtin_meta(&format!("@proto:Object:{name}")).is_some() {
            return with_host(|h| h.alloc(JsObj::Builtin(format!("@proto:Object:{name}"))));
        }
        // `constructor` is excluded from the table because it is not a method:
        // it is the constructor function itself, and node compares equal
        // (`Array.prototype.constructor === Array`). It used to resolve to a
        // `@proto:Array:constructor` thunk, which is a different object every
        // read and so never compared equal to anything.
        if name == "constructor" && is_builtin_ctor(ctor) {
            return with_host(|h| h.alloc(JsObj::Builtin(ctor.to_string())));
        }
        return Value::Undef;
    }
    let qualified = format!("{ns}.{name}");
    if is_known_builtin(&qualified) {
        return with_host(|h| h.alloc(JsObj::Builtin(qualified)));
    }
    // A property the user stuck on this builtin namespace (`Error.prepareStackTrace`).
    if let Some(v) = with_host(|h| h.builtin_static(ns, name)) {
        return v;
    }
    // A builtin FUNCTION's own `name` and `length` (10.3.3-4: every one has
    // both). `Math.max.name` was `undefined` — as was every `.name` a library
    // reads to identify a callback it was handed. The non-callable namespaces
    // fall through: `Math.name` and `require('fs').length` really are undefined.
    if host::builtin_is_callable(ns) {
        match name {
            "name" => {
                if let Some(n) = proto_getter_name(ns) {
                    return with_host(|h| h.new_str(n));
                }
                return with_host(|h| h.new_str(builtin_name(ns).to_string()));
            }
            // Only the intrinsics have a specified arity; a core-module
            // function's is a property of node's own JS source, so it stays
            // `undefined` rather than being invented here.
            "length" => {
                // A getter takes no argument (10.2.9 / the accessor grammar),
                // so its `length` is 0 — it is not in the intrinsic table,
                // which holds only named functions.
                if proto_getter_name(ns).is_some() {
                    return Value::Float(0.0);
                }
                if let Some((_, len)) = builtin_meta(ns) {
                    return Value::Float(len as f64);
                }
            }
            _ => {}
        }
    }
    Value::Undef
}

/// Dispatch a `@proto:<Ctor>:<method>` thunk (a method read off a builtin
/// prototype, e.g. `Object.prototype.toString`) against `recv` (its invoke-time
/// `this`). `Object.prototype.toString` yields the `[object Tag]` brand string
/// libraries type-check on; every other method routes through normal method
/// dispatch on `recv`.
/// The TypeError a `<Ctor>.prototype.<method>` thunk throws when it is invoked
/// with NO receiver — `const f = [].push; f(1)`.
///
/// Reading a method off an instance used to mint a thunk bound to that
/// instance, so a detached method silently kept working on the object it came
/// from. Now that it is the shared intrinsic, a bare call has no `this` and has
/// to say so. Node words it four ways, and which one a method gets is not
/// something that can be derived — the split was measured across every method
/// of each prototype:
///
/// ```text
/// ToObject(this)         "Cannot convert undefined or null to object"
/// RequireObjectCoercible "<Ctor>.prototype.<m> called on null or undefined"
/// brand check            "<Ctor>.prototype.<m> requires that 'this' be a <X>"
/// everything else        the generic incompatible-receiver message
/// ```
fn nullish_receiver_error(ctor: &str, method: &str, recv: &str) -> Option<String> {
    // `Array.prototype` splits: the CALLBACK-taking methods plus `concat` and
    // the two `indexOf` family members name themselves, the rest go through
    // `ToObject` and report its message.
    const ARRAY_NAMED: &[&str] = &[
        "concat",
        "every",
        "filter",
        "find",
        "findIndex",
        "findLast",
        "findLastIndex",
        "forEach",
        "indexOf",
        "map",
        "reduce",
        "reduceRight",
        "some",
    ];
    const TO_OBJECT: &str = "Cannot convert undefined or null to object";
    let named = |c: &str| format!("{c}.prototype.{method} called on null or undefined");
    let branded =
        |c: &str, want: &str| format!("{c}.prototype.{method} requires that 'this' be a {want}");
    // The generic form names the receiver, so a `null` one must not be reported
    // as `undefined`.
    let generic = |c: &str, m: &str| {
        format!("Method {c}.prototype.{m} called on incompatible receiver {recv}")
    };
    Some(match ctor {
        "Array" if ARRAY_NAMED.contains(&method) => named("Array"),
        "Array" => TO_OBJECT.to_string(),
        // `Object.prototype.toString` is the one method that ACCEPTS a nullish
        // receiver — it answers `[object Undefined]`.
        "Object" if method == "toString" => return None,
        "Object" if method == "toLocaleString" => named("Object"),
        "Object" => TO_OBJECT.to_string(),
        // Both aliases report the LEGACY name in the message, which is the one
        // place `name` and the message disagree.
        "String" if method == "trimStart" => named("String").replace("trimStart", "trimLeft"),
        "String" if method == "trimEnd" => named("String").replace("trimEnd", "trimRight"),
        "String" if matches!(method, "toString" | "valueOf") => branded("String", "String"),
        "String" => named("String"),
        "Number" => branded("Number", "Number"),
        "Boolean" => branded("Boolean", "Boolean"),
        "Symbol" => branded("Symbol", "Symbol"),
        "Function" if method == "bind" => "Bind must be called on a function".to_string(),
        "Function" if matches!(method, "call" | "apply") => format!(
            "Function.prototype.{method} was called on undefined, which is undefined and not a function"
        ),
        "Function" => branded("Function", "Function"),
        // `Promise.prototype.catch`/`finally` are written in terms of `then`, so
        // a nullish receiver fails inside them and reports that instead.
        "Promise" if method == "catch" => {
            "Cannot read properties of undefined (reading 'then')".to_string()
        }
        "Promise" if method == "finally" => {
            "Promise.prototype.finally called on non-object".to_string()
        }
        "Date" if method == "toJSON" => TO_OBJECT.to_string(),
        // The plain GETTERS and `valueOf` read `[[DateValue]]` directly and
        // report that slot check; every setter, every `to*String` and the two
        // legacy year methods go through the generic receiver check first.
        "Date"
            if method == "valueOf"
                || (method.starts_with("get") && method != "getYear") =>
        {
            "this is not a Date object.".to_string()
        }
        // An ALIAS reports the method it aliases: `toGMTString` IS `toUTCString`
        // and `Set.prototype.keys` IS `values`, one function object each.
        "Date" if method == "toGMTString" => generic("Date", "toUTCString"),
        "Set" if method == "keys" => generic("Set", "values"),
        // Everything else that is brand-checked names itself. Node reaches this
        // wording from a `[[GetOwnProperty]]`-style slot check; here the check
        // is the receiver's kind, and only the message has to agree.
        "ArrayBuffer" | "DataView" | "RegExp" | "WeakRef" | "Map" | "Set" | "WeakMap"
        | "WeakSet" | "Promise" | "Date" => generic(ctor, method),
        "URLSearchParams" => "Value of \"this\" must be of type URLSearchParams".to_string(),
        // Node's `URL` methods fail while reaching for their internal state, and
        // report the read that failed rather than the method.
        "URL" => "Cannot read properties of undefined (reading 'URL')".to_string(),
        _ => return None,
    })
}

/// Whether `<ctor>.prototype.<method>` begins with a `this<Type>Value` brand
/// check (21.1.3, 20.3.3, 22.1.3.29/.35, 21.2.3). Every `Number.prototype`
/// method does; of `String.prototype` only `toString`/`valueOf` do — the rest
/// are generic and coerce their receiver with `ToString`.
fn is_brand_checked_primitive_method(ctor: &str, method: &str) -> bool {
    match ctor {
        "Number" => matches!(
            method,
            "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision"
        ),
        "BigInt" => matches!(method, "toString" | "toLocaleString" | "valueOf"),
        "String" | "Boolean" => matches!(method, "toString" | "valueOf"),
        _ => false,
    }
}

/// `this<Type>Value(recv)` for `ctor` ∈ Number/String/Boolean/BigInt: the
/// primitive itself, the primitive a wrapper boxes, or — for the three
/// prototypes that are themselves wrappers (21.1.3, 22.1.3, 20.3.3) — the
/// prototype's own `+0` / `""` / `false`. `None` is the TypeError case.
fn this_primitive_value(ctor: &str, recv: &Value) -> Option<Value> {
    let expected = match ctor {
        "Number" => "number",
        "String" => "string",
        "Boolean" => "boolean",
        "BigInt" => "bigint",
        _ => return None,
    };
    let is_expected = |v: &Value| with_host(|h| h.type_of(v)) == expected;
    if is_expected(recv) {
        return Some(recv.clone());
    }
    if let Some(prim) = wrapped_primitive(recv).filter(is_expected) {
        return Some(prim);
    }
    if with_host(|h| h.intrinsic_proto_ctor(recv) == Some(ctor)) {
        return match ctor {
            "Number" => Some(Value::Float(0.0)),
            "String" => Some(with_host(|h| h.new_str(""))),
            "Boolean" => Some(Value::Bool(false)),
            _ => None,
        };
    }
    None
}

pub fn proto_method(recv: &Value, ctor_method: &str, args: Vec<Value>) -> Result<Value, String> {
    let (ctor, method) = ctor_method.split_once(':').unwrap_or(("", ctor_method));
    // A prototype ACCESSOR installed by `ensure_ctor_proto`: it reads or writes
    // the instance's hidden `@@<name>` slot, which is where the value lives now
    // that the public name is a getter rather than an own property.
    if let Some(key) = method.strip_prefix("@get@") {
        if let Some(v) = with_host(|h| match h.get(recv) {
            Some(JsObj::Object(p)) => p.get(&format!("@@{key}")).cloned(),
            _ => None,
        }) {
            return Ok(v);
        }
        // No stored slot: the value is COMPUTED, so ask the class. `KeyObject`'s
        // `symmetricKeySize` is the secret's byte length, which nothing stores.
        let tag = crate::stdlib::native_tag(recv).unwrap_or_default();
        return crate::stdlib::instance_call(&tag, recv, method, args);
    }
    if let Some(key) = method.strip_prefix("@set@") {
        let v = args.first().cloned().unwrap_or(Value::Undef);
        with_host(|h| {
            if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                p.insert(format!("@@{key}"), v);
            }
        });
        crate::stdlib::instance_accessor_written(ctor, key, recv);
        return Ok(Value::Undef);
    }
    if with_host(|h| h.is_nullish(recv)) {
        let shown = if with_host(|h| h.is_null(recv)) {
            "null"
        } else {
            "undefined"
        };
        if let Some(msg) = nullish_receiver_error(ctor, method, shown) {
            return Err(format!("TypeError: {msg}"));
        }
    }
    // `Error.prototype.toString` (20.5.3.4): `name`, `message`, or `name:
    // message`, read off the chain so a subclass's `this.name = 'E'` is honored.
    if ctor == "Error" && method == "toString" {
        // A `DOMException` keeps its `name`/`message` in internal slots, so the
        // chain read below would find the class name on the prototype instead.
        if let Some(n) = dom_exception_slot(recv, "name") {
            let name = with_host(|h| h.str_of(&n));
            let msg = dom_exception_slot(recv, "message")
                .map(|m| with_host(|h| h.str_of(&m)))
                .unwrap_or_default();
            let s = if msg.is_empty() {
                name
            } else {
                format!("{name}: {msg}")
            };
            return Ok(with_host(|h| h.new_str(s)));
        }
        // `name` and `message` are read with `[[Get]]` (20.5.3.4 steps 3 and 5),
        // so a PROXY supplies them through its `get` trap. Reading the stored
        // ones first made `String(new Proxy(err, handler))` ignore the handler.
        let via_proxy = with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy);
        let stored = (!via_proxy).then(|| with_host(|h| h.error_to_string(recv)));
        let s = match stored.flatten() {
            Some(s) => s,
            None => {
                let read = |k: &str| -> Result<Option<String>, String> {
                    Ok(host::protocol_lookup(recv, k)?.map(|v| with_host(|h| h.str_of(&v))))
                };
                let name = read("name")?.unwrap_or_else(|| "Error".into());
                let msg = read("message")?.unwrap_or_default();
                if msg.is_empty() {
                    name
                } else {
                    format!("{name}: {msg}")
                }
            }
        };
        return Ok(with_host(|h| h.new_str(s)));
    }
    // The methods that read their receiver through `thisNumberValue` /
    // `thisBooleanValue` / `thisStringValue` / `thisBigIntValue` accept only the
    // primitive, its wrapper, or the prototype object (which carries the zero
    // value) — anything else is a TypeError naming the method. Unchecked,
    // `Number.prototype.valueOf.call({})` answered `{}`, `toFixed.call({})`
    // reported "toFixed is not a function", and `Number.prototype.valueOf()`
    // recursed through the generic conversion until the stack overflowed.
    if is_brand_checked_primitive_method(ctor, method) {
        let Some(prim) = this_primitive_value(ctor, recv) else {
            return Err(format!(
                "TypeError: {ctor}.prototype.{method} requires that 'this' be a {ctor}"
            ));
        };
        return host::call_method(&prim, method, args);
    }
    // A primitive wrapper's `toString`/`valueOf`/`toLocaleString`: unwrap and
    // answer as the boxed primitive does. `Number.prototype.toString.call(5)`
    // arrives with an already-primitive receiver and needs no unwrapping.
    if matches!(ctor, "String" | "Number" | "Boolean") {
        let prim = wrapped_primitive(recv).unwrap_or_else(|| recv.clone());
        return host::call_method(&prim, method, args);
    }
    // `thisSymbolValue`/`thisBigIntValue` (20.4.3, 21.2.3) accept a WRAPPER as
    // readily as the primitive, and neither was unwrapped here. A BigInt
    // wrapper's `valueOf` therefore re-entered the generic conversion, which
    // looked `valueOf` up again and called it again: `+Object(9n)` recursed
    // until the stack overflowed and ABORTED the process, which no try/catch can
    // see. A Symbol wrapper failed the brand check below instead and reported
    // that `this` was not a Symbol, when it is one. Only a real wrapper is
    // unwrapped — `Symbol.prototype` itself boxes nothing and still has to reach
    // the brand check.
    if matches!(ctor, "Symbol" | "BigInt") {
        if let Some(prim) = wrapped_primitive(recv) {
            return host::call_method(&prim, method, args);
        }
    }
    if ctor == "Object" && method == "toString" {
        // Steps 16-17 of 20.1.3.6: a `Symbol.toStringTag` STRING on the receiver
        // (own or inherited, data property or getter) replaces the builtin brand,
        // which is how a class advertises its own (`class C { get
        // [Symbol.toStringTag]() { return 'Cee' } }` → `[object Cee]`). The read
        // runs outside the host borrow so an accessor can be invoked.
        // A Proxy has no chain to probe: 20.1.3.6 step 15 is an unconditional
        // `Get(O, @@toStringTag)`, so the `get` trap decides. Probing first (as
        // the ordinary receiver does, to keep the read off objects that have no
        // tag) would always miss and brand every tagged proxy `[object Object]`.
        if let Some(s) = to_string_tag(recv)? {
            return Ok(with_host(|h| h.new_str(format!("[object {s}]"))));
        }
        return Ok(with_host(|h| h.new_str(object_tag(h, recv))));
    }
    // These thunks now live on the real `Object.prototype` object, i.e. on the
    // receiver's own chain — routing back through `call_method` would re-resolve
    // this very thunk and recurse.
    if ctor == "Object" && is_object_builtin_method(method) {
        return object_builtin_method(recv, method, args);
    }
    // `EventEmitter.prototype.<m>` mixed onto a receiver (express's `app`): run the
    // emitter method directly against `recv` (routing back through `call_method`
    // would re-resolve the mixed-in thunk and recurse).
    if ctor == "EventEmitter" {
        return crate::stdlib::events::instance_call(recv, method, args);
    }
    // Same recursion hazard for the exotics with a real prototype object: the
    // thunk now lives ON the receiver's prototype chain, so `call_method` would
    // re-resolve this very thunk. Dispatch straight to the native instance
    // implementation when the receiver is in fact an instance of `ctor`.
    if ctor == "Buffer" && crate::stdlib::native_tag(recv).as_deref() == Some("Buffer") {
        return crate::stdlib::buffer::instance_call(recv, method, &args);
    }
    // The shared typed-array methods now live on the `%TypedArray%.prototype`
    // intermediate, so their thunks are tagged `TypedArray`; `Uint8Array` still
    // appears for anything read directly off `Uint8Array.prototype`. Both
    // dispatch the same way, and both must bypass `call_method` or the thunk
    // would re-resolve itself off the receiver's chain and recurse.
    if ctor == "Uint8Array" || ctor == "TypedArray" {
        match crate::stdlib::native_tag(recv).as_deref() {
            Some("Buffer") => return crate::stdlib::buffer::instance_call(recv, method, &args),
            Some("TypedArray") => {
                return crate::stdlib::typedarray::instance_call(recv, method, &args)
            }
            _ => {}
        }
    }
    // `Array.prototype.<m>.call(arrayLike)` — every `Array.prototype` method is
    // GENERIC over `this` (23.1.3: each starts with `ToObject(this)` and
    // `LengthOfArrayLike`), which is what makes
    // `Array.prototype.slice.call(arguments)` the idiom it is. The receiver here
    // is not an Array, so `call_method` would report the method missing.
    if ctor == "Array" && with_host(|h| h.kind_of(recv)) != Some(ObjKind::Array) {
        return array_generic(recv, method, args);
    }
    // The general form of the two special cases above: a thunk taken off a native
    // constructor's real prototype, invoked with a receiver that IS an instance of
    // that constructor. Routing back through `call_method` would re-resolve this
    // very thunk off the receiver's own chain and recurse forever, which is why
    // each such prototype needed a hand-written bypass; now they all have one.
    // A SUBCLASS counts: `SecretKeyObject` reaches `KeyObject.prototype.equals`
    // through its chain, and requiring an exact tag match sent that call back
    // into `call_method`, which re-resolved this same thunk and recursed until
    // the stack overflowed.
    if let Some(tag) = crate::stdlib::native_tag(recv) {
        let mut c = Some(tag.as_str());
        while let Some(t) = c {
            if t == ctor {
                return crate::stdlib::instance_call(&tag, recv, method, args);
            }
            c = crate::stdlib::native_parent(t);
        }
    }
    // A BRANDED method reached with a receiver that has no such internal slot.
    // Every arm above dispatches a receiver that IS an instance, so arriving
    // here with one of these constructors means the brand check failed — the
    // spec's very first step for each of them (24.2.3.x reads `[[SetData]]`,
    // 24.1.3.x `[[MapData]]`, 27.2.5.4 `[[PromiseState]]`, 23.2.3.x
    // `ValidateTypedArray`). Falling through to ordinary dispatch reported
    // `union is not a function`, which says the method does not exist rather
    // than that the receiver is the wrong kind of object.
    // `Date.prototype`'s methods split in two: the ones that read the time value
    // (`ThisTimeValue`, 21.4.4.x) report `this is not a Date object.`, and the
    // rest take the ordinary branded form. Measured on node v26.8.1:
    // `Date.prototype.getTime.call({})` is the first, `.toISOString.call({})`
    // and `.setHours.call({})` the second.
    if ctor == "Date" && crate::stdlib::native_tag(recv).as_deref() != Some("Date") {
        const THIS_TIME_VALUE: &[&str] = &[
            "getTime",
            "valueOf",
            "getYear",
            "getFullYear",
            "getMonth",
            "getDate",
            "getDay",
            "getHours",
            "getMinutes",
            "getSeconds",
            "getMilliseconds",
            "getUTCFullYear",
            "getUTCMonth",
            "getUTCDate",
            "getUTCDay",
            "getUTCHours",
            "getUTCMinutes",
            "getUTCSeconds",
            "getUTCMilliseconds",
            "getTimezoneOffset",
        ];
        if THIS_TIME_VALUE.contains(&method) {
            return Err(host::type_error("this is not a Date object."));
        }
        // `toJSON` (21.4.4.37) is deliberately generic — it converts the
        // receiver and INVOKES `toISOString` on it, so it fails on the missing
        // method rather than on a brand.
        if method != "toJSON" {
            return Err(host::type_error(&format!(
                "Method Date.prototype.{method} called on incompatible receiver {}",
                no_side_effects_string(recv)
            )));
        }
    }
    // `%TypedArray%.prototype`'s methods split the same way: `ValidateTypedArray`
    // (23.2.4.4) reports `this is not a typed array.`, while the handful that
    // check the receiver at the call boundary take the branded form. Measured
    // over all 27 shared methods on node v26.8.1; `toString` is the one that is
    // genuinely generic (it is `Array.prototype.toString`) and never brands.
    if matches!(ctor, "TypedArray" | "Uint8Array")
        && !matches!(
            crate::stdlib::native_tag(recv).as_deref(),
            Some("TypedArray") | Some("Buffer")
        )
    {
        const BRANDED: &[&str] = &[
            "slice",
            "subarray",
            "join",
            "sort",
            "at",
            "toReversed",
            "toSorted",
            "toLocaleString",
        ];
        if BRANDED.contains(&method) {
            return Err(host::type_error(&format!(
                "Method %TypedArray%.prototype.{method} called on incompatible receiver {}",
                no_side_effects_string(recv)
            )));
        }
        // The four base64/hex methods brand themselves against `Uint8Array`
        // specifically — a WRONG view is as incompatible as a plain object, and
        // the generic guard here cannot tell those apart.
        if crate::stdlib::typedarray::UINT8_PROTOTYPE_METHODS.contains(&method) {
            return Err(host::type_error(&format!(
                "Method Uint8Array.prototype.{method} called on incompatible receiver {}",
                no_side_effects_string(recv)
            )));
        }
        if method != "toString" {
            return Err(host::type_error("this is not a typed array."));
        }
    }
    // `Function.prototype.call`/`apply`/`bind` with a callable PROXY as `this`
    // (`pf.call(null, 4, 5)`, reached through the target's chain). Handing
    // that back to `call_method` read `call` off the proxy again, which
    // resolved to this same thunk, and recursed until the stack overflowed and
    // aborted the process. The three are defined on the callee alone, so they
    // run here: the proxy's `apply` trap (or its target) gets the call.
    // `toString` recursed the same way.
    if ctor == "Function"
        && matches!(method, "call" | "apply" | "bind" | "toString")
        && with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy)
    {
        let mut rest = args.into_iter();
        let this_arg = rest.next().unwrap_or(Value::Undef);
        match method {
            "call" => return host::invoke(recv, rest.collect(), Some(this_arg)),
            "apply" => {
                let list = match rest.next() {
                    None | Some(Value::Undef) => Vec::new(),
                    Some(v) if with_host(|h| h.is_null(&v)) => Vec::new(),
                    Some(v) => create_list_from_array_like(&v)?,
                };
                return host::invoke(recv, list, Some(this_arg));
            }
            "bind" => {
                let target = recv.clone();
                let pre: Vec<Value> = rest.collect();
                return Ok(with_host(|h| {
                    h.alloc(JsObj::BoundFunc {
                        target,
                        this: this_arg,
                        args: pre,
                    })
                }));
            }
            // A proxy has no source text; V8 prints the native form for it.
            _ => return Ok(with_host(|h| h.new_str("function () { [native code] }"))),
        }
    }
    // `Symbol.prototype`'s methods are branded, and the receiver that reaches
    // them is very often NOT a symbol: `Symbol.prototype` itself is an ordinary
    // object. Without this check `Symbol.prototype.toString()` re-entered the
    // generic string conversion, which looked `toString` up again and called it
    // again — an infinite recursion that overflowed the stack and ABORTED the
    // process, which no `try`/`catch` can see. Node throws a plain TypeError.
    // The wording is Symbol's own, not the "incompatible receiver" form the
    // collections use.
    if ctor == "Symbol" && with_host(|h| h.kind_of(recv)) != Some(ObjKind::Symbol) {
        // A symbol-KEYED method is named in brackets rather than after a dot:
        // node's wording is `Symbol.prototype [ @@toPrimitive ] requires …`.
        // That is the message `String(Symbol.prototype)` produces, since the
        // conversion reaches `@@toPrimitive` before it would reach `toString`.
        let named = match method.strip_prefix("@@") {
            Some(sym) => format!("Symbol.prototype [ @@{sym} ]"),
            None => format!("Symbol.prototype.{method}"),
        };
        return Err(host::type_error(&format!(
            "{named} requires that 'this' be a Symbol"
        )));
    }
    if let Some(label) = branded_method_label(ctor, recv) {
        return Err(host::type_error(&format!(
            "Method {label}.prototype.{method} called on incompatible receiver {}",
            no_side_effects_string(recv)
        )));
    }
    host::call_method(recv, method, args)
}

/// The name a branded prototype method reports itself under when its receiver
/// fails the brand check, or `None` when `ctor`'s methods are generic over
/// `this` (every `Array.prototype` and `Object.prototype` method is) or the
/// receiver really is an instance.
///
fn branded_method_label(ctor: &str, recv: &Value) -> Option<&'static str> {
    let kind = with_host(|h| h.kind_of(recv));
    // `weak` is part of the brand: a `WeakSet` has `[[WeakSetData]]`, not
    // `[[SetData]]`, so `Set.prototype.has.call(new WeakSet())` is incompatible
    // even though both are `JsObj::Set` here.
    let weak = peek(recv, |o| match o {
        JsObj::Set { weak, .. } | JsObj::Map { weak, .. } => Some(*weak),
        _ => None,
    })
    .unwrap_or(false);
    let ok = match ctor {
        "Set" => kind == Some(ObjKind::Set) && !weak,
        "WeakSet" => kind == Some(ObjKind::Set) && weak,
        "Map" => kind == Some(ObjKind::Map) && !weak,
        "WeakMap" => kind == Some(ObjKind::Map) && weak,
        "Promise" => kind == Some(ObjKind::Promise),
        _ => return None,
    };
    if ok {
        return None;
    }
    Some(match ctor {
        "Set" => "Set",
        "WeakSet" => "WeakSet",
        "Map" => "Map",
        "WeakMap" => "WeakMap",
        _ => "Promise",
    })
}

/// V8's `Object::NoSideEffectsToString`, the rendering an engine-thrown message
/// uses for a value it must not run user code on. Measured on node v26.8.1
/// through `Map.prototype.get.call(x)`:
///
/// ```text
/// 5 / 'str' / true / null / undefined / 9n   the value's own ToString
/// Symbol('s')                                Symbol(s)
/// function f(){}                             its source text
/// new Error('e')                             Error: e
/// {} / new (class A {})                      #<Object> / #<A>
/// new Map() / Promise.resolve()              #<Map> / #<Promise>
/// [] / new Date() / /re/ / new Uint8Array()  [object Array] / [object Date] / …
/// { toString() {} } / Object.create(null)    [object Object]
/// ```
///
/// The split is one test: a receiver whose `toString` is still
/// `Object.prototype.toString` prints `#<Constructor>`, and any other receiver
/// prints what the BUILTIN brand would be — V8 never calls the user's method,
/// which is why an object with its own `toString` prints `[object Object]` and
/// not what that method returns.
fn no_side_effects_string(recv: &Value) -> String {
    if with_host(|h| host::is_primitive(h, recv)) || with_host(|h| host::is_callable(h, recv)) {
        return with_host(|h| h.str_of(recv));
    }
    if let Some(s) = with_host(|h| h.error_to_string(recv)) {
        return s;
    }
    // `native_tag` re-enters the host, so it is read BEFORE the borrow below
    // rather than inside it.
    let native = crate::stdlib::native_tag(recv).is_some();
    let brands_itself = with_host(|h| {
        // `Object.prototype.toString` reaches every object as a thunk on the
        // real prototype object, so its presence proves nothing; only a
        // toString the receiver's chain OVERRIDES it with counts.
        let overridden = host::lookup_chain(h, recv, "toString")
            .map(|f| !matches!(h.get(&f), Some(JsObj::Builtin(n)) if n == "@proto:Object:toString"))
            .unwrap_or(false);
        native
            || overridden
            || h.has_null_proto(recv)
            || !matches!(
                h.kind_of(recv),
                Some(ObjKind::Object)
                    | Some(ObjKind::Map)
                    | Some(ObjKind::Set)
                    | Some(ObjKind::Promise)
            )
    });
    if brands_itself {
        return with_host(|h| object_tag(h, recv));
    }
    let ctor = get_property(recv, "constructor")
        .ok()
        .map(|c| with_host(|h| h.callable_name(&c)))
        .filter(|n| !n.is_empty())
        .unwrap_or_else(|| "Object".to_string());
    format!("#<{ctor}>")
}

/// The value of `v[Symbol.toStringTag]` for a builtin that genuinely carries
/// one, or `None` when reading that symbol must yield `undefined`.
///
/// Every builtin brand is already computed in exactly one place (`object_tag`),
/// so this reuses it and subtracts the legacy builtins, which brand for
/// `Object.prototype.toString` but expose no `Symbol.toStringTag` property.
/// The subtracted list is measured against node v26.7.0, not assumed: `[]`,
/// `function(){}`, `{}`, `new Date()`, `/x/` and `new Error()` all read
/// `undefined`, while `Map`/`Set`/`Promise`/typed arrays/`ArrayBuffer`/
/// `DataView`/`WeakRef`/`FinalizationRegistry`/`BigInt`/`Symbol`/generators/
/// async+generator functions/`Math`/`JSON`/`Reflect`/`URL`/`URLSearchParams`/
/// `TextEncoder`/`TextDecoder` all read their brand.
pub(crate) fn well_known_tag(h: &host::JsHost, v: &Value) -> Option<String> {
    // A primitive never carries the symbol except a BigInt/Symbol wrapper, both
    // of which `object_tag` already brands.
    let tag = object_brand(h, v);
    const NO_TAG: &[&str] = &[
        "Undefined",
        "Null",
        "Boolean",
        "Number",
        "String",
        "Array",
        "Function",
        "Object",
        "Date",
        "RegExp",
        "Error",
    ];
    if NO_TAG.contains(&tag.as_str()) {
        return None;
    }
    Some(tag)
}

/// The constructor name of the nearest intrinsic prototype on `v`'s chain that
/// carries an own `Symbol.toStringTag`, if any.
fn chain_tag_ctor(h: &host::JsHost, v: &Value) -> Option<String> {
    let mut cur = h.proto_of(v);
    for _ in 0..100 {
        let p = cur?;
        if h.is_null(&p) {
            return None;
        }
        let name = match h.get(&p) {
            Some(JsObj::Builtin(ns)) => ns.strip_suffix(".prototype").map(str::to_string),
            _ => h.intrinsic_proto_ctor(&p).map(str::to_string),
        }
        // A CLASS prototype is not linked to the builtin its class extends —
        // the relationship lives on the class value — so the walk crosses over
        // there, or `Object.create(D.prototype)` for `class D extends Map`
        // finds nothing.
        .or_else(|| {
            h.class_owning_proto(&p)
                .and_then(|c| h.class_builtin_ancestor(&c))
                .map(|b| h.callable_name(&b))
                .filter(|n| !n.is_empty())
        });
        if let Some(n) = name {
            if intrinsic_proto_members(&format!("{n}.prototype"))
                .is_some_and(|ms| ms.contains(&"@@toStringTag"))
            {
                return Some(n);
            }
        }
        cur = h.proto_of(&p);
    }
    None
}

/// The `Object.prototype.toString` brand tag for `v` (`[object Array]` etc.).
/// Every builtin exotic object reports its own brand, which is how packages
/// type-test values they did not construct (`toString.call(x) ===
/// '[object Uint8Array]'`). A `Buffer` reports `Uint8Array` because in Node it
/// IS a `Uint8Array` subclass and inherits that `Symbol.toStringTag`.
pub(crate) fn object_tag(h: &host::JsHost, v: &Value) -> String {
    format!("[object {}]", object_brand(h, v))
}

/// The bare brand name behind `Object.prototype.toString` (`Array`, `Uint8Array`
/// …), without the `[object …]` wrapper. Split out so the brand and the
/// `Symbol.toStringTag` property read cannot disagree about what a value is.
/// Whether `v` is a function's `arguments` object.
///
/// Backed by an Array so indices, `length`, spread and `for-of` all work, but
/// marked so it does not pass for one: node's is an exotic, and `isArray`, the
/// brand and `util.types.isArgumentsObject` all have to tell them apart.
pub fn is_arguments(v: &Value) -> bool {
    with_host(|h| is_arguments_h(h, v))
}

/// `is_arguments` for a caller that already holds the host borrow — `object_brand`
/// runs under one, and re-entering through `with_host` aborts the process.
pub fn is_arguments_h(h: &host::JsHost, v: &Value) -> bool {
    h.fn_prop(v, "@@arguments").is_some()
}

fn object_brand(h: &host::JsHost, v: &Value) -> String {
    // A `<C>.prototype` this host built as a real object is an ORDINARY object:
    // it holds no instance slot, so only the branded few report anything but
    // `[object Object]`. Checked before the match because those prototypes are
    // plain `JsObj::Object`s and would otherwise be branded by whatever their
    // own properties happen to look like — `TypeError.prototype` has `name` and
    // `message`, which read as an Error instance.
    if let Some(ctor) = h.intrinsic_proto_ctor(v) {
        return if BRANDED_PROTOS.contains(&ctor) {
            ctor.to_string()
        } else {
            "Object".to_string()
        };
    }
    let tag: String = match v {
        Value::Undef => "Undefined".into(),
        Value::Bool(_) => "Boolean".into(),
        Value::Int(_) | Value::Float(_) => "Number".into(),
        Value::Str(_) => "String".into(),
        Value::Obj(_) => match h.get(v) {
            Some(JsObj::Null) => "Null".into(),
            Some(JsObj::Str(_)) => "String".into(),
            Some(JsObj::Array(_)) if is_arguments_h(h, v) => "Arguments".into(),
            Some(JsObj::Array(_)) => "Array".into(),
            // A lazy iterator helper brands as node does.
            Some(JsObj::Object(p))
                if p.get("@@native").map(|t| h.str_of(t)).as_deref() == Some("IteratorHelper") =>
            {
                "Iterator Helper".into()
            }
            // A `DOMException` brands by its class, not as a plain `Error`.
            Some(JsObj::Object(p)) if p.contains_key("@@domName") => "DOMException".into(),
            // 20.1.3.6 steps 5-8 brand a wrapper by its internal slot, so
            // `Object.prototype.toString.call(new Number(1))` is
            // `[object Number]` rather than `[object Object]`.
            Some(JsObj::Object(p)) if p.contains_key("@@primitive") => match p["@@primitive"] {
                Value::Bool(_) => "Boolean".into(),
                Value::Int(_) | Value::Float(_) => "Number".into(),
                _ => "String".into(),
            },
            // 20.1.3.6 step 3 brands by `IsArray`, which follows a Proxy to its
            // `[[ProxyTarget]]` — `Object.prototype.toString.call(new Proxy([],
            // {}))` is `'[object Array]'`. Everything else about a proxy brands
            // as a plain Object (a `Symbol.toStringTag` read through the `get`
            // trap is handled by the caller, before this).
            Some(JsObj::Proxy { target, .. }) => {
                let mut cur = target;
                for _ in 0..100 {
                    match h.get(cur) {
                        Some(JsObj::Proxy { target: t, .. }) => cur = t,
                        _ => break,
                    }
                }
                match h.get(cur) {
                    Some(JsObj::Array(_)) => "Array".into(),
                    _ => "Object".into(),
                }
            }
            // `function*` / `async function` / `async function*` carry their own
            // `Symbol.toStringTag` in V8 (27.3.3.2, 27.7.3.2, 27.4.3.2).
            Some(JsObj::Func(f)) => match h.funcs.get(f.def_id) {
                Some(d) if d.is_generator && d.is_async => "AsyncGeneratorFunction".into(),
                Some(d) if d.is_generator => "GeneratorFunction".into(),
                Some(d) if d.is_async => "AsyncFunction".into(),
                _ => "Function".into(),
            },
            // `Math`/`JSON`/`Reflect` are namespace OBJECTS, not callables, and
            // brand by name (21.3.1.9, 25.5.3, 28.1.14).
            Some(JsObj::Builtin(n)) if matches!(n.as_str(), "Math" | "JSON" | "Reflect") => {
                n.clone()
            }
            // A `<Ctor>.prototype` object brands as the constructor it belongs
            // to — `Object.prototype.toString.call(Set.prototype)` is
            // `[object Set]` — and a `require()`d module namespace is a plain
            // object. Neither is a function, so neither brands as one.
            Some(JsObj::Builtin(n)) if !host::builtin_is_callable(n) => {
                match n.strip_suffix(".prototype") {
                    Some(ctor) if BRANDED_PROTOS.contains(&ctor) => ctor.to_string(),
                    _ => "Object".into(),
                }
            }
            Some(JsObj::Class(_))
            | Some(JsObj::Builtin(_))
            | Some(JsObj::BoundFunc { .. })
            | Some(JsObj::BoundMethod { .. }) => "Function".into(),
            // A suspended generator object is `[object Generator]`; an async one
            // `[object AsyncGenerator]`.
            Some(JsObj::Generator { .. }) if h.is_async_gen_val(v) => "AsyncGenerator".into(),
            Some(JsObj::Generator { .. }) => "Generator".into(),
            Some(JsObj::RegExp(_)) => "RegExp".into(),
            Some(JsObj::Map { weak, .. }) => if *weak { "WeakMap" } else { "Map" }.into(),
            Some(JsObj::Set { weak, .. }) => if *weak { "WeakSet" } else { "Set" }.into(),
            Some(JsObj::Promise { .. }) => "Promise".into(),
            Some(JsObj::Symbol { .. }) => "Symbol".into(),
            Some(JsObj::BigInt(_)) => "BigInt".into(),
            // Native-tagged instances brand by their tag; a typed array brands by
            // its element kind (`@@kind`), and every Error subclass is `Error`.
            Some(JsObj::Object(p)) => match p.get("@@native").map(|t| h.str_of(t)).as_deref() {
                Some("TypedArray") => p
                    .get("@@kind")
                    .map(|k| h.str_of(k))
                    .unwrap_or_else(|| "Uint8Array".into()),
                Some("Buffer") => "Uint8Array".into(),
                // Every native class that really carries a `Symbol.toStringTag`
                // in Node brands by its own name. Verified against node v26:
                // `Object.prototype.toString.call(new WeakRef({}))` is
                // `[object WeakRef]`. The rest of the `@@native` tags
                // (`EventEmitter`, `Server`, `Hash`, `Readable`, …) are plain
                // classes with NO tag, so they stay `[object Object]` — listing
                // them here would invent a brand Node does not have.
                Some(
                    t @ ("ArrayBuffer"
                    | "DataView"
                    | "Date"
                    | "WeakRef"
                    | "FinalizationRegistry"
                    | "TextEncoder"
                    | "TextDecoder"
                    | "URL"
                    | "URLSearchParams"),
                ) => t.into(),
                _ if has_error_data(h, v) => "Error".into(),
                _ => "Object".into(),
            },
            _ => "Object".into(),
        },
        // node-js only produces the Value variants above; fusevm's shell-oriented
        // variants never arise here.
        _ => "Object".into(),
    };
    // Nothing about the value itself brands it. An ordinary object whose CHAIN
    // reaches an intrinsic prototype carrying an own `Symbol.toStringTag`
    // borrows that one: 20.1.3.6 step 15 is a `Get`, which walks.
    // `Object.prototype.toString.call(Object.create(Map.prototype))` is
    // `[object Map]` and was `[object Object]`.
    //
    // Only as a FALLBACK, and only for the prototypes that REALLY carry the
    // symbol. A typed array reaches `%TypedArray%.prototype`, whose tag is an
    // ACCESSOR returning the specific kind, so consulting the chain FIRST
    // branded every view `[object TypedArray]` instead of `[object Uint8Array]`
    // — three records caught it. `Error.prototype` carries no tag at all, so
    // inheriting from it borrows nothing.
    if tag == "Object" && !has_error_data(h, v) {
        if let Some(ctor) = chain_tag_ctor(h, v) {
            return ctor;
        }
    }
    tag
}

fn b_setattr(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sval(&vm.pop());
    let recv = vm.pop();
    if let Err(e) = set_property(&recv, &name, val.clone()) {
        return abort(vm, e);
    }
    val
}

/// `NAMED_EVAL` — SetFunctionName (10.2.9) for a function whose name is only
/// known at run time, i.e. one defined under a COMPUTED key: `{ [k]: () => {} }`,
/// `class C { static [k] = function(){} }`.
///
/// The compiler emits this ONLY where the grammar says NamedEvaluation applies
/// (`IsAnonymousFunctionDefinition` is a syntactic predicate, not a runtime one:
/// `{ m: someAlreadyAnonymousFn }` must NOT be renamed), so the name is set
/// unconditionally here.
///
/// A symbol key becomes `[description]` per step 2 of SetFunctionName; `kind`
/// contributes the accessor prefix, so `{ get [k](){} }` is `get <key>`.
fn b_named_eval(vm: &mut VM, _: u8) -> Value {
    let func = vm.pop();
    let kind = vm.pop().to_int();
    let key = vm.pop();
    let key = sval(&key);
    // `@@sym:<id>` / `@@iterator` — an internal symbol key. Step 2: an empty
    // description gives the empty name, not `[undefined]`.
    let base = match with_host(|h| h.symbol_of_key(&key)) {
        Some(sym) => match with_host(|h| h.get(&sym).cloned()) {
            Some(JsObj::Symbol {
                desc: Some(desc), ..
            }) => format!("[{desc}]"),
            _ => String::new(),
        },
        None => key,
    };
    let name = match kind {
        host::member::GET => format!("get {base}"),
        host::member::SET => format!("set {base}"),
        _ => base,
    };
    with_host(|h| {
        let s = h.new_str(name);
        h.set_fn_prop(&func, "name", s);
    });
    func
}

/// `[[Set]]` reachable from `crate::proxy`'s no-trap forward, which has to land
/// on the same path a plain `o.k = v` takes.
pub fn set_property_pub(recv: &Value, name: &str, val: Value) -> Result<(), String> {
    set_property(recv, name, val)
}

/// An object's OWN property as `(value, writable, configurable, is_accessor)`,
/// or `None` when it has none. Reads through a Proxy's
/// `getOwnPropertyDescriptor` trap, so it answers for any object.
pub fn own_prop_facts(obj: &Value, key: &str) -> Option<(Value, bool, bool, bool)> {
    let k = with_host(|h| h.new_str(key.to_string()));
    let d = own_descriptor_pub(obj, k).ok()?;
    if matches!(d, Value::Undef) {
        return None;
    }
    let field = |n: &str| get_property(&d, n).unwrap_or(Value::Undef);
    // Each read is hoisted out of the `with_host` borrow: `get_property` takes
    // the host itself, so reading inside the closure double-borrows.
    let value = field("value");
    let writable = field("writable");
    let configurable = field("configurable");
    let truthy = |v: &Value| with_host(|h| h.truthy(v));
    let is_accessor = with_host(|h| host::lookup_chain(h, &d, "get").is_some());
    Some((value, truthy(&writable), truthy(&configurable), is_accessor))
}

/// `OrdinarySetWithOwnDescriptor` (10.1.9.2) with a receiver distinct from the
/// object the lookup started on — what `Reflect.set(t, k, v, receiver)` and a
/// proxy `set` trap forwarding to it both need.
///
/// The distinction that matters: an accessor found on `target`'s chain RUNS,
/// with `receiver` as `this`; a data property does not write to `target` at all
/// but is CREATED on `receiver` through its `[[DefineOwnProperty]]`. Routing
/// that second case back through `[[Set]]` made a proxy receiver re-enter its
/// own `set` trap forever — the trap body `Reflect.set(t, k, v, recv)` is the
/// documented way to forward a write, so the recursion hit every faithful
/// handler.
pub fn set_with_receiver(
    target: &Value,
    key: &str,
    val: Value,
    receiver: &Value,
) -> Result<bool, String> {
    // A proxy target answers through its own trap, which re-enters here with
    // whatever receiver the handler passes on.
    if crate::proxy::parts(target).is_some() {
        return crate::proxy::set(target, key, &val, receiver);
    }
    // An accessor anywhere on the target's chain wins, and sees `receiver`.
    if let Some((_, setter)) = with_host(|h| host::lookup_accessor(h, target, key)) {
        return match setter {
            Some(s) => {
                host::invoke(&s, vec![val], Some(receiver.clone()))?;
                Ok(true)
            }
            // A getter with no setter refuses the write rather than shadowing it.
            None => Ok(false),
        };
    }
    if !with_host(|h| h.can_write_prop(target, key)) {
        return Ok(false);
    }
    // Steps 3.b-3.d: only an object can receive the property, and its OWN
    // property decides — an accessor or a read-only slot refuses, and every
    // other case defines a plain data property.
    //
    // `is_object_like`, not a shape test: a string, a symbol and a bigint are
    // PRIMITIVES that ride as `Value::Obj` handles here, so the shape check
    // passed them through to `defineProperty`, which then threw `called on
    // non-object` where 10.1.9.2 step 3.b simply reports `false`.
    if !with_host(|h| is_object_like(h, receiver)) {
        return Ok(false);
    }
    if let Some((_, writable, _, is_accessor)) = own_prop_facts(receiver, key) {
        if is_accessor || !writable {
            return Ok(false);
        }
    }
    // Steps 3.d.iii and 3.e both DEFINE, they do not assign: a setter inherited
    // by the receiver must not run, and a proxy receiver must reach its
    // `defineProperty` trap rather than its `set` trap.
    let desc = with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        m.insert("value".into(), val);
        m.insert("writable".into(), Value::Bool(true));
        m.insert("enumerable".into(), Value::Bool(true));
        m.insert("configurable".into(), Value::Bool(true));
        h.new_object(m)
    });
    if crate::proxy::parts(receiver).is_some() {
        return crate::proxy::define_property(receiver, key, &desc);
    }
    let k = with_host(|h| h.new_str(key.to_string()));
    define_property_pub(receiver, k, desc)?;
    Ok(true)
}

/// Whether the first argument is a PRIMITIVE — including the three that ride as
/// heap handles, which a shape test misses.
fn is_primitive_arg(args: &[Value]) -> bool {
    let v = arg0(args);
    with_host(|h| host::is_primitive(h, &v))
}

/// The `TypeError` a refused write raises in strict code, worded as V8 does.
///
/// Adding a key to a non-extensible object reports differently from assigning
/// to a read-only one, and the object is named by its brand — `#<Object>` for a
/// plain object, `[object Array]` for an array.
fn write_refused(recv: &Value, name: &str) -> String {
    let extensible = with_host(|h| h.is_extensible(recv));
    // Which of the two messages applies turns on whether the key already
    // EXISTS. Every shape that keeps its own properties in the fn-prop side
    // table answered a blanket `true` here, so adding a key to a frozen
    // function reported "read only" where node reports "not extensible".
    let has_own = with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p.contains_key(name),
        Some(JsObj::Array(items)) => {
            name.parse::<usize>()
                .map(|i| i < items.len())
                .unwrap_or(false)
                || h.fn_prop(recv, name).is_some()
        }
        Some(JsObj::RegExp(_)) => name == "lastIndex" || h.fn_prop(recv, name).is_some(),
        _ => h.fn_prop(recv, name).is_some(),
    });
    if !extensible && !has_own {
        return host::type_error(&format!(
            "Cannot add property {name}, object is not extensible"
        ));
    }
    // The receiver renders the way every other brand-check message renders one
    // — `#<Object>`, `[object Array]`, `[object RegExp]`, `#<Map>`, `#<C>` for a
    // class instance, `Error: m` for an error. Only Array was special-cased, so
    // every other exotic reported `#<Object>`.
    host::type_error(&format!(
        "Cannot assign to read only property '{name}' of object '{}'",
        no_side_effects_string(recv)
    ))
}

fn set_property(recv: &Value, name: &str, val: Value) -> Result<(), String> {
    // 6.2.5.6 `PutValue` begins with `RequireObjectCoercible`: writing any
    // property of `undefined` or `null` throws, naming the key. Every such
    // write was silently discarded, so `u.x = 1` — the mirror of the single
    // most common runtime fault in JS, which the READ side already reports —
    // looked like it had succeeded.
    if with_host(|h| h.is_nullish(recv)) {
        return Err(host::type_error(&format!(
            "Cannot set properties of {} (setting '{name}')",
            with_host(|h| h.str_of(recv))
        )));
    }
    // A write to a PRIMITIVE receiver has no target — `ToObject` makes a
    // throwaway wrapper — so it is discarded in sloppy code and throws in
    // strict (10.1.9.2 / 6.2.5.6 again). The refusal was silent in both.
    // `is_primitive` rather than a shape test: a string, a symbol and a bigint
    // ride as `Value::Obj` handles in this host, so a check for a non-`Obj`
    // value caught only numbers and booleans.
    if with_host(|h| host::is_primitive(h, recv)) && with_host(|h| h.current_strict()) {
        return Err(host::type_error(&format!(
            "Cannot create property '{name}' on {} '{}'",
            with_host(|h| h.type_of(recv)),
            with_host(|h| h.str_of(recv))
        )));
    }
    // `[[PrivateSet]]` (7.3.32) refuses a receiver that carries no such private
    // element. The class's own field initializers install theirs directly
    // (`host::init_one_field`), so a declaration never reaches this check.
    if name.starts_with('#') && !with_host(|h| h.has_private(recv, name)) {
        return Err(private_brand_message(name, true));
    }
    // `[[Set]]` on a Proxy: the handler's `set` trap, or a forward to the target.
    if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
        // A `set` trap that returns falsish REFUSED the write: silent in sloppy
        // code, a TypeError in strict, exactly as an ordinary refused write is.
        if crate::proxy::set(recv, name, &val, recv)? {
            return Ok(());
        }
        if with_host(|h| h.current_strict()) {
            return Err(host::type_error(&format!(
                "'set' on proxy: trap returned falsish for property '{name}'"
            )));
        }
        return Ok(());
    }
    // `globalThis.x = 1` creates a real global binding, so the bare `x` reads it
    // back. Writing only the own property left the two views disagreeing:
    // `globalThis.zz` was 7 while `zz` was still a `ReferenceError`.
    if with_host(|h| h.is_global_object(recv)) && !name.starts_with("@@") {
        with_host(|h| h.set_name(name, val.clone()));
    }
    // `obj.__proto__ = p` re-links the prototype — but only for the two values
    // the Annex B setter accepts, an Object or `null`. Everything else is a
    // silent no-op in Node (`o.__proto__ = 5` leaves `Object.getPrototypeOf(o)`
    // untouched and creates no own key), and a null-prototype object inherits
    // no such setter at all, so there the assignment is an ORDINARY own
    // property write. Re-linking unconditionally made `o.__proto__ = 5` set the
    // prototype to the number 5.
    if name == "__proto__" && with_host(|h| h.kind_of(recv)) == Some(ObjKind::Object) {
        if with_host(|h| h.has_null_proto(recv)) {
            // falls through to the ordinary own-property write below
        } else {
            let assignable =
                with_host(|h| h.is_null(&val) || matches!(h.kind_of(&val), Some(ObjKind::Object)));
            if assignable {
                // The `__proto__` setter runs `[[SetPrototypeOf]]`, which a
                // NON-EXTENSIBLE object refuses — and unlike an ordinary
                // refused write, the setter throws in sloppy code too. It was
                // rewriting the link of a frozen object.
                if would_cycle(recv, &val) {
                    return Err(host::type_error("Cyclic __proto__ value"));
                }
                if !with_host(|h| h.is_extensible(recv)) && !same_prototype(recv, &val) {
                    return Err(host::type_error(&format!(
                        "{} is not extensible",
                        no_side_effects_string(recv)
                    )));
                }
                with_host(|h| h.set_proto(recv, val));
            }
            return Ok(());
        }
    }
    // Every environment value is a STRING. `process.env.PORT = 8080` stores
    // "8080", so `process.env.PORT + 1` concatenates the way it does in a real
    // process; storing the number made it add instead.
    if !name.starts_with("@@")
        && with_host(
            |h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@envObject")),
        )
    {
        let text = with_host(|h| h.str_of(&val));
        // Write THROUGH to the real environment as well. `process.env` is not a
        // private map: node applies the change to the process, so a child
        // spawned afterwards inherits it. Keeping it only in the JS object meant
        // `process.env.NODE_ENV = 'production'` was invisible to every
        // `spawnSync`/`execSync` that followed.
        std::env::set_var(name, &text);
        let sv = with_host(|h| h.new_str(text));
        with_host(|h| {
            if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                p.insert(name.to_string(), sv);
            }
        });
        return Ok(());
    }
    // Assigning `e.stack` wins permanently: drop the not-yet-formatted marker so
    // no later read re-derives a header over the top of the assigned value.
    if name == "stack" {
        with_host(|h| {
            if let Some(JsObj::Object(p)) = h.get_mut(recv) {
                p.shift_remove("@@stackRaw");
            }
        });
    }
    // An inherited/own setter accessor intercepts the write. This is checked
    // BEFORE the writable test because 10.1.9.2 branches on the descriptor
    // kind first: `writable` is a data-property attribute and means nothing on
    // an accessor, where the setter alone decides. Testing it first meant an
    // accessor defined through `Object.defineProperty` — which leaves
    // `writable` false, having no such field — silently swallowed every write
    // instead of calling its setter, so the standard clone idiom
    // `Object.create(proto, Object.getOwnPropertyDescriptors(src))` produced an
    // object whose setters did nothing. An accessor from an object literal
    // carries all-true attributes, which is why only the former broke.
    if let Some((getter, setter)) = with_host(|h| host::lookup_accessor(h, recv, name)) {
        if let Some(setter) = setter {
            let _ = host::invoke(&setter, vec![val], Some(recv.clone()));
            return Ok(());
        }
        // Only a getter: the write is refused — silent in sloppy mode, a
        // TypeError in strict code. The `return` above matters, since a
        // successful setter call must not fall into this.
        let _ = getter;
        if with_host(|h| h.current_strict()) {
            return Err(host::type_error(&format!(
                "Cannot set property {name} of #<Object> which has only a getter"
            )));
        }
        return Ok(());
    }
    // A non-writable property, or a new key on a non-extensible object, refuses
    // the write. In SLOPPY mode that is silent; in strict code it is a
    // TypeError, and the ASSIGNMENT SITE decides which — not the object. Every
    // refusal used to be silent, so `'use strict'` did not catch a write to a
    // frozen object, which is most of the reason to freeze one.
    if !with_host(|h| h.can_write_prop(recv, name)) {
        if with_host(|h| h.current_strict()) {
            return Err(write_refused(recv, name));
        }
        return Ok(());
    }
    // Writing `name`/`prototype`/statics on a function value.
    if matches!(
        with_host(|h| h.kind_of(recv)),
        Some(ObjKind::Func) | Some(ObjKind::Class)
    ) {
        with_host(|h| h.set_fn_prop(recv, name, val));
        return Ok(());
    }
    // Writing a static onto a builtin namespace/ctor (`Error.prepareStackTrace`).
    // Each bare reference is a fresh `Builtin` handle, so route to the stable
    // per-namespace side table rather than the per-index `fn_props`.
    if let Some(ns) = peek(recv, |o| match o {
        JsObj::Builtin(ns) => Some(ns.clone()),
        _ => None,
    }) {
        // `process.exitCode` is an accessor in Node, not a data property: the
        // setter validates and stores the code the process will finally exit
        // with. Landing it in the generic static table made it a write-only
        // decoration — `process.exitCode = 3` read back as 3 and the process
        // still exited 0.
        if ns == "process" && name == "exitCode" {
            return crate::stdlib::process::set_exit_code(&val);
        }
        with_host(|h| h.set_builtin_static(&ns, name, val));
        return Ok(());
    }
    // A write onto a REAL intrinsic prototype object (`Object.prototype`,
    // `String.prototype`, `TypeError.prototype`) is mirrored into the
    // per-namespace side table as well as the object's own map. Instances are
    // not linked to these objects by `proto_of` — the chain walk never reaches
    // them — so the mirror is what makes `String.prototype.pad = f` visible as
    // `"x".pad`. The own-map write below still happens, so reading the
    // prototype itself and enumerating it keep working unchanged.
    if let Some(ns) = with_host(|h| {
        h.intrinsic_proto_ctor(recv)
            .map(str::to_string)
            .or_else(|| (h.object_proto() == *recv).then(|| "Object".to_string()))
    }) {
        with_host(|h| h.set_builtin_static(&format!("{ns}.prototype"), name, val.clone()));
    }
    // `re.lastIndex = n` on a RegExp advances/resets its match cursor. The
    // writability check above already refused it on a FROZEN regexp, which it
    // could only do once `integrity_keys` learned that `lastIndex` is an own
    // property.
    if name == "lastIndex" {
        if let Some(n) = with_host(|h| match h.get(recv) {
            Some(JsObj::RegExp(_)) => Some(h.to_number(&val)),
            _ => None,
        }) {
            with_host(|h| {
                if let Some(JsObj::RegExp(r)) = h.get_mut(recv) {
                    r.last_index = if n.is_finite() && n >= 0.0 {
                        crate::utf16::U16Index::new(n as usize)
                    } else {
                        crate::utf16::U16Index::ZERO
                    };
                }
            });
            return Ok(());
        }
    }
    // An `arguments` object is an ORDINARY object with a `length` data property,
    // not an array: a write PAST the end adds an index and leaves `length`
    // alone. The array backing grew it instead, so `f(1)` followed by
    // `arguments[1] = 9` reported `arguments.length` as 2.
    if let Ok(i) = name.parse::<usize>() {
        if is_arguments(recv) && i >= array_len(recv) {
            with_host(|h| h.set_fn_prop(recv, name, val));
            return Ok(());
        }
    }
    // Typed-array element write (`ta[i] = v`): coerce + store into `@@elems`.
    if !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit()) {
        let is_ta = crate::stdlib::native_tag(recv).as_deref() == Some("TypedArray");
        if is_ta && crate::stdlib::typedarray::elem_set(recv, name, &val)? {
            return Ok(());
        }
        // An index write to a view over a DETACHED buffer is DROPPED. Falling
        // through would store it as an ordinary own property, which then showed
        // up in `getOwnPropertyDescriptor` over a buffer with no bytes.
        if is_ta && crate::stdlib::typedarray::view_detached(recv) {
            return Ok(());
        }
        // `buf[i] = n` writes through to the Buffer's hidden byte array.
        if crate::stdlib::buffer::byte_set(recv, name, &val) {
            return Ok(());
        }
    }
    // Any own property on an exotic with no property map of its own. This sits
    // BELOW the exotic-specific writes above, so a RegExp's `lastIndex` still
    // moves its match cursor rather than being shadowed by a side-table entry.
    if uses_side_table(recv) {
        with_host(|h| h.set_fn_prop(recv, name, val));
        return Ok(());
    }
    // An arbitrary own prop on an array (e.g. exec-result `.index`/`.input`).
    if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Array)
        && name != "length"
        && name.parse::<usize>().is_err()
    {
        with_host(|h| h.set_fn_prop(recv, name, val));
        return Ok(());
    }
    // `arr.length = n` (10.4.2.4 `ArraySetLength`) validates BEFORE it resizes,
    // and does so outside the host borrow because `ToNumber` may run a user
    // `valueOf`. An invalid length throws instead of being silently coerced to 0.
    let new_len = if name == "length" && with_host(|h| h.kind_of(recv)) == Some(ObjKind::Array) {
        let want = host::to_array_length(&val)?;
        // 10.4.2.4 steps 15-17: shrinking deletes from the END downwards and
        // STOPS at the first element that cannot be deleted, leaving the length
        // just past it. Truncating regardless discarded a non-configurable
        // element and reported a length node would not have accepted.
        let floor = with_host(|h| {
            let old = match h.get(recv) {
                Some(JsObj::Array(items)) => items.len(),
                _ => 0,
            };
            let mut stop = want;
            for i in (want..old).rev() {
                if !h.prop_attrs(recv, &i.to_string()).configurable {
                    stop = i + 1;
                    break;
                }
            }
            stop
        });
        Some(floor.max(want))
    } else {
        None
    };
    with_host(|h| match h.get_mut(recv) {
        Some(JsObj::Object(props)) => {
            // Adding a *new* array-index key must re-place it into ascending
            // integer-key order (updating an existing key keeps its position).
            let is_new = !props.contains_key(name);
            props.insert(name.to_string(), val);
            if is_new && host::array_index(name).is_some() {
                host::canonicalize_own_keys(props);
            }
        }
        Some(JsObj::Array(items)) => {
            if let Some(n) = new_len {
                // Growing `length` appends HOLES (`a=[1]; a.length=3` still has
                // just the one own key); shrinking drops any hole past the end.
                let old = items.len();
                items.resize(n, Value::Undef);
                if n > old {
                    h.mark_hole_range(recv, old..n);
                } else {
                    h.truncate_holes(recv, n);
                }
            } else if let Ok(i) = name.parse::<usize>() {
                // A write PAST the end leaves the skipped positions elided.
                let old = items.len();
                if i >= old {
                    items.resize(i + 1, Value::Undef);
                }
                items[i] = val;
                if i > old {
                    h.mark_hole_range(recv, old..i);
                }
                // …and the written index itself is no longer one. This is the
                // single site that keeps a hole record from outliving the
                // elision it describes: every array element write in the
                // language reaches it.
                h.clear_hole(recv, i);
            }
        }
        _ => {}
    });
    Ok(())
}

fn b_getitem(vm: &mut VM, _: u8) -> Value {
    let idx = vm.pop();
    let recv = vm.pop();
    let key = match host::to_property_key(&idx) {
        Ok(k) => k,
        Err(e) => return abort(vm, e),
    };
    match get_property(&recv, &key) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}

fn b_setitem(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let idx = vm.pop();
    let recv = vm.pop();
    let key = match host::to_property_key(&idx) {
        Ok(k) => k,
        Err(e) => return abort(vm, e),
    };
    if let Err(e) = set_property(&recv, &key, val.clone()) {
        return abort(vm, e);
    }
    val
}

/// `[[Delete]]` (10.1.10) for an already-resolved property key: the one place
/// `delete o[k]`, `delete o.k` and `Reflect.deleteProperty` all go through, so
/// the three cannot drift. Reports `false` for a non-configurable property
/// (sloppy mode ignores the failure rather than throwing) and `true` otherwise,
/// which is also what deleting an absent key reports.
pub fn delete_property(recv: &Value, key: &str) -> Result<bool, String> {
    // 13.5.1.2 step 5 runs `ToObject` on the base, which a nullish one refuses.
    // `delete u.x` reported success instead.
    if with_host(|h| h.is_nullish(recv)) {
        return Err(host::type_error(
            "Cannot convert undefined or null to object",
        ));
    }
    // `[[Delete]]` on a Proxy runs the handler's `deleteProperty` trap, which may
    // throw — the reason this reports a `Result` rather than a bare `bool`.
    if let Some(b) = crate::proxy::delete(recv, key)? {
        return Ok(b);
    }
    // `delete globalThis.x` removes a global a script created. It lives in the
    // globals map, not the object's property map, so the ordinary path reported
    // success and removed nothing — the binding stayed readable afterwards.
    if with_host(|h| h.is_global_object(recv)) && with_host(|h| h.remove_global(key)) {
        return Ok(true);
    }
    // `delete require.cache[id]` drops the module so the next `require` of that
    // file runs it again — the whole point of exposing the cache.
    if peek(recv, |o| match o {
        JsObj::Builtin(ns) => Some(ns == REQUIRE_CACHE),
        _ => None,
    }) == Some(true)
    {
        return Ok(crate::module::cache_delete(key));
    }
    // `delete process.env.X` unsets the variable in the PROCESS, not just in the
    // JS view, so a child spawned afterwards no longer sees it.
    if !key.starts_with("@@")
        && with_host(
            |h| matches!(h.get(recv), Some(JsObj::Object(p)) if p.contains_key("@@envObject")),
        )
    {
        std::env::remove_var(key);
    }
    // A member of a builtin NAMESPACE (`Math.PI`, `Number.MAX_VALUE`,
    // `Object.prototype`) is non-configurable when it is a constant or a
    // constructor's `prototype`, and `delete` of one answers false without
    // removing anything. There is no property map behind a namespace, so the
    // ordinary attribute lookup below cannot tell — it reported success for
    // every one of them.
    // A REAL intrinsic prototype object carries the write in its own map AND in
    // the side table the instance read consults, so the delete has to clear
    // both. Clearing only the map left `Object.prototype.patch` deleted as far
    // as the prototype was concerned and still inherited by every object.
    if let Some(ns) = with_host(|h| {
        h.intrinsic_proto_ctor(recv)
            .map(str::to_string)
            .or_else(|| (h.object_proto() == *recv).then(|| "Object".to_string()))
    }) {
        with_host(|h| h.remove_builtin_static(&format!("{ns}.prototype"), key));
    }
    if let Some(ns) = peek(recv, |o| match o {
        JsObj::Builtin(ns) => Some(ns.clone()),
        _ => None,
    }) {
        // A script-assigned static is an ordinary configurable property and is
        // removed from the side table the assignment landed in. Falling through
        // to the attribute check below answered true and deleted nothing, so a
        // patch survived its own `delete`.
        if with_host(|h| h.remove_builtin_static(&ns, key)) {
            return Ok(true);
        }
        if ns != REQUIRE_CACHE && !builtin_member_configurable(&ns, key) {
            return Ok(false);
        }
    }
    if !with_host(|h| h.prop_attrs(recv, key).configurable) {
        return Ok(false);
    }
    // An accessor lives in its own table, not the property map, so removing it
    // has to be explicit — otherwise `delete` reported success while the getter
    // kept answering and `in` kept reporting the key.
    if with_host(|h| h.own_accessor(recv, key).is_some()) {
        with_host(|h| h.remove_accessor(recv, key));
        return Ok(true);
    }
    with_host(|h| {
        let index = key.parse::<usize>();
        match h.get_mut(recv) {
            Some(JsObj::Object(props)) => {
                props.shift_remove(key);
                return;
            }
            Some(JsObj::Array(items)) => {
                if let Ok(i) = index {
                    if i < items.len() {
                        // `delete a[i]` punches a HOLE: the length is unchanged
                        // but the index stops being an own property.
                        items[i] = Value::Undef;
                        h.mark_hole(recv, i);
                    }
                    return;
                }
            }
            _ => {}
        }
        // A non-index key on an array (`arr.foo`, `arr[sym]`), or any own key on
        // a function/class, is an ordinary own property kept in the side table.
        h.remove_fn_prop(recv, key);
    });
    Ok(true)
}

fn b_delitem(vm: &mut VM, _: u8) -> Value {
    let strict = vm.pop();
    let idx = vm.pop();
    let recv = vm.pop();
    // `delete o[k]` keys through ToPropertyKey (7.1.19), exactly as the read and
    // the write do: `String(k)` would turn a Symbol into its `Symbol(desc)`
    // description and delete a key nothing ever wrote.
    let key = match host::to_property_key(&idx) {
        Ok(k) => k,
        Err(e) => return abort(vm, e),
    };
    match delete_property(&recv, &key) {
        Ok(false) if with_host(|h| h.truthy(&strict)) => {
            abort(vm, refused_delete_error(&recv, &key))
        }
        Ok(b) => Value::Bool(b),
        Err(e) => abort(vm, e),
    }
}

fn b_delprop_name(vm: &mut VM, _: u8) -> Value {
    let strict = vm.pop();
    let name = sval(&vm.pop());
    let recv = vm.pop();
    match delete_property(&recv, &name) {
        Ok(false) if with_host(|h| h.truthy(&strict)) => {
            abort(vm, refused_delete_error(&recv, &name))
        }
        Ok(b) => Value::Bool(b),
        Err(e) => abort(vm, e),
    }
}

/// The TypeError a STRICT `delete` of a non-configurable property raises. The
/// receiver renders the way every other brand-check message renders one.
fn refused_delete_error(recv: &Value, key: &str) -> String {
    // A PROXY names the trap that refused. Only the `delete` OPERATOR reports
    // it; `Reflect.deleteProperty` answers `false`, which is why this lives
    // here rather than in the shared `[[Delete]]`.
    if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
        return host::type_error(&format!(
            "'deleteProperty' on proxy: trap returned falsish for property '{key}'"
        ));
    }
    // A non-callable builtin NAMESPACE renders as a plain object here — node
    // reports `#<Object>` for `Math`, not its `[object Math]` brand.
    let shown = match peek(recv, |o| match o {
        JsObj::Builtin(ns) => Some(ns.clone()),
        _ => None,
    }) {
        Some(ns) if !host::builtin_is_callable(&ns) => "#<Object>".to_string(),
        _ => no_side_effects_string(recv),
    };
    host::type_error(&format!("Cannot delete property '{key}' of {shown}"))
}

// ── constructors ──────────────────────────────────────────────────────────────

fn b_mkstr(vm: &mut VM, argc: u8) -> Value {
    let parts = pop_n(vm, argc as usize);
    let s: String = with_host(|h| parts.iter().map(|p| h.str_of(p)).collect());
    with_host(|h| h.new_str(s))
}

fn b_mkarr(vm: &mut VM, argc: u8) -> Value {
    let items = pop_n(vm, argc as usize);
    with_host(|h| h.new_array(items))
}

/// `MARK_HOLE [arr, index]`: record `arr[index]` as an ELIDED element. Emitted
/// only for an array literal that actually contains an elision, so a dense
/// literal costs nothing. Returns `undefined`; the array stays on the stack
/// underneath (the compiler `Dup`s it).
fn b_mark_hole(vm: &mut VM, _: u8) -> Value {
    let idx = vm.pop();
    let arr = vm.pop();
    let i = match idx {
        Value::Int(i) if i >= 0 => i as usize,
        _ => return Value::Undef,
    };
    with_host(|h| h.mark_hole(&arr, i));
    Value::Undef
}

fn b_mkobj(vm: &mut VM, argc: u8) -> Value {
    let flat = pop_n(vm, argc as usize);
    let mut props: IndexMap<String, Value> = IndexMap::new();
    // A literal `__proto__: x` key sets the object's prototype (not an own prop).
    let mut proto_override: Option<Value> = None;
    let mut method_keys: Vec<String> = Vec::new();
    let mut i = 0;
    while i + 2 < flat.len() || (i + 2 == flat.len() && flat.len() % 3 == 0 && i < flat.len()) {
        if i + 2 >= flat.len() {
            break;
        }
        // Tag 2: an ACCESSOR's position. An accessor lives in its own table, so
        // the literal reserves its slot here with the `@@ord:` marker key that
        // `own_enum_data_keys` resolves back — otherwise `{ get g(){}, d: 2 }`
        // enumerated `d, g`, because `DEF_ACCESSOR` runs after `MKOBJ` and its
        // marker landed at the end.
        if matches!(flat[i], Value::Int(2)) {
            let key = with_host(|h| h.str_of(&flat[i + 1]));
            props
                .entry(format!("{}{key}", host::ORD_MARKER))
                .or_insert(Value::Undef);
            i += 3;
            continue;
        }
        // Tag 3: a METHOD DEFINITION — an ordinary property whose key is also
        // recorded so the literal can become its `[[HomeObject]]` below.
        if matches!(flat[i], Value::Int(3)) {
            let key = with_host(|h| h.str_of(&flat[i + 1]));
            method_keys.push(key.clone());
            props.insert(key, flat[i + 2].clone());
            i += 3;
            continue;
        }
        let spread = matches!(flat[i], Value::Int(1));
        if spread {
            let src = flat[i + 1].clone();
            // A STRING source spreads its index properties (`{..."ab"}` is
            // `{0:'a',1:'b'}`): CopyDataProperties (7.3.25) calls ToObject, and a
            // String exotic object owns one enumerable property per UTF-16 code
            // UNIT (10.4.3). `own_enum_entries_deep` only walks heap objects, so
            // a string source contributed nothing and `{..."ab"}` was `{}`.
            // Every other primitive (number/boolean/symbol) boxes to an object
            // with no own enumerable properties, and null/undefined are ignored,
            // so those correctly stay no-ops on the path below.
            if let Some(s) = with_host(|h| h.as_str(&src)) {
                for idx in 0..crate::utf16::len(&s) {
                    if let Ok(ch) = get_property(&src, &idx.to_string()) {
                        props.insert(idx.to_string(), ch);
                    }
                }
                i += 3;
                continue;
            }
            // Object spread copies own *enumerable* properties only — never the
            // hidden `@@…` slots (copying `@@native` used to turn `{...buf}`
            // into something that still claimed to be a Buffer) and never a
            // property a descriptor marked non-enumerable.
            // A getter that throws during spread propagates as a thrown value,
            // which in the VM means aborting the frame.
            let entries = match host::own_enum_entries_deep(&src) {
                Ok(e) => e,
                Err(e) => return abort(vm, e),
            };
            for (k, v) in entries {
                props.insert(k, v);
            }
            // `CopyDataProperties` (7.3.25) copies own enumerable SYMBOL keys
            // too — only `Object.keys`/`for-in`/`JSON.stringify` skip them.
            for (k, v) in with_host(|h| h.own_symbol_entries(&src)) {
                props.insert(k, v);
            }
        } else {
            let key = with_host(|h| h.str_of(&flat[i + 1]));
            if key == "__proto__" {
                proto_override = Some(flat[i + 2].clone());
            } else {
                props.insert(key, flat[i + 2].clone());
            }
        }
        i += 3;
    }
    with_host(|h| {
        let o = h.new_object(props);
        if let Some(p) = proto_override {
            if matches!(p, Value::Obj(_)) {
                h.set_proto(&o, p);
            }
        }
        // A method DEFINED here takes the literal as its `[[HomeObject]]`, which
        // is what `super` inside it resolves through. The home object is fixed
        // at definition, so a method that merely arrives as a value
        // (`{ m: other.m }`) keeps the one it was defined with — stamping every
        // method-valued property instead rebound the original and changed what
        // IT resolved.
        for key in &method_keys {
            let m = match h.get(&o) {
                Some(JsObj::Object(p)) => p.get(key).cloned(),
                _ => None,
            };
            if let Some(m) = m {
                if let Some(JsObj::Func(f)) = h.get_mut(&m) {
                    f.home_object = Some(o.clone());
                }
            }
        }
        o
    })
}

fn b_mkfunc(vm: &mut VM, _: u8) -> Value {
    let def_id = match vm.pop() {
        Value::Int(n) => n as usize,
        Value::Float(f) => f as usize,
        _ => return abort(vm, "internal: MKFUNC id".into()),
    };
    let (is_arrow, self_name) = with_host(|h| match h.funcs.get(def_id) {
        Some(d) => (
            d.is_arrow,
            (d.self_name && !d.name.is_empty()).then(|| d.name.clone()),
        ),
        None => (false, None),
    });
    with_host(|h| {
        let mut env = h.current_env_capture();
        let this = h.current_this();
        // An arrow has no `super` of its own: it uses the enclosing METHOD's,
        // exactly as it uses the enclosing `this`. Nothing was captured, so
        // `super.m()` inside an arrow reported the method missing — in a class
        // method as well as an object literal.
        let (home_class, home_static, home_object) = if is_arrow {
            h.current_home()
        } else {
            (None, false, None)
        };
        // A named function expression closes over an extra scope holding its own
        // name, so the body can recurse through it (`function f(){ … f() … }`)
        // independently of whatever the outer binding is later set to.
        if self_name.is_some() {
            env = host::child_env(env);
        }
        let f = h.alloc(JsObj::Func(FuncVal {
            def_id,
            env: Some(env.clone()),
            this,
            is_arrow,
            home_class,
            home_static,
            home_object,
        }));
        if let Some(n) = self_name {
            env.borrow_mut().vars.insert(n, f.clone());
        }
        f
    })
}

// ── truthiness / coercion / equality ──────────────────────────────────────────

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

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

fn b_tostr(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    // ToString with user-`toString`/`valueOf` dispatch (template interpolation,
    // `String(x)`, object keys).
    match host::to_string_value(&v) {
        Ok(s) => s,
        Err(e) => abort(vm, e),
    }
}

fn b_typeof(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| {
        let t = h.type_of(&v);
        h.new_str(t)
    })
}

/// `typeof <bare ident>`: read the name like `b_getlocal` but return "undefined"
/// (never a ReferenceError) when the name is unbound — JS `typeof` semantics.
fn b_typeof_name(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    // `typeof` does NOT excuse the temporal dead zone: it answers "undefined"
    // for an UNBOUND name, but a `let` above its declaration is bound and
    // throws. Reading the marker's type answered "function".
    if with_host(|h| h.is_tdz_global(&name) && h.read_name(&name).is_none()) {
        return abort(vm, host::tdz_error(&name));
    }
    if let Some(v) = with_host(|h| h.read_name(&name)) {
        if with_host(|h| h.is_tdz(&v)) {
            return abort(vm, host::tdz_error(&name));
        }
    }
    // Bound name (user variable) → typeof its value.
    if let Some(v) = with_host(|h| h.read_name(&name)) {
        return with_host(|h| {
            let t = h.type_of(&v);
            h.new_str(t)
        });
    }
    // Lazily-bound globals mirror `b_getlocal`: resolve to the same value it
    // would produce, then take its type (so object-namespaces like `console`/
    // `Math`/`JSON`/`process` report "object", constructors report "function").
    let t = match name.as_str() {
        "undefined" => "undefined".to_string(),
        "NaN" | "Infinity" => "number".to_string(),
        "globalThis" | "global" => "object".to_string(),
        n if is_namespace(n) || is_known_builtin(n) => {
            let v = with_host(|h| h.alloc(JsObj::Builtin(name.clone())));
            with_host(|h| h.type_of(&v)).to_string()
        }
        _ => "undefined".to_string(), // genuinely unbound → JS returns "undefined"
    };
    with_host(|h| h.new_str(t))
}

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

fn b_loose_eq(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    // Abstract Equality steps 10-11 (7.2.15): object ⇄ primitive converts the
    // object with `ToPrimitive` — a JS `valueOf`/`Symbol.toPrimitive` call, so it
    // runs before the host borrow. Object ⇄ object stays a reference check.
    let (a, b) = match with_host(|h| (host::is_primitive(h, &a), host::is_primitive(h, &b))) {
        (false, true) if coerces_against_object(&b) => match host::to_primitive(&a, "default") {
            Ok(p) => (p, b),
            Err(e) => return abort(vm, e),
        },
        (true, false) if coerces_against_object(&a) => match host::to_primitive(&b, "default") {
            Ok(p) => (a, p),
            Err(e) => return abort(vm, e),
        },
        _ => (a, b),
    };
    Value::Bool(with_host(|h| h.loose_eq(&a, &b)))
}

fn b_instanceof(vm: &mut VM, _: u8) -> Value {
    let ctor = vm.pop();
    let obj = vm.pop();
    match host::instance_of(&obj, &ctor) {
        Ok(b) => Value::Bool(b),
        Err(e) => abort(vm, e),
    }
}

// ── bitwise / unary ───────────────────────────────────────────────────────────

fn b_binop(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let tag = match vm.pop() {
        Value::Int(n) => n,
        _ => 0,
    };
    // Both operands are ToPrimitive-d with the number hint before ToInt32
    // (ECMA-262 13.12.1), which has to happen outside the host borrow.
    let r = host::to_primitive(&a, "number")
        .and_then(|a| host::to_primitive(&b, "number").map(|b| (a, b)))
        .and_then(|(a, b)| with_host(|h| h.bitwise(tag, &a, &b)));
    finish(vm, r)
}

fn b_unary(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    let tag = match vm.pop() {
        Value::Int(n) => n,
        _ => 0,
    };
    // Unary `+`/`~` on a BigInt: `+` is a hard TypeError in JS; `~x` is `-x - 1`
    // computed in arbitrary precision.
    if with_host(|h| h.is_bigint_val(&v)) {
        return match tag {
            host::unop::POS => abort(
                vm,
                host::type_error("Cannot convert a BigInt value to a number"),
            ),
            host::unop::BITNOT => {
                let b = with_host(|h| h.as_bigint(&v)).unwrap();
                let r = -(b + num_bigint::BigInt::from(1));
                with_host(|h| h.new_bigint(r))
            }
            _ => Value::Undef,
        };
    }
    // `ToNumber` outside the host borrow: an object operand's `valueOf` /
    // `Symbol.toPrimitive` is a JS call, so it cannot run under `with_host`.
    let n = match host::to_number_value(&v) {
        Ok(n) => n,
        Err(e) => return abort(vm, e),
    };
    match tag {
        host::unop::POS => Value::Float(n),
        host::unop::BITNOT => {
            let i = if n.is_finite() {
                n.trunc() as i64 as i32
            } else {
                0
            };
            Value::Float(!i as f64)
        }
        _ => Value::Undef,
    }
}

// ── membership ────────────────────────────────────────────────────────────────

fn b_contains(vm: &mut VM, _: u8) -> Value {
    let container = vm.pop();
    let key = vm.pop();
    // `x in y` requires y to be an object. V8 names both operands:
    // `Cannot use 'in' operator to search for 'a' in 5`.
    // A heap-backed PRIMITIVE — a string, a symbol, a bigint — is a
    // `Value::Obj` in this host but is not an object, so the shape test alone
    // let `'length' in 'ab'` and `'description' in Symbol('x')` answer `true`
    // where node throws. `is_primitive` is the same predicate `ToObject` and
    // `typeof` use, so the three cannot disagree about what an object is.
    if !matches!(container, Value::Obj(_)) || with_host(|h| host::is_primitive(h, &container)) {
        let (k, c) = with_host(|h| (h.property_key(&key), h.str_of(&container)));
        return abort(
            vm,
            host::type_error(&format!(
                "Cannot use 'in' operator to search for '{k}' in {c}"
            )),
        );
    }
    let k = match host::to_property_key(&key) {
        Ok(k) => k,
        Err(e) => return abort(vm, e),
    };
    match has_property(&container, &k) {
        Ok(b) => Value::Bool(b),
        Err(e) => abort(vm, e),
    }
}

// ── control ───────────────────────────────────────────────────────────────────

fn b_sig_return(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| h.signal = Some(host::Signal::Return(v.clone())));
    vm.ip = vm.chunk.ops.len();
    v
}

/// `break [label]` whose target loop lives in an enclosing chunk (the statement is
/// inside a `try` block, which the host runs as its own chunk). Raise the signal
/// and halt this chunk; `SIG_UNWIND` after the `TRY` op re-dispatches it.
fn b_sig_break(vm: &mut VM, _: u8) -> Value {
    let label = sval(&vm.pop());
    let label = (!label.is_empty()).then_some(label);
    with_host(|h| h.signal = Some(host::Signal::Break(label)));
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// `continue [label]` out of a `try` block — see [`b_sig_break`].
fn b_sig_continue(vm: &mut VM, _: u8) -> Value {
    let label = sval(&vm.pop());
    let label = (!label.is_empty()).then_some(label);
    with_host(|h| h.signal = Some(host::Signal::Continue(label)));
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// Dispatch a pending control signal at the instruction after a `TRY`. `tag`
/// describes what the `try` is nested in (see [`host::unwind`]):
///
/// * no signal → `NONE`, execution continues normally;
/// * `Return`, or no enclosing loop in this chunk → halt the chunk so the signal
///   keeps travelling outward;
/// * `break`/`continue` targeting the enclosing loop → consume it and report
///   `BREAK`/`CONTINUE` so the compiler-emitted jump lands on the loop's exit /
///   continue target;
/// * a LABELED `break`/`continue` for some outer loop → report `BREAK` but leave
///   the signal pending, so leaving this loop re-dispatches it one level out.
fn b_sig_unwind(vm: &mut VM, _: u8) -> Value {
    let cont_tag = sval(&vm.pop());
    let brk_tag = sval(&vm.pop());
    let sig = match with_host(|h| h.signal.clone()) {
        Some(s) => s,
        None => return Value::Int(host::unwind::NONE),
    };
    // Nothing in this chunk can catch a `break`: halt so the signal keeps going.
    let propagate = |vm: &mut VM| {
        vm.ip = vm.chunk.ops.len();
        Value::Int(host::unwind::NONE)
    };
    match &sig {
        host::Signal::Return(_) => propagate(vm),
        host::Signal::Break(label) => {
            if brk_tag == host::unwind::NO_LOOP {
                return propagate(vm);
            }
            let mine = match label {
                None => true, // unlabeled: always the innermost enclosing context
                Some(l) => brk_tag == *l,
            };
            if mine {
                with_host(|h| h.signal = None);
            }
            // Not ours: still leave this context by its break exit, keeping the
            // signal pending for the next dispatch point one level out.
            Value::Int(host::unwind::BREAK)
        }
        host::Signal::Continue(label) => {
            let mine = match label {
                // Unlabeled `continue` binds to the innermost continue-catching
                // loop — which a `switch` between here and it is NOT.
                None => cont_tag != host::unwind::NO_LOOP,
                Some(l) => cont_tag == *l,
            };
            if mine {
                with_host(|h| h.signal = None);
                return Value::Int(host::unwind::CONTINUE);
            }
            if brk_tag == host::unwind::NO_LOOP {
                return propagate(vm);
            }
            // The target loop is further out: exit the innermost context here and
            // re-dispatch there.
            Value::Int(host::unwind::BREAK)
        }
    }
}

fn b_throw(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    let msg = with_host(|h| {
        h.exc = Some(v.clone());
        // Prefer an error object's message for the top-level report.
        error_display(h, &v)
    });
    abort(vm, msg)
}

fn error_display(h: &host::JsHost, v: &Value) -> String {
    if let Some(JsObj::Object(props)) = h.get(v) {
        let name = props
            .get("name")
            .map(|x| h.str_of(x))
            .unwrap_or_else(|| "Error".into());
        if let Some(m) = props.get("message") {
            return format!("Uncaught {name}: {}", h.str_of(m));
        }
    }
    format!("Uncaught {}", h.str_of(v))
}

fn b_try(vm: &mut VM, _: u8) -> Value {
    let id = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => return abort(vm, "internal: TRY id".into()),
    };
    // Shape only. Running a `try` used to clone the whole `TryDef` — its block,
    // its handler and its finalizer bytecode — every time control entered it,
    // which for a `try` inside a loop is once per iteration.
    let (has_handler, catch_bind, has_finalizer) = match with_host(|h| h.try_shape(id)) {
        Some(t) => t,
        None => return abort(vm, "internal: unknown try id".into()),
    };
    let mut pending: Option<String> = None;
    // Each sub-block runs as its own chunk on THIS frame, so a throw part-way
    // through can leave block scopes open. Snapshot the scope and restore it
    // before the handler and after the whole statement.
    let scope = with_host(|h| h.scope_snapshot());

    with_host(|h| h.push_scope()); // the try block is its own block scope
    let body_res = host::run_chunk_keyed(host::try_key(id, 0), || {
        with_host(|h| h.try_chunk(id, 0)).expect("try block exists")
    });
    with_host(|h| h.restore_scope(scope.clone()));
    let signal_after = with_host(|h| h.signal.is_some());
    if let Err(e) = body_res {
        if signal_after {
            pending = Some(e);
        } else if has_handler {
            // Bind the thrown value (or a synthesized error) to the catch param.
            let thrown =
                with_host(|h| h.exc.clone()).unwrap_or_else(|| with_host(|h| synth_error(h, &e)));
            with_host(|h| {
                h.error = None;
                h.exc = None;
            });
            // The catch parameter is block-scoped to the handler.
            with_host(|h| h.push_scope());
            if let Some(name) = &catch_bind {
                with_host(|h| h.declare_name(name, thrown));
            }
            let hres = host::run_chunk_keyed(host::try_key(id, 1), || {
                with_host(|h| h.try_chunk(id, 1)).expect("handler exists")
            });
            with_host(|h| h.restore_scope(scope.clone()));
            if let Err(e2) = hres {
                pending = Some(e2);
            }
        } else {
            pending = Some(e);
        }
    }

    // finally always runs; a finally error/signal supersedes.
    if has_finalizer {
        let sig_before = with_host(|h| h.signal.take());
        with_host(|h| h.push_scope()); // ditto for `finally`
        let fres = host::run_chunk_keyed(host::try_key(id, 2), || {
            with_host(|h| h.try_chunk(id, 2)).expect("finalizer exists")
        });
        with_host(|h| h.restore_scope(scope.clone()));
        match fres {
            Ok(_) => {
                if with_host(|h| h.signal.is_none()) {
                    // The finalizer completed normally: the try/catch block's own
                    // abrupt completion resumes.
                    with_host(|h| h.signal = sig_before);
                } else {
                    // ECMA-262 14.15.3 TryStatement evaluation: when the finalizer's
                    // completion is abrupt (`return`/`break`/`continue` inside
                    // `finally`), that completion REPLACES the try/catch block's —
                    // including a pending throw, which is discarded, not rethrown.
                    pending = None;
                    with_host(|h| {
                        h.error = None;
                        h.exc = None;
                    });
                }
            }
            Err(e) => pending = Some(e),
        }
    }

    if let Some(e) = pending {
        return abort(vm, e);
    }
    Value::Undef
}

/// Synthesize an `Error`-shaped object from an internal error string, linked to
/// the matching builtin error prototype so `instanceof`/`.constructor` work.
pub(crate) fn synth_error(h: &mut host::JsHost, e: &str) -> Value {
    h.ensure_error_protos();
    // A `DOMException` marker: the WHATWG error NAME rides in the string, since
    // it is not one of the ECMAScript error classes below.
    if let Some(rest) = e.strip_prefix(host::DOM_MARK) {
        if let Some((name, msg)) = rest.split_once('\u{1}') {
            return dom_exception_with(h, name, msg);
        }
    }
    // A `Name [ERR_CODE]: message` head carries a Node error `code` next to the
    // error class, exactly as Node's internal errors render it in `.stack`.
    let (head, rest) = match e.split_once(": ") {
        Some((n, m)) => (n, m.to_string()),
        None => ("", e.to_string()),
    };
    let (base, code) = match head.split_once(" [") {
        Some((n, c)) if c.ends_with(']') => (n, Some(c[..c.len() - 1].to_string())),
        _ => (head, None),
    };
    let (name, mut message) = if host::ERROR_NAMES.contains(&base) {
        (base.to_string(), rest)
    } else {
        ("Error".to_string(), e.to_string())
    };
    // A `host::plain_coded_error` marker: the code rides at the head of the
    // MESSAGE rather than in the class, because Node's native-layer errors set
    // `.code` while leaving `String(err)` unbracketed (`TypeError: Invalid URL`
    // with `code === 'ERR_INVALID_URL'`). Strip it back off here — the marker is
    // internal and must never reach a user-visible `.message`.
    let mut code = code;
    // Whether `String(err)`/`err.stack` show `Name [CODE]:` — true for the
    // bracketed head, false for the marker form.
    let mut bracketed = code.is_some();
    // Extra own properties (`input`, `base`) from `host::plain_coded_error_with`.
    let mut fields: Vec<(String, String)> = Vec::new();
    if let Some(rest) = message.strip_prefix(host::CODE_MARK) {
        if let Some((c, m)) = rest.split_once('\u{1}') {
            code = Some(c.to_string());
            bracketed = false;
            let (m, fs) = host::split_error_fields(m);
            fields = fs
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect();
            message = m.to_string();
        }
    }
    let mut props: IndexMap<String, Value> = IndexMap::new();
    let mv = h.new_str(message.clone());
    props.insert("message".into(), mv);
    if let Some(c) = &code {
        let cv = h.new_str(c.clone());
        props.insert("code".into(), cv);
        for (k, v) in fields {
            let fv = h.new_str(v);
            props.insert(k, fv);
        }
        if bracketed {
            // Marks this as a Node JS-layer error, whose `toString` brackets the
            // code. A native-layer error has the same `.code` and does not.
            props.insert("@@nodeError".into(), Value::Bool(true));
        }
    }
    let label = match (&code, bracketed) {
        (Some(c), true) => format!("{name} [{c}]"),
        _ => name.clone(),
    };
    let frames = h.stack_frames();
    let stack = if message.is_empty() {
        format!("{label}{frames}")
    } else {
        format!("{label}: {message}{frames}")
    };
    let sv = h.new_str(stack);
    props.insert("stack".into(), sv);
    // A libuv system-error message is itself the canonical encoding of the
    // error's metadata — `ENOENT: no such file or directory, open '/x'` — so a
    // filesystem/network failure recovers the enumerable `code`/`errno`/
    // `syscall`/`path` own properties that `err.code === 'ENOENT'` checks (the
    // single most common error-handling idiom in Node packages) depend on.
    for (k, v) in syscall_error_fields(&message) {
        let sv = match v {
            SysField::Str(s) => h.new_str(s),
            SysField::Num(n) => Value::Float(n),
        };
        props.insert(k.into(), sv);
    }
    let obj = h.new_object(props);
    if let Some(p) = host::error_proto_of(h, &name) {
        h.set_proto(&obj, p);
    }
    // `message`/`stack` are non-enumerable; a Node `ERR_*` error's `code` is not
    // (`Object.keys(e)` on an `ERR_INVALID_ARG_TYPE` reads `["code"]`).
    h.hide_prop(&obj, "message");
    h.hide_prop(&obj, "stack");
    obj
}

enum SysField {
    Str(String),
    Num(f64),
}

/// Decompose a libuv-shaped message (`ECODE: reason, syscall 'path'`) into the
/// own properties Node hangs off a system error. Returns empty for any message
/// that is not in that shape.
fn syscall_error_fields(message: &str) -> Vec<(&'static str, SysField)> {
    let (code, rest) = match message.split_once(": ") {
        Some((c, r))
            if c.len() >= 2
                && c.starts_with('E')
                && c.bytes()
                    .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) =>
        {
            (c, r)
        }
        _ => return Vec::new(),
    };
    let mut out: Vec<(&'static str, SysField)> = vec![
        ("errno", SysField::Num(errno_for(code))),
        ("code", SysField::Str(code.to_string())),
    ];
    // `reason, syscall 'path'` — the path is optional (`EPIPE: …, write`).
    if let Some((_, tail)) = rest.split_once(", ") {
        let (syscall, path) = match tail.split_once(" '") {
            // A two-path message ends `'from' -> 'to'`; `err.path` is the FIRST
            // one, so the scan stops at its closing quote rather than at the
            // end of the line — which had been swallowing `' -> 'dest` into the
            // path for every `rename` and `copyFile` failure.
            Some((s, p)) => (s, p.split_once('\'').map(|(first, _)| first)),
            None => (tail, None),
        };
        out.push(("syscall", SysField::Str(syscall.to_string())));
        if let Some(p) = path {
            out.push(("path", SysField::Str(p.to_string())));
        }
    }
    out
}

/// The negative `errno` Node reports for a libuv error code on this platform.
/// Only the codes `err_str` can produce are mapped; anything else reports the
/// generic `EIO` number rather than inventing a value.
fn errno_for(code: &str) -> f64 {
    let n: i32 = match code {
        "ENOENT" => 2,
        "EACCES" => 13,
        "EEXIST" => 17,
        "ENOTDIR" => 20,
        "EISDIR" => 21,
        "EINVAL" => 22,
        "EPIPE" => 32,
        "ENOTEMPTY" => 66,
        _ => 5, // EIO
    };
    -f64::from(n)
}

// ── iteration ─────────────────────────────────────────────────────────────────

fn b_getiter(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    // A generator is its own iterator (resumed lazily by FORITER).
    if with_host(|h| h.is_generator_val(&v)) {
        return v;
    }
    // A Proxy's iterator comes from its traps, materialized eagerly: the
    // `lookup_chain` probe below reads the property map a proxy does not have.
    if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
        return match crate::proxy::iterate(&v) {
            Ok(Some(items)) => with_host(|h| {
                h.alloc(JsObj::Iter {
                    items,
                    idx: 0,
                    array: None,
                })
            }),
            Ok(None) => abort(vm, "internal: kind_of said Proxy".into()),
            Err(e) => abort(vm, e),
        };
    }
    // Arrays and strings take the direct path below: they have no iterator
    // state to preserve and are the hot case, so they must not pay a property
    // lookup and a call per loop.
    let direct = matches!(
        with_host(|h| h.kind_of(&v)),
        Some(ObjKind::Array) | Some(ObjKind::Str)
    );
    // …but only while their `Symbol.iterator` is still reachable. It comes from
    // the intrinsic prototype, so replacing the link takes it away: node reports
    // `a is not iterable` for an array whose prototype is a plain object, where
    // the fast path below iterated the backing vector regardless.
    if !own_intrinsic_reachable(&v)
        && !matches!(
            get_property(&v, "@@iterator"),
            Ok(ref f) if with_host(|h| host::is_callable(h, f))
        )
    {
        let shown = with_host(|h| h.inspect(&v));
        let msg = host::type_error(&format!("{shown} is not iterable"));
        return abort(vm, host::name_call_site(vm, &shown, msg));
    }
    // Anything else with a `Symbol.iterator`: call it for the iterator object.
    //
    // Resolved as a full property READ, not a stored-property lookup. A
    // NATIVE-tagged object (`URLSearchParams`, `Headers`, `Map`, `Set`)
    // dispatches its methods through the stdlib table rather than a property
    // map, so a `lookup_chain` probe found nothing and the loop fell through to
    // materializing the value — which threw for `URLSearchParams` and
    // snapshotted for `Map`. Spreading the same object already worked, because
    // that path had been fixed and this one had not.
    if !direct {
        if let Ok(iter_fn) = get_property(&v, "@@iterator") {
            if with_host(|h| host::is_callable(h, &iter_fn)) {
                return match host::invoke(&iter_fn, Vec::new(), Some(v.clone())) {
                    Ok(it) => it,
                    Err(e) => abort(vm, e),
                };
            }
        }
    }
    // An array is iterated live, as its `values()` iterator does: a snapshot
    // missed every push during the loop, so a worklist `for (const n of q)
    // q.push(…)` stopped after the first element.
    if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Array) {
        return array_iterator(&v, host::ArrayIterKind::Values);
    }
    match with_host(|h| h.iter_vec(&v)) {
        Ok(items) => with_host(|h| {
            h.alloc(JsObj::Iter {
                items,
                idx: 0,
                array: None,
            })
        }),
        // V8 names the SOURCE EXPRESSION, not the value: `for (const x of a)`
        // reports `a is not iterable`. The text was recorded for this op.
        Err(e) => {
            let shown = with_host(|h| h.inspect(&v));
            let named = host::name_call_site(vm, &shown, e);
            abort(vm, named)
        }
    }
}

fn b_forin_keys(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    // `for-in` over a Proxy is 14.7.5.9 `EnumerateObjectProperties`: the
    // `ownKeys` trap filtered by `[[GetOwnProperty]]`'s `enumerable`. Both traps
    // are user code, so this cannot run inside `enum_keys`'s `&mut` host borrow.
    if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
        // `ownKeys` ONLY. The `enumerable` filter is 14.7.5.10's per-key
        // `[[GetOwnProperty]]`, which `FORIN_ALIVE` runs at the moment each key
        // is visited — so the `getOwnPropertyDescriptor` traps interleave with
        // the body the way node's do, instead of all firing up front.
        return match crate::proxy::own_keys(&v) {
            Ok(keys) => with_host(|h| {
                let out: Vec<Value> = keys
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|k| !host::is_symbol_key(k))
                    .map(|k| h.new_str(k))
                    .collect();
                h.new_array(out)
            }),
            Err(e) => abort(vm, e),
        };
    }
    let mut keys = with_host(|h| h.enum_keys(&v));
    // A member patched onto the receiver's INTRINSIC prototype is enumerable
    // and inherited, so `for-in` visits it after the own keys — but the
    // intrinsic prototypes are not links `enum_keys` can walk, so its chain
    // pass never reaches them.
    if !with_host(|h| h.has_null_proto(&v)) {
        let seen: Vec<String> = keys.iter().map(|k| with_host(|h| h.str_of(k))).collect();
        for ns in intrinsic_proto_namespaces(&v) {
            for k in with_host(|h| h.builtin_static_keys(&ns)) {
                if !seen.contains(&k) && !intrinsic_proto_member(&ns, &k) {
                    keys.push(with_host(|h| h.new_str(k)));
                }
            }
        }
    }
    with_host(|h| h.new_array(keys))
}

/// The intrinsic prototype namespaces `v` inherits from, nearest first — its
/// own constructor's and then `Object`'s, the same two steps
/// `inherited_builtin_static` looks a value up in.
fn intrinsic_proto_namespaces(v: &Value) -> Vec<String> {
    let ctor = match wrapped_primitive(v).as_ref().and_then(wrapper_ctor_of) {
        Some(c) => Some(c),
        None if is_arguments(v) => Some("Object"),
        None => with_host(|h| default_ctor_name(h, v)),
    };
    let mut out: Vec<String> = ctor
        .filter(|c| *c != "Object")
        .map(|c| format!("{c}.prototype"))
        .into_iter()
        .collect();
    out.push("Object.prototype".to_string());
    out
}

/// `FORIN_ALIVE` — is `key` STILL an enumerable property of `obj`?
///
/// `for-in` takes its key list once (14.7.5.10 builds it lazily, but a snapshot
/// of the enumerable keys is observationally the same for everything except
/// this), and the body can delete a key before the loop reaches it. Node does
/// not visit a key deleted that way; without this check `delete d.z` inside the
/// loop still produced `x,y,z`.
///
/// The check is `[[GetOwnProperty]]`-shaped rather than `in`: on a Proxy it runs
/// the `getOwnPropertyDescriptor` trap, which is what node runs, and NOT the
/// `has` trap, which node never fires for `for-in`. That also puts each trap
/// call immediately before its visit, matching node's interleaving — the trap
/// log used to show every `gopd` up front because the key list was filtered
/// eagerly.
fn b_forin_alive(vm: &mut VM, _: u8) -> Value {
    let key = vm.pop();
    let obj = vm.pop();
    let name = with_host(|h| h.str_of(&key));
    if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
        return match crate::proxy::own_enumerable(&obj, &name) {
            Ok(b) => Value::Bool(b),
            Err(e) => abort(vm, e),
        };
    }
    // A STRING's keys are its character indices. `in` is not defined on a string
    // primitive at all, so the ordinary path below has no answer for one and
    // `for (const i in 'abc')` came back empty.
    if let Some(s) = with_host(|h| h.as_str(&obj)) {
        let len = crate::utf16::len(&s);
        return Value::Bool(name.parse::<usize>().is_ok_and(|i| i < len));
    }
    // Any other receiver: EXISTENCE only. Node re-checks that the key is still
    // there and does NOT re-check enumerability — making one non-enumerable
    // mid-loop still visits it, where re-filtering on `enumerable` dropped it.
    // (The Proxy branch above does re-check, because there the answer comes from
    // the trap node itself calls.)
    Value::Bool(has_property_ordinary(&obj, &name))
}

fn b_foriter(vm: &mut VM, _: u8) -> Value {
    let it = match vm.stack.last() {
        Some(v) => v.clone(),
        None => return abort(vm, "internal: FORITER with empty stack".into()),
    };
    // A built-in iterator: a snapshot (strings, a Proxy's items) or live over
    // an array.
    if let Some(step) = iter_step(&it) {
        return match step {
            Some(v) => {
                vm.push(v);
                Value::Bool(true)
            }
            None => Value::Bool(false),
        };
    }
    // Generator: resume one step.
    if with_host(|h| h.is_generator_val(&it)) {
        return match host::gen_resume(&it, Value::Undef) {
            Ok(host::GenStep::Yield(v)) => {
                vm.push(v);
                Value::Bool(true)
            }
            Ok(host::GenStep::Done(_)) => Value::Bool(false),
            Err(e) => abort(vm, e),
        };
    }
    // A user iterator object with a `.next()` returning `{ value, done }`.
    match host::call_method(&it, "next", Vec::new()) {
        Ok(step) => {
            let done = get_property(&step, "done")
                .map(|d| with_host(|h| h.truthy(&d)))
                .unwrap_or(true);
            if done {
                Value::Bool(false)
            } else {
                match get_property(&step, "value") {
                    Ok(v) => {
                        vm.push(v);
                        Value::Bool(true)
                    }
                    Err(e) => abort(vm, e),
                }
            }
        }
        Err(e) => abort(vm, e),
    }
}

fn b_unpack(vm: &mut VM, _: u8) -> Value {
    let star = match vm.pop() {
        Value::Int(n) => n,
        _ => -1,
    };
    let count = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => 0,
    };
    let iterable = vm.pop();
    // Without a `...rest` element the pattern needs exactly `count` values and
    // must then close the iterator; draining hung on an unbounded source.
    let items = match if star < 0 {
        host::iter_take(&iterable, count)
    } else {
        host::iter_all(&iterable)
    } {
        Ok(v) => v,
        // Destructuring a non-iterable names the SOURCE EXPRESSION, the way
        // `for-of` does: `const [x] = o` reports `o is not iterable`. The text
        // was recorded for this op at compile time.
        Err(e) => {
            // Node names the source only when the pattern's right-hand side is
            // a plain IDENTIFIER — `const [x] = o` is `o is not iterable`.
            // Anything else (a member, a call, a nested pattern, a parameter)
            // reports the TYPE instead, with the property note. Measured across
            // twelve shapes rather than guessed.
            let msg = match host::call_site_text(vm) {
                Some(text) => host::type_error(&format!("{text} is not iterable")),
                None if e.ends_with(" is not iterable") => {
                    host::type_error(&not_iterable_typed(&iterable))
                }
                None => e,
            };
            return abort(vm, msg);
        }
    };
    let ordered: Vec<Value> = if star < 0 {
        (0..count)
            .map(|i| items.get(i).cloned().unwrap_or(Value::Undef))
            .collect()
    } else {
        let si = star as usize;
        let after = count.saturating_sub(si + 1);
        let rest_end = items.len().saturating_sub(after).max(si);
        let mut out: Vec<Value> = Vec::with_capacity(count);
        for i in 0..si {
            out.push(items.get(i).cloned().unwrap_or(Value::Undef));
        }
        let rest: Vec<Value> = items
            .get(si..rest_end)
            .map(|s| s.to_vec())
            .unwrap_or_default();
        out.push(with_host(|h| h.new_array(rest)));
        for j in 0..after {
            out.push(items.get(rest_end + j).cloned().unwrap_or(Value::Undef));
        }
        out
    };
    if ordered.is_empty() {
        return Value::Undef;
    }
    for it in ordered[1..].iter().rev().cloned() {
        vm.push(it);
    }
    ordered[0].clone()
}

fn b_build_args(vm: &mut VM, argc: u8) -> Value {
    let flat = pop_n(vm, argc as usize);
    let mut out = Vec::new();
    // Elided positions of an array literal (tag 2), recorded as the run-time
    // index each lands on — which only this walk knows, because a preceding
    // spread contributes an unknown number of elements. Call-argument lists,
    // the other `BUILD_ARGS` caller, cannot contain an elision, so this stays
    // empty for them.
    let mut holes: rustc_hash::FxHashSet<usize> = rustc_hash::FxHashSet::default();
    let mut i = 0;
    while i + 1 < flat.len() {
        let val = flat[i + 1].clone();
        match flat[i] {
            // Tag 1 is an ARRAY-LITERAL spread, tag 3 a CALL-ARGUMENT one. They
            // report a non-iterable differently, which is the only reason the
            // two are told apart here.
            Value::Int(1) => match host::iter_all(&val).map_err(|e| {
                let shown = with_host(|h| h.inspect(&val));
                host::name_call_site(vm, &shown, e)
            }) {
                Ok(items) => out.extend(items),
                Err(e) => return abort(vm, e),
            },
            Value::Int(3) => match host::iter_all(&val) {
                Ok(items) => out.extend(items),
                Err(e) => {
                    // A NULLISH spread names the value and what could not be
                    // read off it; anything else names the missing protocol.
                    let shown = with_host(|h| h.is_nullish(&val).then(|| h.str_of(&val)));
                    return abort(
                        vm,
                        match shown {
                            Some(s) => host::type_error(&format!(
                                "{s} is not iterable (cannot read property {s})"
                            )),
                            None if e.ends_with(" is not iterable") => host::type_error(
                                "Spread syntax requires ...iterable[Symbol.iterator] to be a function",
                            ),
                            None => e,
                        },
                    );
                }
            },
            Value::Int(2) => {
                holes.insert(out.len());
                out.push(Value::Undef);
            }
            _ => out.push(val),
        }
        i += 2;
    }
    with_host(|h| {
        let arr = h.new_array(out);
        h.install_holes(&arr, holes);
        arr
    })
}

// ── calls ──────────────────────────────────────────────────────────────────────

fn b_call(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let name = sval(&args.remove(0));
    let r = host::call_named(&name, args);
    // A bare name that resolved to a non-callable reports the VALUE
    // (`undefined is not a function`); node names the identifier. Resolving it
    // again to learn what the message said costs nothing off the error path.
    let r = r.map_err(|e| {
        let shown = global_binding(&name)
            .map(|v| with_host(|h| h.str_of(&v)))
            .unwrap_or_default();
        host::name_call_site(vm, &shown, e)
    });
    finish(vm, r)
}

/// `recv[0](…)` — a computed call whose key is an ARRAY INDEX rather than a
/// method name. `call_method` resolves by name and bottoms out in
/// `call_type_method`, which knows `sort`/`slice` and not `"0"`, so an element
/// that happens to be a function reported "is not a function". Read the element
/// and invoke it with `recv` as `this`, which is the receiver 13.3.6 gives it.
/// A computed call's key is a property key, so it goes through ToPropertyKey:
/// `arr[0](…)` looks up `"0"`. `sval` only unwraps an existing `Value::Str` and
/// answers "" for a number, which turned `arr[0]()` into a call to the method
/// named "" — so the key is stringified here instead.
fn call_key_of(v: &Value) -> String {
    if let Value::Str(s) = v {
        return (**s).clone();
    }
    // `ToPropertyKey`, not `ToString`. A SYMBOL key has an internal `@@name`
    // spelling that `str_of` does not produce — it renders
    // `Symbol(Symbol.iterator)` — so `obj[Symbol.iterator]()` dispatched a
    // method by that display text and reported it was not a function, for every
    // object including a plain literal with a computed symbol method. Reading
    // the same property without calling it worked, which is what hid this.
    with_host(|h| h.property_key(v))
}

fn index_element_call(recv: &Value, name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    if name.is_empty() || !name.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let f = get_property(recv, name).ok()?;
    with_host(|h| host::is_callable(h, &f))
        .then(|| host::invoke(&f, args.to_vec(), Some(recv.clone())))
}

fn b_call_method(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let recv = args.remove(0);
    let name = call_key_of(&args.remove(0));
    if let Some(r) = index_element_call(&recv, &name, &args) {
        return finish(vm, r);
    }
    let r = host::call_method(&recv, &name, args);
    // `z.f()` on a missing method is `z.f is not a function` in node, not
    // `f is not a function`: V8 names the callee as the source wrote it. The
    // text was recorded for this op at compile time.
    let r = r.map_err(|e| host::name_call_site(vm, &name, e));
    finish(vm, r)
}

fn b_call_value(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let callable = args.remove(0);
    let r = host::invoke(&callable, args, None);
    // The callee here is an expression, not a name, so the message it produced
    // describes the VALUE (`undefined is not a function`); node names the
    // expression. Same site table, keyed on that rendering.
    let r = r.map_err(|e| {
        let shown = with_host(|h| h.str_of(&callable));
        host::name_call_site(vm, &shown, e)
    });
    finish(vm, r)
}

/// `NEW_SPREAD` — `new C(...xs)`, where the argument list is a run-time array
/// rather than a fixed count of stack slots.
///
/// `compile_new` used to compile each argument with `compile_expr`, and a
/// spread there evaluates to the SPREAD OBJECT itself — so `new C(...[1, 2])`
/// passed the array as one argument and `new Date(...[2020, 0, 1])` built an
/// Invalid Date.
fn b_new_spread(vm: &mut VM, _: u8) -> Value {
    let args_arr = vm.pop();
    let ctor = vm.pop();
    let args = host::iter_all(&args_arr).unwrap_or_default();
    let r = host::construct(&ctor, args).map_err(|e| {
        let shown = with_host(|h| h.str_of(&ctor));
        host::name_call_site(vm, &shown, e)
    });
    finish(vm, r)
}

fn b_new(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let ctor = args.remove(0);
    let r = host::construct(&ctor, args);
    // `new (o.a.b.c)()` on a non-constructor names the expression, as a failed
    // call does.
    let r = r.map_err(|e| {
        let shown = with_host(|h| h.str_of(&ctor));
        host::name_call_site(vm, &shown, e)
    });
    finish(vm, r)
}

fn b_apply(vm: &mut VM, _: u8) -> Value {
    let args_arr = vm.pop();
    let callable = vm.pop();
    let args = host::iter_all(&args_arr).unwrap_or_default();
    let r = host::invoke(&callable, args, None);
    finish(vm, r)
}

fn b_apply_method(vm: &mut VM, _: u8) -> Value {
    let args_arr = vm.pop();
    let name = call_key_of(&vm.pop());
    let recv = vm.pop();
    let args = host::iter_all(&args_arr).unwrap_or_default();
    if let Some(r) = index_element_call(&recv, &name, &args) {
        return finish(vm, r);
    }
    let r = host::call_method(&recv, &name, args);
    finish(vm, r)
}

// ── numeric hook ──────────────────────────────────────────────────────────────

/// Host callback for arithmetic fusevm cannot complete natively (a non-`Int`/
/// non-`Float` operand). Supplies JavaScript `+` concatenation and coercion.
///
/// Every operand is run through `ToPrimitive` FIRST (ECMA-262 13.15.3 for `+`,
/// 13.6.3 for the other arithmetic ops, 13.10.1 for the relational ones), which
/// is what invokes a user `valueOf`/`Symbol.toPrimitive`. It has to happen here
/// rather than inside `JsHost::arith`, because calling back into JS re-enters
/// the VM and `arith` runs under the host's `RefCell` borrow.
pub fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    use NumOp::*;
    let (a, b) = match op {
        // `==`/`!=` only convert when the OTHER side is a primitive that can be
        // compared numerically or textually; `{} == {}` stays a reference check.
        Eq | Ne => {
            let (pa, pb) = with_host(|h| (host::is_primitive(h, a), host::is_primitive(h, b)));
            match (pa, pb) {
                (false, true) if coerces_against_object(b) => {
                    (host::to_primitive(a, "default")?, b.clone())
                }
                (true, false) if coerces_against_object(a) => {
                    (a.clone(), host::to_primitive(b, "default")?)
                }
                _ => (a.clone(), b.clone()),
            }
        }
        // `+` uses the default hint (`valueOf` first, but a string result still
        // selects concatenation); everything else uses the number hint.
        Add => (
            host::to_primitive(a, "default")?,
            host::to_primitive(b, "default")?,
        ),
        _ => (
            host::to_primitive(a, "number")?,
            host::to_primitive(b, "number")?,
        ),
    };
    reject_symbol_operand(op, &a, &b)?;
    with_host(|h| h.arith(op, &a, &b))
}

/// A symbol has no `ToNumber` and no `ToString`, so every operator except the
/// equality family rejects it (7.1.4 step 2, 7.1.17 step 2). node-js instead
/// concatenated `Symbol(desc)` into the result.
///
/// Which of the two messages V8 uses is decided by whether the operation is
/// STRING concatenation — measured on node v26.7.0, `Symbol() + ''` is
/// `Cannot convert a Symbol value to a string` while `Symbol() + 1`,
/// `Symbol() + Symbol()` and `Symbol() * 1` are all
/// `Cannot convert a Symbol value to a number`. `==`/`===` never convert
/// (`Symbol() == 1` is `false`), so they are left alone.
fn reject_symbol_operand(op: NumOp, a: &Value, b: &Value) -> Result<(), String> {
    use NumOp::*;
    if matches!(op, Eq | Ne) {
        return Ok(());
    }
    let (sym, concat) = with_host(|h| {
        let is_sym = |v: &Value| matches!(h.get(v), Some(JsObj::Symbol { .. }));
        let is_str =
            |v: &Value| matches!(v, Value::Str(_)) || matches!(h.get(v), Some(JsObj::Str(_)));
        (is_sym(a) || is_sym(b), is_str(a) || is_str(b))
    });
    if !sym {
        return Ok(());
    }
    Err(host::type_error(if matches!(op, Add) && concat {
        "Cannot convert a Symbol value to a string"
    } else {
        "Cannot convert a Symbol value to a number"
    }))
}

/// Whether a primitive `v` makes `==` against an object convert that object
/// (7.2.15 steps 10-11): numbers, strings, bigints and symbols do; `null`,
/// `undefined` and booleans are settled without a `ToPrimitive` call
/// (a boolean is coerced to a number first, and then it does).
fn coerces_against_object(v: &Value) -> bool {
    match v {
        Value::Undef => false,
        Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::Str(_) => true,
        _ => with_host(|h| !h.is_null(v)),
    }
}

// ══ standard library ═══════════════════════════════════════════════════════════

/// Namespaces reachable as bare globals.
fn is_namespace(name: &str) -> bool {
    matches!(
        name,
        "console"
            | "Math"
            | "JSON"
            | "Object"
            | "Array"
            | "Number"
            | "String"
            | "Boolean"
            | "Symbol"
            | "Reflect"
            | "Promise"
            | "process"
            | "Buffer"
            | "URL"
            | "URLSearchParams"
    )
}

const GLOBAL_FUNCS: &[&str] = &[
    "parseInt",
    "parseFloat",
    "isNaN",
    "isFinite",
    "encodeURIComponent",
    "decodeURIComponent",
    "encodeURI",
    "decodeURI",
    // Annex B legacy encoders. Still globals on every engine, and still called
    // by pre-`encodeURIComponent` library code.
    "escape",
    "unescape",
    "eval",
    "String",
    "Number",
    "Boolean",
    "Array",
    "Object",
    "Function",
    "Symbol",
    "Map",
    "Set",
    "WeakMap",
    "WeakSet",
    "Promise",
    "Error",
    "TypeError",
    "RangeError",
    "SyntaxError",
    "ReferenceError",
    "EvalError",
    "URIError",
    "AggregateError",
    "DOMException",
    "Iterator",
    "BigInt",
    "RegExp",
    "Date",
    "ArrayBuffer",
    "DataView",
    "Uint8Array",
    "Int8Array",
    "Uint8ClampedArray",
    "Int16Array",
    "Uint16Array",
    "Int32Array",
    "Uint32Array",
    "Float32Array",
    "Float64Array",
    "BigInt64Array",
    "BigUint64Array",
    "WeakRef",
    "FinalizationRegistry",
    "TextEncoder",
    "TextDecoder",
    // WHATWG Fetch globals (see `stdlib::fetch`).
    "fetch",
    "Headers",
    "Request",
    "Response",
    "Blob",
    "File",
    "FormData",
    "AbortController",
    "AbortSignal",
    "queueMicrotask",
    "setTimeout",
    "setInterval",
    "setImmediate",
    "clearTimeout",
    "clearInterval",
    "clearImmediate",
    "structuredClone",
    // Base64 helpers. They existed only as `require('buffer').btoa`, but node
    // exposes both as globals, so `btoa('abc')` was a ReferenceError.
    "btoa",
    "atob",
    "Proxy",
    "require",
    // CommonJS loader dispatch targets referenced by per-module `require`
    // closures (see `module.rs`); never written by user code.
    "__cjs_require",
    "__cjs_resolve",
    "__cjs_cache",
];

const NS_METHODS: &[&str] = &[
    "console.log",
    "console.error",
    "console.warn",
    "console.info",
    "console.debug",
    "Math.abs",
    "Math.acos",
    "Math.acosh",
    "Math.asin",
    "Math.asinh",
    "Math.atan",
    "Math.atanh",
    "Math.atan2",
    "Math.ceil",
    "Math.cbrt",
    "Math.expm1",
    "Math.clz32",
    "Math.cos",
    "Math.cosh",
    "Math.exp",
    "Math.floor",
    "Math.fround",
    "Math.hypot",
    "Math.imul",
    "Math.log",
    "Math.log1p",
    "Math.log2",
    "Math.log10",
    "Math.max",
    "Math.min",
    "Math.pow",
    "Math.random",
    "Math.round",
    "Math.sign",
    "Math.sin",
    "Math.sinh",
    "Math.sqrt",
    "Math.tan",
    "Math.tanh",
    "Math.trunc",
    "JSON.stringify",
    "JSON.parse",
    "JSON.rawJSON",
    "JSON.isRawJSON",
    "Object.keys",
    "Object.values",
    "Object.entries",
    "Object.assign",
    "Object.freeze",
    "Object.is",
    "Object.fromEntries",
    "Object.getPrototypeOf",
    "Object.setPrototypeOf",
    "Object.create",
    "Object.getOwnPropertyNames",
    "Object.getOwnPropertySymbols",
    "Object.defineProperty",
    "Object.getOwnPropertyDescriptor",
    "Object.getOwnPropertyDescriptors",
    "Object.defineProperties",
    "Object.isFrozen",
    "Object.isSealed",
    "Object.seal",
    "Object.preventExtensions",
    "Object.isExtensible",
    "Object.hasOwn",
    "Object.groupBy",
    "Array.isArray",
    "Array.from",
    "Array.fromAsync",
    "Array.of",
    "Number.isFinite",
    "Number.isInteger",
    "Number.isNaN",
    "Number.isSafeInteger",
    "Number.parseFloat",
    "Number.parseInt",
    "String.fromCharCode",
    "String.fromCodePoint",
    "String.raw",
    "Symbol.for",
    "Symbol.keyFor",
    "BigInt.asIntN",
    "BigInt.asUintN",
    "Proxy.revocable",
    "Reflect.defineProperty",
    "Reflect.deleteProperty",
    "Reflect.apply",
    "Reflect.construct",
    "Reflect.get",
    "Reflect.getOwnPropertyDescriptor",
    "Reflect.getPrototypeOf",
    "Reflect.has",
    "Reflect.isExtensible",
    "Reflect.ownKeys",
    "Reflect.preventExtensions",
    "Reflect.set",
    "Reflect.setPrototypeOf",
    "Promise.resolve",
    "Promise.reject",
    "Promise.all",
    "Promise.allSettled",
    "Promise.race",
    "Promise.any",
    "Promise.withResolvers",
    "Promise.try",
    "RegExp.escape",
    "Error.isError",
    "Map.groupBy",
    "Response.json",
    "Response.error",
    "Response.redirect",
    "AbortSignal.abort",
    "AbortSignal.timeout",
    "process.nextTick",
    "Error.captureStackTrace",
    "require.resolve",
    "require.resolve.paths",
    "process.memoryUsage.rss",
];

/// The `name` and `length` a builtin function reports, from the generated
/// intrinsic table ([`crate::arity::BUILTIN_ARITY`]). `None` for a key the table
/// does not cover — every non-function namespace (`Math`, `require('fs')`),
/// and the core-module functions, whose arity is not specified anywhere.
pub fn builtin_meta(key: &str) -> Option<(&'static str, u32)> {
    crate::arity::BUILTIN_ARITY
        .binary_search_by(|(k, _, _)| (*k).cmp(key))
        .ok()
        .map(|i| {
            let (_, name, len) = crate::arity::BUILTIN_ARITY[i];
            (name, len)
        })
}

/// The `name` a builtin function reports. The table answers for an intrinsic;
/// anything else falls back to the last segment of the key, which is what the
/// name is for every builtin this frontend synthesizes: `@proto:TypedArray:set`
/// is `set` and `fs.readFileSync` is `readFileSync`. Reporting the whole key was
/// how `[Function: @proto:TypedArray:set]` reached `console.log`.
pub fn builtin_name(key: &str) -> &str {
    if let Some((name, _)) = builtin_meta(key) {
        return name;
    }
    match key.strip_prefix("@proto:") {
        Some(rest) => rest.rsplit(':').next().unwrap_or(rest),
        // An accessor's getter is named `get <member>` (10.2.9 SetFunctionName
        // with a `get` prefix), which is what `util.inspect` prints for it and
        // what a library reads to identify one.
        None => key.rsplit('.').next().unwrap_or(key),
    }
}

/// The `name` of an intrinsic accessor's getter thunk, or `None` for anything
/// else. Kept out of `builtin_name`'s `&str` return, which cannot own the
/// `"get size"` it has to build.
pub fn proto_getter_name(key: &str) -> Option<String> {
    let (verb, rest) = match key.strip_prefix("@protoget:") {
        Some(rest) => ("get", rest),
        None => ("set", key.strip_prefix("@protoset:")?),
    };
    let (_, member) = rest.split_once(':')?;
    Some(format!("{verb} {member}"))
}

pub fn is_known_builtin(name: &str) -> bool {
    // Binary search over a sorted INDEX of the two tables rather than a scan of
    // both. This runs on every call whose callee is a builtin — `call_method`
    // asks it before dispatching `Math.max(…)` or `JSON.parse(…)` — and the
    // answer came only after a full scan of `GLOBAL_FUNCS` (77) plus a scan of
    // `NS_METHODS` up to the entry — 106 string comparisons for `Math.max`, 120
    // for `Object.keys` — because those tables are ordered for ENUMERATION (V8's
    // own order for `Math`/`Number`/`Reflect`), not for lookup. Eight probes
    // now. The index is built once per process and derived FROM those tables, so
    // it cannot drift from them.
    //
    // That is an operation count, not a measured time, and NO wall-clock win is
    // claimed. Re-measured in isolation (this hunk alone applied to the previous
    // commit, interleaved against it, minimums over ten rounds each): the A/B
    // ratio came out 0.753, 1.072, 0.994 and 0.744 across four repeats, while
    // the A/A control — the SAME binary under both labels — came out 1.084,
    // 1.072, 0.787 and 1.093. The A/B spread lies inside the A/A spread, so on
    // this machine the change is not distinguishable from noise. It is kept for
    // the comparison count and because it cannot drift from the tables it is
    // derived from, not because anything got faster.
    static SORTED: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
    let sorted = SORTED.get_or_init(|| {
        let mut v: Vec<&'static str> = GLOBAL_FUNCS
            .iter()
            .chain(NS_METHODS.iter())
            .copied()
            .collect();
        v.sort_unstable();
        v
    });
    sorted.binary_search(&name).is_ok() || is_namespace(name) || crate::stdlib::is_method(name)
}

// ── dynamic functions (runtime source → callable) ────────────────────────────

/// Build a callable from a complete function-expression source text — the ONE
/// dynamic-function generator on this frontend.
///
/// `src` is the exact source V8 synthesizes for the construct, WITHOUT the
/// wrapping parentheses needed to parse it as an expression: those are added
/// here, and `src` itself is retained so `Function.prototype.toString` reports
/// what V8 reports. The two callers synthesize different text and both shapes
/// are observable — see `stdlib::vm::compile_function` for the measured diff.
///
/// The body runs in the MODULE scope, never the constructing function's scope
/// (20.2.1.1.1 step 26 instantiates a dynamic function's body against the
/// *global* environment). That also makes a `var` inside the body a function
/// local: measured on node v26.7.0, `new Function('a','var zz = 5; return zz + a')`
/// returns 6 and leaves `globalThis.zz` `undefined`.
pub fn dynamic_function(src: &str) -> Result<Value, String> {
    let f = crate::eval_in_global_scope(&format!("({src})"))?;
    with_host(|h| {
        let s = h.new_str(src.to_string());
        h.set_fn_prop(&f, "@@source", s);
    });
    Ok(f)
}

/// `new Function(p1, …, pN, body)` / `Function(p1, …, pN, body)`.
///
/// Argument convention (20.2.1.1.1): the LAST argument is the body and the rest
/// are parameter-list fragments joined with `,` — so a fragment may itself hold
/// several parameters (`new Function('a,b', 'c', …)` takes three). With no
/// arguments at all, both the parameter list and the body are empty.
///
/// Measured on node v26.7.0:
///
/// ```text
/// new Function('a','b','return a+b').toString() === 'function anonymous(a,b\n) {\nreturn a+b\n}'
/// new Function().toString()                     === 'function anonymous(\n) {\n\n}'
/// new Function('a,b','c','return [a,b,c]').length === 3
/// new Function('a','b','return a+b').name       === 'anonymous'
/// ```
pub fn function_ctor(args: &[Value]) -> Result<Value, String> {
    let parts: Vec<String> = args.iter().map(|a| with_host(|h| h.str_of(a))).collect();
    let (params, body) = match parts.split_last() {
        Some((body, params)) => (params.join(","), body.clone()),
        None => (String::new(), String::new()),
    };
    dynamic_function(&format!("function anonymous({params}\n) {{\n{body}\n}}"))
}

/// `eval(src)`. `direct` selects the scope the source runs in: a DIRECT eval —
/// the literal `eval(...)` call form — evaluates in the CALLER's scope, every
/// other route to the same function value is an INDIRECT eval and evaluates in
/// the global scope (ECMA-262 19.2.1.1 `PerformEval`). The two are told apart in
/// `host::call_named`, which `ops::CALL` reaches and `ops::CALL_VALUE`/`APPLY`
/// do not.
///
/// A non-string argument is returned unchanged (19.2.1.1 step 2).
pub fn eval_source(arg: Option<&Value>, direct: bool) -> Result<Value, String> {
    let v = arg.cloned().unwrap_or(Value::Undef);
    let is_string =
        matches!(v, Value::Str(_)) || with_host(|h| matches!(h.get(&v), Some(JsObj::Str(_))));
    if !is_string {
        return Ok(v);
    }
    let src = with_host(|h| h.str_of(&v));
    // A DIRECT eval inherits the caller's strictness (19.2.1.1 step 10), which
    // decides both the early errors the COMPILE raises and the variable
    // environment below. An INDIRECT one is global-scope sloppy code.
    let caller_strict = direct && with_host(|h| h.current_strict());
    let chunk = crate::load_merged(crate::compile_completion_strict(&src, caller_strict)?);
    if !direct {
        return host::run_chunk_in_global_scope(chunk);
    }
    // A STRICT direct eval gets its OWN variable environment (19.2.1.1 step 12),
    // so its `var`s and function declarations die with it. Only a SLOPPY one
    // shares the caller's, which is the form that can inject a binding — and
    // sharing it unconditionally meant `eval('var x=1')` inside strict code
    // left `x` behind.
    let strict = caller_strict
        || src.trim_start().starts_with("'use strict'")
        || src.trim_start().starts_with("\"use strict\"");
    if !strict {
        // 19.2.1.1 steps 12-13: a SLOPPY direct eval shares the caller's
        // VARIABLE environment — which is what lets `eval('var x=1')` inject a
        // binding — but gets a fresh LEXICAL one of its own. A `let`, `const`
        // or `class` declared inside therefore dies with the eval; every one of
        // them was landing in the caller's scope, so `eval('let a=1')` left `a`
        // behind and `let a=1; eval('let a=2')` overwrote it.
        //
        // `push_scope` is exactly that split: `var` and a hoisted function
        // declaration bind to `base_env`, which this does not touch.
        with_host(|h| h.push_scope());
        let out = host::run_chunk_on(chunk);
        with_host(|h| h.pop_scope());
        return out;
    }
    let prev = with_host(|h| h.push_var_scope());
    let out = host::run_chunk_on(chunk);
    with_host(|h| h.pop_var_scope(prev));
    out
}

/// Call a resolved builtin function (global or `namespace.method`).
pub fn call_builtin_function(name: &str, args: Vec<Value>) -> Result<Value, String> {
    // `require(spec)`: the ENTRY script's top-level require — core module first,
    // else the CommonJS loader resolving from the entry file's directory.
    if name == "require" {
        let spec = with_host(|h| h.str_of(&arg0(&args)));
        return crate::module::require(&spec, &crate::module::entry_dir());
    }
    // `__cjs_require(spec, fromDir)`: a per-module `require` closure's dispatch
    // into the loader, resolving `spec` against the module's own directory.
    if name == "__cjs_require" {
        let spec = with_host(|h| h.str_of(&arg0(&args)));
        let from = with_host(|h| h.str_of(args.get(1).unwrap_or(&Value::Undef)));
        return crate::module::require(&spec, std::path::Path::new(&from));
    }
    if name == "process.memoryUsage.rss" {
        return Ok(crate::stdlib::process::memory_usage_rss());
    }
    if name == "require.resolve.paths" {
        let spec = with_host(|h| h.str_of(&arg0(&args)));
        // A core module is not looked up on disk at all.
        if crate::stdlib::is_core(&spec) {
            return Ok(with_host(|h| h.null()));
        }
        let dirs = crate::module::resolve_paths(&spec, &crate::module::entry_dir());
        return Ok(with_host(|h| {
            let items: Vec<Value> = dirs.into_iter().map(|d| h.new_str(d)).collect();
            h.new_array(items)
        }));
    }
    // A `require.extensions` entry. This runtime's loader does not dispatch
    // through the map, so calling one is the loader's own behaviour for that
    // extension rather than a hook point.
    if let Some(ext) = name.strip_prefix("@@extension:") {
        let _ = ext;
        return Ok(Value::Undef);
    }
    // `require.resolve(spec)` at the ENTRY level: resolve from the entry dir.
    if name == "require.resolve" {
        let spec = with_host(|h| h.str_of(&arg0(&args)));
        if crate::stdlib::is_core(&spec) {
            return Ok(with_host(|h| h.new_str(spec)));
        }
        return match crate::module::resolve(&spec, &crate::module::entry_dir()) {
            Some(p) => Ok(with_host(|h| h.new_str(p.to_string_lossy().to_string()))),
            None => Err(crate::host::plain_coded_error(
                "Error",
                "MODULE_NOT_FOUND",
                &format!("Cannot find module '{spec}'"),
            )),
        };
    }
    // `__cjs_resolve(spec, fromDir)`: `require.resolve` — the resolved absolute
    // path (core modules resolve to the bare specifier, as in Node).
    if name == "__cjs_resolve" {
        let spec = with_host(|h| h.str_of(&arg0(&args)));
        let from = with_host(|h| h.str_of(args.get(1).unwrap_or(&Value::Undef)));
        if crate::stdlib::is_core(&spec) {
            return Ok(with_host(|h| h.new_str(spec)));
        }
        return match crate::module::resolve(&spec, std::path::Path::new(&from)) {
            Some(p) => Ok(with_host(|h| h.new_str(p.to_string_lossy().to_string()))),
            None => Err(crate::host::plain_coded_error(
                "Error",
                "MODULE_NOT_FOUND",
                &format!("Cannot find module '{spec}'"),
            )),
        };
    }
    // `Error.captureStackTrace(target[, ctor])`: V8's stack capture. Sets
    // `target.stack`; when a custom `Error.prepareStackTrace` is installed (the
    // stack-introspection pattern used by `depd`), it is called with a synthetic
    // CallSite array and its result becomes `.stack`, else `.stack` is a string.
    if name == "Error.captureStackTrace" {
        let target = arg0(&args);
        let prep = with_host(|h| h.builtin_static("Error", "prepareStackTrace"));
        let stack = match prep {
            Some(f)
                if matches!(
                    with_host(|h| h.get(&f).cloned()),
                    Some(JsObj::Func(_)) | Some(JsObj::Builtin(_)) | Some(JsObj::BoundFunc { .. })
                ) =>
            {
                let sites = crate::module::callsite_stack(10)?;
                host::invoke(&f, vec![target.clone(), sites], None)?
            }
            _ => with_host(|h| h.new_str("")),
        };
        let _ = set_property(&target, "stack", stack);
        return Ok(Value::Undef);
    }
    // Native stdlib module methods (path/os/fs/util/assert/crypto/buffer/url).
    if let Some(r) = crate::stdlib::call(name, &args) {
        return r;
    }
    match name {
        // Node's DEFAULT `Error.prepareStackTrace`: the `Name: message` header
        // followed by one `    at <site>` line per call site. Reachable because
        // the read hands the hook out, and a library may call it directly to
        // render a stack it captured.
        DEFAULT_PREPARE => {
            let err = arg0(&args);
            let header = with_host(|h| {
                let name = host::lookup_chain(h, &err, "name")
                    .map(|v| h.str_of(&v))
                    .unwrap_or_else(|| "Error".to_string());
                let msg = host::lookup_chain(h, &err, "message")
                    .map(|v| h.str_of(&v))
                    .unwrap_or_default();
                if msg.is_empty() {
                    name
                } else {
                    format!("{name}: {msg}")
                }
            });
            let sites = args.get(1).cloned().unwrap_or(Value::Undef);
            let lines = with_host(|h| match h.get(&sites) {
                Some(JsObj::Array(items)) => items.clone(),
                _ => Vec::new(),
            });
            let mut out = header;
            for s in lines {
                let rendered = host::to_string_value(&s)
                    .map(|v| with_host(|h| h.str_of(&v)))
                    .unwrap_or_default();
                out.push_str("\n    at ");
                out.push_str(&rendered);
            }
            Ok(with_host(|h| h.new_str(out)))
        }
        "console.log" | "console.info" | "console.debug" => {
            print_line(&args, false)?;
            Ok(Value::Undef)
        }
        "console.error" | "console.warn" => {
            print_line(&args, true)?;
            Ok(Value::Undef)
        }
        "parseInt" | "Number.parseInt" => Ok(Value::Float(parse_int(&args)?)),
        "parseFloat" | "Number.parseFloat" => Ok(Value::Float(parse_float(&args)?)),
        // `isNaN`/`isFinite` are `ToNumber(x)` too (19.2.3/4).
        "isNaN" => Ok(Value::Bool(to_number_arg(&args, 0)?.is_nan())),
        "isFinite" => Ok(Value::Bool(to_number_arg(&args, 0)?.is_finite())),
        "encodeURIComponent" => uri_encode(&arg_to_string(&args, 0)?, false),
        "encodeURI" => uri_encode(&arg_to_string(&args, 0)?, true),
        "decodeURIComponent" => uri_decode(&arg_to_string(&args, 0)?, false),
        "decodeURI" => uri_decode(&arg_to_string(&args, 0)?, true),
        "escape" => legacy_escape(&with_host(|h| h.str_of(&arg0(&args)))),
        "unescape" => legacy_unescape(&with_host(|h| h.str_of(&arg0(&args)))),
        // Reaching `eval` through this table means the eval FUNCTION VALUE was
        // called — `(0, eval)(src)`, `const e = eval; e(src)`, `[eval][0](src)`.
        // Those are INDIRECT evals and run in the global scope. A literal
        // `eval(src)` is intercepted earlier, in `host::call_named`.
        "eval" => eval_source(args.first(), false),
        // `new Function(...)` and `Function(...)` are the same operation
        // (20.2.1.1 `CreateDynamicFunction` is reached from both [[Call]] and
        // [[Construct]]), so both route to the one generator.
        "Function" => function_ctor(&args),
        // `Buffer(arg[, encodingOrOffset[, length]])` — the deprecated call form
        // (DEP0005). Node still supports it and still routes it to the same place
        // `new Buffer` goes, which is why `safe-buffer`'s legacy `SafeBuffer`
        // wrapper is just `return Buffer(arg, encodingOrOffset, length)`. Measured
        // on node v26.7.0: `Buffer('abc').toString() === 'abc'`,
        // `Buffer([1,2]).toString('hex') === '0102'`, `Buffer(3).length === 3`.
        // Node emits DEP0005 once, on stderr, through the same one-shot machinery
        // `url.parse`'s DEP0169 uses, so this does too rather than staying silent
        // where Node warns.
        "Buffer" => {
            crate::stdlib::process::emit_deprecation_warning(
                "DEP0005",
                "Buffer() is deprecated due to security and usability issues. \
                 Please use the Buffer.alloc(), Buffer.allocUnsafe(), or \
                 Buffer.from() methods instead.",
            );
            crate::stdlib::construct("Buffer", &args)
                .unwrap_or_else(|| Err(host::type_error("Buffer is not a function")))
        }
        "Number.isInteger" => Ok(Value::Bool(is_integer(arg0(&args)))),
        "Number.isSafeInteger" => Ok(Value::Bool(is_safe_integer(arg0(&args)))),
        "Number.isNaN" => Ok(Value::Bool(
            matches!(arg0(&args), Value::Float(f) if f.is_nan()),
        )),
        "Number.isFinite" => Ok(Value::Bool(
            matches!(arg0(&args), Value::Float(f) if f.is_finite())
                || matches!(arg0(&args), Value::Int(_)),
        )),
        "String" => {
            if args.is_empty() {
                Ok(with_host(|h| h.new_str("")))
            } else {
                // A symbol argument stringifies to `Symbol(desc)` (explicit String()
                // is allowed); everything else via ToString method dispatch.
                host::string_ctor_value(&args[0])
            }
        }
        // `Number(v)` is NOT plain ToNumber: 21.1.1.1 step 2 converts the object
        // first and then explicitly ACCEPTS a BigInt, returning its mathematical
        // value as a Number. Only `Number` does — `+v` and `Math.abs(v)` reject
        // one — which is why this cannot just call `to_number_value`.
        "Number" => Ok(Value::Float(if args.is_empty() {
            0.0
        } else {
            let prim = host::to_primitive(&args[0], "number")?;
            match with_host(|h| h.as_bigint(&prim)) {
                Some(b) => host::bigint_to_f64(&b),
                None => host::to_number_value(&prim)?,
            }
        })),
        "BigInt" => bigint_ctor(&arg0(&args)),
        "RegExp" => regexp_ctor(&args),
        "BigInt.asIntN" | "BigInt.asUintN" => bigint_as_n(name.ends_with("asUintN"), &args),
        "Boolean" => Ok(Value::Bool(with_host(|h| h.truthy(&arg0(&args))))),
        // Each argument is truncated to a uint16 and taken as one code UNIT, so
        // `String.fromCharCode(0x1D4B3)` is U+D4B3, NOT the astral U+1D4B3, and
        // a surrogate PAIR of arguments composes into one character.
        "String.fromCharCode" => Ok(with_host(|h| {
            let units: Vec<u16> = args
                .iter()
                .map(|a| crate::utf16::to_uint16(h.to_number(a)))
                .collect();
            let s = crate::utf16::to_string_lossy(&units);
            h.new_str(s)
        })),
        // `fromCodePoint` takes whole code POINTS and rejects anything that is
        // not one — including a lone surrogate, which `fromCharCode` accepts.
        "String.fromCodePoint" => {
            let mut s = String::new();
            for a in &args {
                let n = with_host(|h| h.to_number(a));
                let cp = if n.is_finite() && n.trunc() == n && (0.0..=0x10FFFF as f64).contains(&n)
                {
                    char::from_u32(n as u32)
                } else {
                    None
                };
                match cp {
                    Some(c) => s.push(c),
                    None => {
                        return Err(format!(
                            "RangeError: Invalid code point {}",
                            with_host(|h| h.str_of(a))
                        ))
                    }
                }
            }
            Ok(new_s(s))
        }
        "String.raw" => string_raw(&args),
        // `Array(5)` === `new Array(5)` (length-5 empty), but `Array.of(5)` is `[5]`.
        "Array" => construct_builtin("Array", args),
        "Array.of" => construct_array_like(host::current_static_this(), args),
        // 23.1.2.2 `IsArray` follows a Proxy to its `[[ProxyTarget]]` rather than
        // consulting any trap, so `Array.isArray(new Proxy([], {}))` is `true`.
        "Array.isArray" => {
            let v = arg0(&args);
            let subject = crate::proxy::ultimate_target(&v).unwrap_or(v);
            Ok(Value::Bool(
                matches!(
                    with_host(|h| h.get(&subject).cloned()),
                    Some(JsObj::Array(_))
                ) && !is_arguments(&subject),
            ))
        }
        "Array.from" => array_from(args),
        "Array.fromAsync" => array_from_async(args),
        "Object" => Ok(object_call(args)),
        "Object.keys" => object_keys(args, 0),
        "Object.values" => object_keys(args, 1),
        "Object.entries" => object_keys(args, 2),
        "Object.assign" => object_assign(args),
        "Object.freeze" => {
            let v = arg0(&args);
            reject_sealing_a_view(&v, "freeze")?;
            if seal_proxy(&v, true)? {
                return Ok(v);
            }
            with_host(|h| h.seal_object(&v, true));
            Ok(v)
        }
        "Object.seal" => {
            let v = arg0(&args);
            reject_sealing_a_view(&v, "seal")?;
            if seal_proxy(&v, false)? {
                return Ok(v);
            }
            with_host(|h| h.seal_object(&v, false));
            Ok(v)
        }
        "Object.preventExtensions" => {
            let v = arg0(&args);
            if crate::proxy::prevent_extensions(&v)? {
                return Ok(v);
            }
            with_host(|h| h.prevent_extensions(&v));
            Ok(v)
        }
        // A PRIMITIVE has no integrity to speak of and 7.3.15/16 answer for it
        // without coercion: it is not extensible, and vacuously frozen and
        // sealed. Reporting it extensible and unfrozen was the opposite of
        // every one of the three.
        "Object.isFrozen" if is_primitive_arg(&args) => Ok(Value::Bool(true)),
        "Object.isSealed" if is_primitive_arg(&args) => Ok(Value::Bool(true)),
        "Object.isExtensible" if is_primitive_arg(&args) => Ok(Value::Bool(false)),
        "Object.isFrozen" => integrity_level(&arg0(&args), true),
        "Object.isSealed" => integrity_level(&arg0(&args), false),
        "Object.isExtensible" => {
            let v = arg0(&args);
            match crate::proxy::is_extensible(&v)? {
                Some(b) => Ok(Value::Bool(b)),
                None => Ok(Value::Bool(with_host(|h| h.is_extensible(&v)))),
            }
        }
        // Object.is — SameValue: like `===` but NaN is equal to NaN and +0 is
        // distinct from -0.
        "Object.is" => {
            let a = arg0(&args);
            let b = args.get(1).cloned().unwrap_or(Value::Undef);
            let num = |v: &Value| match v {
                Value::Int(n) => Some(*n as f64),
                Value::Float(f) => Some(*f),
                _ => None,
            };
            let r = match (num(&a), num(&b)) {
                (Some(x), Some(y)) => {
                    if x.is_nan() && y.is_nan() {
                        true
                    } else if x == 0.0 && y == 0.0 {
                        x.is_sign_negative() == y.is_sign_negative()
                    } else {
                        x == y
                    }
                }
                _ => with_host(|h| h.strict_eq(&a, &b)),
            };
            Ok(Value::Bool(r))
        }
        "Object.fromEntries" => object_from_entries(args),
        // `[[GetPrototypeOf]]`: a Proxy answers from its trap (which may throw),
        // so the proxy form cannot share `prototype_of`'s infallible signature.
        // `Object.getPrototypeOf` coerces a primitive to its wrapper and
        // answers; `Reflect.getPrototypeOf` requires an object (28.1.8).
        "Object.getPrototypeOf" | "Reflect.getPrototypeOf" => {
            if name == "Reflect.getPrototypeOf" {
                reflect_require_object(&arg0(&args), "getPrototypeOf")?;
            }
            let v = arg0(&args);
            match crate::proxy::get_prototype_of(&v)? {
                Some(p) => Ok(p),
                None => Ok(prototype_of(&v)),
            }
        }
        "Object.setPrototypeOf" => {
            let obj = arg0(&args);
            let proto = args.get(1).cloned().unwrap_or(Value::Undef);
            if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
                reject_bad_prototype(&proto)?;
                crate::proxy::set_prototype_of(&obj, &proto)?;
                return Ok(obj);
            }
            // 20.1.2.23: `RequireObjectCoercible` on the target, then the
            // prototype type check, then — only for an actual object target —
            // the extensibility check. A PRIMITIVE target is returned untouched
            // (`Object.setPrototypeOf(1, {})` is `1`), which is why the
            // extensibility test cannot come first.
            if with_host(|h| matches!(obj, Value::Undef) || h.is_null(&obj)) {
                return Err(host::type_error(
                    "Object.setPrototypeOf called on null or undefined",
                ));
            }
            reject_bad_prototype(&proto)?;
            if with_host(|h| is_object_like(h, &obj)) {
                // Setting the SAME prototype is a no-op and stays legal even on a
                // frozen object: node v26.7.0 accepts
                // `Object.setPrototypeOf(Object.freeze({}), Object.prototype)`.
                // `prototype_of`, not `proto_of`: an object with no EXPLICIT
                // link still has `Object.prototype`, and comparing against the
                // absent link would call that a change.
                if would_cycle(&obj, &proto) {
                    return Err(host::type_error("Cyclic __proto__ value"));
                }
                if !same_prototype(&obj, &proto) && !with_host(|h| h.is_extensible(&obj)) {
                    // The receiver is named by its brand, as every other
                    // refusal names it — a NULL-PROTOTYPE object is
                    // `[object Object]`, not `#<Object>`, because it has no
                    // constructor to name.
                    return Err(host::type_error(&format!(
                        "{} is not extensible",
                        no_side_effects_string(&obj)
                    )));
                }
                with_host(|h| h.set_proto(&obj, proto));
            }
            Ok(obj)
        }
        "Object.create" => object_create(args),
        "Object.getOwnPropertyNames" => object_keys(args, 3),
        "Object.getOwnPropertySymbols" => {
            let v = arg0(&args);
            require_object_coercible(&v)?;
            let syms = proxy_or_own_symbol_keys(&v)?;
            Ok(with_host(|h| h.new_array(syms)))
        }
        // `Object.hasOwn(obj, key)` — the static form of `hasOwnProperty`.
        "Object.hasOwn" => {
            let obj = arg0(&args);
            let key = args.get(1).cloned().unwrap_or(Value::Undef);
            object_builtin_method(&obj, "hasOwnProperty", vec![key])
        }
        "Object.defineProperty" => object_define_property(args),
        "Object.getOwnPropertyDescriptor" => object_get_own_descriptor(args),
        "Object.getOwnPropertyDescriptors" => object_get_own_descriptors(args),
        "Object.defineProperties" => object_define_properties(args),
        // `Object.groupBy(items, cb)` (ES2024): group into a null-prototype object
        // keyed by `ToPropertyKey(cb(item, i))`, each value an array of members.
        "Object.groupBy" => object_group_by(args),
        "Symbol" => Ok(with_host(|h| {
            let desc = args
                .first()
                .filter(|a| !matches!(a, Value::Undef))
                .map(|a| h.str_of(a));
            h.new_symbol(desc)
        })),
        "Symbol.for" => Ok(with_host(|h| {
            let key = h.str_of(&arg0(&args));
            h.symbol_for(&key)
        })),
        // `Symbol.keyFor(sym)` (20.4.2.6) is a REGISTRY lookup, not a
        // description read: it answers only for symbols `Symbol.for` created.
        // Returning the description made every symbol look registered —
        // `Symbol.keyFor(Symbol("k"))` was `"k"` where node says `undefined`.
        "Symbol.keyFor" => Ok(with_host(|h| h.symbol_registry_key(&arg0(&args)))),
        "Map" | "WeakMap" | "Set" | "WeakSet" | "Promise" => construct_builtin(name, args),
        // `Proxy` has no `[[Call]]` slot: it is constructor-only (28.2.1).
        "Proxy" => Err(host::type_error("Constructor Proxy requires 'new'")),
        "Proxy.revocable" => crate::proxy::revocable(&args),
        // `Reflect.ownKeys` reports EVERY own key, non-enumerable included —
        // the same set as `getOwnPropertyNames` (node-js has no symbol-keyed
        // own properties, so there is no second half to append).
        // `Reflect.ownKeys` is `OwnPropertyKeys` (7.3.23): every own key,
        // non-enumerable included, strings first and then the SYMBOLS.
        "Reflect.ownKeys" => {
            let v = arg0(&args);
            reflect_require_object(&v, "ownKeys")?;
            let names = object_keys(args, 3)?;
            let syms = proxy_or_own_symbol_keys(&v)?;
            if syms.is_empty() {
                return Ok(names);
            }
            let mut all = with_host(|h| h.iter_vec(&names)).unwrap_or_default();
            all.extend(syms);
            Ok(with_host(|h| h.new_array(all)))
        }
        "Reflect.getOwnPropertyDescriptor" => object_get_own_descriptor(args),
        // `Reflect.defineProperty` REPORTS success as a boolean where
        // `Object.defineProperty` throws (28.1.3). It was propagating the
        // throw, so the whole point of the reflective form was lost.
        "Reflect.defineProperty" => {
            reflect_require_object(&arg0(&args), "defineProperty")?;
            Ok(Value::Bool(object_define_property(args).is_ok()))
        }
        "Reflect.deleteProperty" => {
            let obj = arg0(&args);
            reflect_require_object(&obj, "deleteProperty")?;
            let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
            Ok(Value::Bool(delete_property(&obj, &k)?))
        }
        "Reflect.setPrototypeOf" => {
            let obj = arg0(&args);
            let p = args.get(1).cloned().unwrap_or(Value::Undef);
            if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
                crate::proxy::set_prototype_of(&obj, &p)?;
                return Ok(Value::Bool(true));
            }
            // 10.1.2.1: a NON-EXTENSIBLE object refuses a prototype change —
            // unless the new one is what it already has, which is a no-op. It
            // reported success and rewrote the link.
            // `Reflect` reports a refusal rather than throwing, for a cycle as
            // for a non-extensible receiver.
            if would_cycle(&obj, &p) {
                return Ok(Value::Bool(false));
            }
            if !with_host(|h| h.is_extensible(&obj)) {
                return Ok(Value::Bool(same_prototype(&obj, &p)));
            }
            with_host(|h| h.set_proto(&obj, p));
            Ok(Value::Bool(true))
        }
        "Reflect.isExtensible" => {
            let v = arg0(&args);
            match crate::proxy::is_extensible(&v)? {
                Some(b) => Ok(Value::Bool(b)),
                None => Ok(Value::Bool(with_host(|h| h.is_extensible(&v)))),
            }
        }
        "Reflect.preventExtensions" => {
            let v = arg0(&args);
            if crate::proxy::prevent_extensions(&v)? {
                return Ok(Value::Bool(true));
            }
            with_host(|h| h.prevent_extensions(&v));
            Ok(Value::Bool(true))
        }
        // `Reflect.apply(target, thisArg, argsList)` / `Reflect.construct(t, a)`.
        "Reflect.apply" => {
            let f = arg0(&args);
            let this = args.get(1).cloned();
            let list = create_list_from_array_like(&args.get(2).cloned().unwrap_or(Value::Undef))?;
            host::invoke(&f, list, this.filter(|t| !with_host(|h| h.is_nullish(t))))
        }
        // `Reflect.construct(target, args, newTarget)` — the optional third
        // argument decides which constructor's `prototype` the instance gets
        // (28.1.2). It was ignored, so the result always inherited from
        // `target` and `instanceof newTarget` was false.
        "Reflect.construct" => {
            let f = arg0(&args);
            let list = create_list_from_array_like(&args.get(1).cloned().unwrap_or(Value::Undef))?;
            let new_target = args.get(2).cloned().unwrap_or_else(|| f.clone());
            host::construct_nt(&f, list, new_target)
        }
        "Reflect.has" => {
            let obj = arg0(&args);
            reflect_require_object(&obj, "has")?;
            let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
            Ok(Value::Bool(has_property(&obj, &k)?))
        }
        // `Reflect.get(target, key, receiver)` — the optional third argument is
        // what a getter sees as `this` (28.1.6). Defaults to the target.
        "Reflect.get" => {
            let obj = arg0(&args);
            reflect_require_object(&obj, "get")?;
            let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
            let receiver = args.get(2).cloned().unwrap_or_else(|| obj.clone());
            get_property_recv(&obj, &k, &receiver)
        }
        // `Reflect.set(target, key, value, receiver)` — the optional fourth
        // argument is what a setter sees as `this`, and where a DATA property
        // lands (28.1.13). It was ignored: the setter ran against the target
        // and the property was written there.
        "Reflect.set" => {
            let obj = arg0(&args);
            reflect_require_object(&obj, "set")?;
            let k = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
            let v = args.get(2).cloned().unwrap_or(Value::Undef);
            let receiver = args.get(3).cloned().unwrap_or_else(|| obj.clone());
            Ok(Value::Bool(set_with_receiver(&obj, &k, v, &receiver)?))
        }
        "JSON.stringify" => json_stringify(args),
        "JSON.parse" => json_parse(args),
        "JSON.rawJSON" => json_raw(args),
        "JSON.isRawJSON" => json_is_raw(args),
        "structuredClone" => structured_clone(args),
        // The deferred drain a `Readable.from` schedules; the suffix is the
        // stream's heap index.
        _ if name.starts_with("@@transformCb:") => {
            let idx: u32 = name["@@transformCb:".len()..].parse().unwrap_or(0);
            crate::stdlib::stream::transform_callback(&Value::Obj(idx), &args)?;
            Ok(Value::Undef)
        }
        _ if name.starts_with("@@streamFlush:") => {
            let idx: u32 = name["@@streamFlush:".len()..].parse().unwrap_or(0);
            crate::stdlib::stream::flush_from(&Value::Obj(idx))?;
            Ok(Value::Undef)
        }
        // Same implementation the `buffer` module exposes; only the binding was
        // missing.
        "btoa" | "atob" => crate::stdlib::buffer::module_call(name, &args)
            .unwrap_or_else(|| Err(host::type_error(&format!("{name} is not a function")))),
        "fetch" => crate::stdlib::fetch::fetch(&args),
        // An `AbortSignal.timeout` deadline reached its macrotask: the thunk's
        // suffix is the signal's heap index.
        _ if name.starts_with("@@aborttimeout:") => {
            let idx: u32 = name["@@aborttimeout:".len()..].parse().unwrap_or(0);
            crate::stdlib::fetch::fire_timeout_abort(idx)
        }
        // The `callback` handed to a `new Writable({ write(chunk, enc, cb) })`
        // implementation. Nothing here waits on backpressure, so it only has to
        // BE callable — an implementation that ends with `cb()`, which the
        // stream contract requires, would otherwise throw.
        "@@streamWriteCallback" => Ok(Value::Undef),
        "queueMicrotask" | "process.nextTick" => {
            let cb = arg0(&args);
            require_callback(&cb)?;
            let rest = args.get(1..).map(|s| s.to_vec()).unwrap_or_default();
            enqueue_microtask(name == "process.nextTick", cb, rest);
            Ok(Value::Undef)
        }
        "setTimeout" | "setInterval" | "setImmediate" => {
            require_callback(&arg0(&args))?;
            Ok(schedule_timer(name, args))
        }
        "clearTimeout" | "clearInterval" | "clearImmediate" => {
            clear_timer(&arg0(&args));
            Ok(Value::Undef)
        }
        "Promise.resolve" => promise_resolve(arg0(&args)),
        "Promise.reject" => promise_reject(arg0(&args)),
        "Promise.all" => promise_all(args, AllMode::All),
        "Promise.allSettled" => promise_all(args, AllMode::AllSettled),
        "Promise.race" => promise_race(args, false),
        "Promise.any" => promise_race(args, true),
        // `Promise.withResolvers()` (ES2024): a new pending promise plus its own
        // resolve/reject functions, returned as `{ promise, resolve, reject }`.
        "Promise.withResolvers" => promise_with_resolvers(),
        "Promise.try" => promise_try(args),
        "RegExp.escape" => regexp_escape(args),
        "Error.isError" => error_is_error(args),
        // `Map.groupBy(items, cb)` (ES2024): group into a `Map` keyed by the raw
        // `cb(item, i)` result (SameValueZero), each value an array of members.
        "Map.groupBy" => map_group_by(args),
        n if host::ERROR_NAMES.contains(&n) => make_error_checked(name, &args),
        _ if name.starts_with("Math.") => math_fn(&name[5..], &args),
        // Internal continuations (Promise resolve/reject fns, `.finally` wrappers).
        // The executor a species-constructed promise is built with: it does
        // nothing, because the caller settles the result through its id.
        "@@pnoop" => Ok(Value::Undef),
        _ if name.starts_with("@@presolve:") => {
            let id: u32 = name[11..].parse().unwrap_or(0);
            host::resolve_promise_val(id, arg0(&args));
            Ok(Value::Undef)
        }
        _ if name.starts_with("@@preject:") => {
            let id: u32 = name[10..].parse().unwrap_or(0);
            host::reject_promise_val(id, arg0(&args));
            Ok(Value::Undef)
        }
        // The revoker `Proxy.revocable` hands back, keyed by the proxy's heap
        // index so calling it twice is the spec's no-op rather than a re-tear.
        _ if name.starts_with("@@prevoke:") => {
            let i: u32 = name[10..].parse().unwrap_or(0);
            Ok(crate::proxy::revoke(i))
        }
        _ if name.starts_with("@@finpass:") => {
            // finally(cb) on fulfill: run cb, await whatever it returned, then
            // pass the original value through.
            let i: u32 = name["@@finpass:".len()..].parse().unwrap_or(0);
            let result = host::invoke(&Value::Obj(i), Vec::new(), None)?;
            Ok(finally_chain(result, arg0(&args), false))
        }
        _ if name.starts_with("@@finthrow:") => {
            // finally(cb) on reject: same, then re-throw the original reason.
            let i: u32 = name["@@finthrow:".len()..].parse().unwrap_or(0);
            let result = host::invoke(&Value::Obj(i), Vec::new(), None)?;
            Ok(finally_chain(result, arg0(&args), true))
        }
        // The two thunks `finally_chain` hangs off that awaited promise. Each
        // carries the value it must reinstate in a one-slot cell, since a
        // builtin is identified only by its name and cannot close over one.
        _ if name.starts_with("@@finret:") => {
            let i: u32 = name["@@finret:".len()..].parse().unwrap_or(0);
            get_property(&Value::Obj(i), "0")
        }
        _ if name.starts_with("@@finrethrow:") => {
            let i: u32 = name["@@finrethrow:".len()..].parse().unwrap_or(0);
            let reason = get_property(&Value::Obj(i), "0")?;
            with_host(|h| h.exc = Some(reason.clone()));
            Err(with_host(|h| error_string(h, &reason)))
        }
        _ => Err(host::type_error(&format!("{name} is not a function"))),
    }
}

/// `BigInt(x)`: convert a boolean/number/string/bigint to a BigInt. A
/// non-integer number is a `RangeError`; an unparseable string a `SyntaxError`
/// (matching Node's messages).
/// V8 names the offending value: `BigInt(undefined)` is `Cannot convert
/// undefined to a BigInt`, `BigInt({})` is `Cannot convert [object Object] to a
/// BigInt`. The old text said "value" literally, for every input.
fn bigint_convert_error(v: &Value) -> String {
    let shown = with_host(|h| h.str_of(v));
    host::type_error(&format!("Cannot convert {shown} to a BigInt"))
}

/// `ToBigInt(v)` — 7.1.13. The conversion every BigInt-typed SINK performs: a
/// 64-bit typed array's element write, `DataView.prototype.setBigInt64`, and
/// BigInt arithmetic's operand check.
///
/// It is NOT `BigInt(v)`: a Number is a `TypeError` here (`BigInt(1)` is `1n`,
/// but `new BigInt64Array(1)[0] = 1` throws), which is the whole point of the
/// separate abstract op. Everything else follows `ToPrimitive(v, number)` then
/// the type table — booleans convert (`true` → `1n`), strings parse with a
/// `SyntaxError` on failure, and `undefined`/`null`/symbols throw.
///
/// Measured on node v26.8.1, receiver `new BigInt64Array(1)`:
///
/// ```text
/// a[0] = true            → 1n
/// a[0] = '12'            → 12n
/// a[0] = []              → 0n        (ToPrimitive → "" → 0n)
/// a[0] = ['3']           → 3n
/// a[0] = 1               → TypeError: Cannot convert 1 to a BigInt
/// a[0] = new Number(3)   → TypeError: Cannot convert 3 to a BigInt
/// a[0] = 'a'             → SyntaxError: Cannot convert a to a BigInt
/// a[0] = {}              → SyntaxError: Cannot convert [object Object] to a BigInt
/// ```
pub fn to_bigint(v: &Value) -> Result<num_bigint::BigInt, String> {
    let prim = host::to_primitive(v, "number")?;
    if let Some(b) = with_host(|h| match h.get(&prim) {
        Some(JsObj::BigInt(b)) => Some(b.clone()),
        _ => None,
    }) {
        return Ok(b);
    }
    match &prim {
        Value::Bool(b) => Ok(num_bigint::BigInt::from(*b as i64)),
        Value::Str(s) => host::parse_bigint_str(s)
            .ok_or_else(|| format!("SyntaxError: Cannot convert {s} to a BigInt")),
        _ if with_host(|h| matches!(h.get(&prim), Some(JsObj::Str(_)))) => {
            let s = with_host(|h| h.str_of(&prim));
            host::parse_bigint_str(&s)
                .ok_or_else(|| format!("SyntaxError: Cannot convert {s} to a BigInt"))
        }
        _ => Err(bigint_convert_error(&prim)),
    }
}

fn bigint_ctor(v: &Value) -> Result<Value, String> {
    use num_bigint::BigInt;
    let big = match v {
        Value::Bool(b) => BigInt::from(*b as i64),
        Value::Int(n) => BigInt::from(*n),
        Value::Float(f) => {
            if !f.is_finite() || f.fract() != 0.0 {
                let disp = with_host(|h| h.str_of(v));
                return Err(format!(
                    "RangeError: The number {disp} cannot be converted to a BigInt because it is not an integer"
                ));
            }
            // The decimal EXPANSION, not `fmt_number`: `Number.prototype
            // .toString` switches to exponential notation at 1e21, and
            // `BigInt::parse_bytes` cannot read `"1e+21"` — so `BigInt(1e21)`
            // threw `Cannot convert value to a BigInt` where node returns
            // `1000000000000000000000n`. `{:.0}` prints an integral f64's exact
            // value, which is also what node reports for a magnitude past the
            // exactly-representable range (`BigInt(1e30)` is
            // `1000000000000000019884624838656n` in both).
            match BigInt::parse_bytes(format!("{f:.0}").as_bytes(), 10) {
                Some(b) => b,
                None => return Err(bigint_convert_error(v)),
            }
        }
        Value::Str(s) => match host::parse_bigint_str(s) {
            Some(b) => b,
            None => return Err(format!("SyntaxError: Cannot convert {s} to a BigInt")),
        },
        Value::Obj(_) => match with_host(|h| h.get(v).cloned()) {
            Some(JsObj::BigInt(b)) => b,
            Some(JsObj::Str(s)) => match host::parse_bigint_str(&s) {
                Some(b) => b,
                None => return Err(format!("SyntaxError: Cannot convert {s} to a BigInt")),
            },
            _ => return Err(bigint_convert_error(v)),
        },
        _ => return Err(bigint_convert_error(v)),
    };
    Ok(with_host(|h| h.new_bigint(big)))
}

/// `new RegExp(source[, flags])` / `RegExp(...)`. A first `RegExp` argument copies
/// its source (and flags, unless new ones are given).
fn regexp_ctor(args: &[Value]) -> Result<Value, String> {
    let (source, existing_flags) = match with_host(|h| h.get(&arg0(args)).cloned()) {
        Some(JsObj::RegExp(r)) => (r.source.clone(), Some(r.flags.clone())),
        _ => {
            let a0 = arg0(args);
            // 22.2.4.1 step 9 is `ToString(pattern)`, which a SYMBOL refuses —
            // `new RegExp(sym)` was compiling the text `Symbol(d)` into a
            // pattern instead of throwing.
            let src = if matches!(a0, Value::Undef) {
                String::new()
            } else {
                arg_to_string(args, 0)?
            };
            (src, None)
        }
    };
    let flags = match args.get(1) {
        Some(v) if !matches!(v, Value::Undef) => arg_to_string(args, 1)?,
        _ => existing_flags.unwrap_or_default(),
    };
    // An empty source compiles as the JS canonical `(?:)`.
    let src = if source.is_empty() {
        "(?:)".to_string()
    } else {
        source
    };
    crate::regexp::build_regexp(&src, &flags)
}

/// `BigInt.asIntN(bits, x)` / `BigInt.asUintN(bits, x)`: wrap `x` to a `bits`-wide
/// two's-complement (signed) or unsigned integer.
fn bigint_as_n(unsigned: bool, args: &[Value]) -> Result<Value, String> {
    use num_bigint::BigInt;
    use num_traits::Signed;
    let bits = with_host(|h| h.to_number(&arg0(args))) as i64;
    if bits < 0 {
        return Err("RangeError: Invalid value: not (convertible to) a safe integer".into());
    }
    let x = match with_host(|h| h.as_bigint(&args.get(1).cloned().unwrap_or(Value::Undef))) {
        Some(b) => b,
        None => return Err(host::type_error("Cannot convert to a BigInt")),
    };
    let bits = bits as u32;
    if bits == 0 {
        return Ok(with_host(|h| h.new_bigint(BigInt::from(0))));
    }
    let modulus = BigInt::from(1) << bits; // 2^bits
                                           // Reduce into [0, 2^bits); for the signed form fold the top half negative.
    let mut r = &x % &modulus;
    if r.is_negative() {
        r += &modulus;
    }
    if !unsigned {
        let half = BigInt::from(1) << (bits - 1);
        if r >= half {
            r -= &modulus;
        }
    }
    Ok(with_host(|h| h.new_bigint(r)))
}

/// `String.raw(callSite, ...subs)`: concatenate the raw quasis (`callSite.raw`)
/// interleaved with the substitutions.
fn string_raw(args: &[Value]) -> Result<Value, String> {
    let call_site = arg0(args);
    let raw = get_property(&call_site, "raw")?;
    let raws = with_host(|h| h.iter_vec(&raw)).unwrap_or_default();
    let mut out = String::new();
    for (i, r) in raws.iter().enumerate() {
        out.push_str(&with_host(|h| h.str_of(r)));
        if i + 1 < raws.len() {
            if let Some(sub) = args.get(i + 1) {
                out.push_str(&with_host(|h| h.str_of(sub)));
            }
        }
    }
    Ok(with_host(|h| h.new_str(out)))
}

/// `Object(x)`: box/pass-through — for our model, non-object args just return a
/// fresh object; objects pass through.
/// Whether `v`'s own properties live in the fn-prop SIDE TABLE rather than in a
/// property map. A `Map`/`Set`/`Promise`/`RegExp`/generator/symbol/bigint is an
/// ordinary object that also has internal slots, so it can carry own properties
/// like anything else — but its heap variant holds only those slots, so a write
/// had nowhere to go and vanished: `m.x = 5` left `m.x` undefined.
pub fn uses_side_table(v: &Value) -> bool {
    matches!(
        with_host(|h| h.kind_of(v)),
        Some(
            ObjKind::Map
                | ObjKind::Set
                | ObjKind::Promise
                | ObjKind::RegExp
                | ObjKind::Generator
                | ObjKind::Symbol
                | ObjKind::BigInt
                | ObjKind::Iter
        )
    )
}

fn object_call(args: Vec<Value>) -> Value {
    let a = arg0(&args);
    // `Object(v)` is `ToObject(v)` (20.1.1.1): a primitive comes back BOXED,
    // not replaced by an empty object. `Object(1).valueOf()` was `undefined`.
    if matches!(a, Value::Undef) || with_host(|h| h.is_null(&a)) {
        return with_host(|h| h.new_object(IndexMap::new()));
    }
    to_object(&a)
}

/// The name of the wrapper a primitive boxes into, or `None` when the value is
/// already an object.
fn wrapper_ctor_of(v: &Value) -> Option<&'static str> {
    match v {
        Value::Int(_) | Value::Float(_) => Some("Number"),
        Value::Bool(_) => Some("Boolean"),
        Value::Obj(_) => match with_host(|h| h.get(v).cloned()) {
            Some(JsObj::Str(_)) => Some("String"),
            Some(JsObj::Symbol { .. }) => Some("Symbol"),
            Some(JsObj::BigInt(_)) => Some("BigInt"),
            _ => None,
        },
        _ => None,
    }
}

/// The primitive a wrapper object boxes (`new String("a")` → `"a"`), or `None`
/// for every other value. The slot is a hidden `@@primitive` own property —
/// the same `@@` marker convention the engine already uses for internal state,
/// so it stays out of `Object.keys` and `JSON.stringify` on its own.
pub fn wrapped_primitive(v: &Value) -> Option<Value> {
    with_host(|h| match h.get(v) {
        Some(JsObj::Object(p)) => p.get("@@primitive").cloned(),
        _ => None,
    })
}

/// `ToObject(v)` (7.1.18) for a primitive: the wrapper object with the matching
/// prototype and a `[[StringData]]`/`[[NumberData]]`/`[[BooleanData]]` slot.
///
/// A String wrapper also owns its index properties and `length`, which is what
/// makes `w[0]`, `w.length` and `Object.keys(w)` answer; all of them are
/// non-writable and non-configurable, as the exotic `String` object's are.
pub fn to_object(v: &Value) -> Value {
    let Some(ctor) = wrapper_ctor_of(v) else {
        return v.clone();
    };
    with_host(|h| h.ensure_wrapper_protos());
    let chars: Vec<String> = if ctor == "String" {
        with_host(|h| h.str_of(v))
            .chars()
            .map(|c| c.to_string())
            .collect()
    } else {
        Vec::new()
    };
    with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        for (i, c) in chars.iter().enumerate() {
            let s = h.new_str(c.clone());
            m.insert(i.to_string(), s);
        }
        let w = h.new_object(m);
        if ctor == "String" {
            for i in 0..chars.len() {
                h.set_prop_attrs(
                    &w,
                    &i.to_string(),
                    host::PropAttrs {
                        writable: false,
                        enumerable: true,
                        configurable: false,
                    },
                );
            }
            let len = Value::Float(chars.len() as f64);
            if let Some(JsObj::Object(p)) = h.get_mut(&w) {
                p.insert("length".into(), len);
            }
            h.set_prop_attrs(
                &w,
                "length",
                host::PropAttrs {
                    writable: false,
                    enumerable: false,
                    configurable: false,
                },
            );
        }
        if let Some(JsObj::Object(p)) = h.get_mut(&w) {
            p.insert("@@primitive".into(), v.clone());
        }
        if let Some(proto) = h.native_proto(ctor) {
            h.set_proto(&w, proto);
        }
        w
    })
}

/// Construct via `new` for the builtin constructors.
pub fn construct_builtin(name: &str, args: Vec<Value>) -> Result<Value, String> {
    // Native stdlib constructors (`new URL(...)`, `new EventEmitter()`, `new Buffer(...)`).
    if let Some(r) = crate::stdlib::construct(name, &args) {
        return r;
    }
    match name {
        "Array" => {
            // `new Array(n)` -> length-n array; `new Array(a, b)` -> [a, b].
            // A single NUMBER argument is a length and is validated as one
            // (23.1.1.1 step 6), so `new Array(-1)` / `new Array(1.5)` /
            // `new Array(2**32)` are all `RangeError: Invalid array length` on
            // node v26.7.0; only a non-number single argument is an element.
            if args.len() == 1 {
                if let Value::Float(_) | Value::Int(_) = args[0] {
                    let n = host::to_array_length(&args[0])?;
                    // Every element of `new Array(n)` is a HOLE, not a stored
                    // `undefined`: `Object.keys(Array(3))` is `[]`.
                    return Ok(with_host(|h| {
                        let a = h.new_array(vec![Value::Undef; n]);
                        h.mark_hole_range(&a, 0..n);
                        a
                    }));
                }
            }
            Ok(with_host(|h| h.new_array(args)))
        }
        "Object" => Ok(object_call(args)),
        // `new String(v)` / `new Number(v)` / `new Boolean(v)` — the wrapper
        // form. These were not constructors at all, so every one threw.
        "String" => Ok(to_object(&host::to_string_value(
            &args
                .first()
                .cloned()
                .unwrap_or_else(|| with_host(|h| h.new_str(String::new()))),
        )?)),
        "Number" => Ok(to_object(&Value::Float(match args.first() {
            Some(a) => host::to_number_value(a)?,
            None => 0.0,
        }))),
        "Boolean" => Ok(to_object(&Value::Bool(with_host(|h| {
            h.truthy(&arg0(&args))
        })))),
        "Map" | "WeakMap" => {
            let weak = name == "WeakMap";
            let m = with_host(|h| {
                h.alloc(JsObj::Map {
                    entries: indexmap::IndexMap::new(),
                    weak,
                })
            });
            if let Some(init) = args
                .first()
                .filter(|a| !matches!(a, Value::Undef) && !with_host(|h| h.is_null(a)))
            {
                // Stepped, not drained: an entry that is not a pair has to
                // stop the construction at that element and CLOSE the iterator
                // (24.1.1.2 step 8). Materializing first meant a bad entry in an
                // infinite source was never reached and the constructor HUNG.
                host::iter_for_each(init, |p, _| {
                    // 24.1.1.2 step 8.d: each entry must be an OBJECT. A string
                    // is iterable, so without this check `new Map(["ab"])`
                    // happily stored `'a' => 'b'` instead of throwing — and over
                    // an infinite source it never stopped.
                    if !with_host(|h| is_object_like(h, &p)) {
                        let shown = with_host(|h| h.str_of(&p));
                        return Err(host::type_error(&format!(
                            "Iterator value {shown} is not an entry object"
                        )));
                    }
                    // The entry is read by INDEX with `[[Get]]` (step 8.e), not
                    // iterated: an object with a `Symbol.iterator` but no `0`/`1`
                    // gives `undefined => undefined`, and an array-LIKE entry
                    // works. Iterating it instead accepted a string as a pair
                    // and rejected the array-like.
                    let k = get_property(&p, "0")?;
                    let v = get_property(&p, "1")?;
                    map_method(&m, "set", vec![k, v])?;
                    Ok(())
                })?;
            }
            Ok(m)
        }
        "Set" | "WeakSet" => {
            let weak = name == "WeakSet";
            let s = with_host(|h| {
                h.alloc(JsObj::Set {
                    entries: indexmap::IndexMap::new(),
                    weak,
                })
            });
            if let Some(init) = args
                .first()
                .filter(|a| !matches!(a, Value::Undef) && !with_host(|h| h.is_null(a)))
            {
                host::iter_for_each(init, |v, _| {
                    set_method(&s, "add", vec![v])?;
                    Ok(())
                })?;
            }
            Ok(s)
        }
        "Promise" => new_promise(arg0(&args)),
        "Proxy" => crate::proxy::create(&args),
        // `new Function(p…, body)` — the same `CreateDynamicFunction` the plain
        // call form runs (20.2.1.1). `depd`'s `wrapfunction` builds its
        // deprecation wrapper this way, so `require('body-parser')` — and with it
        // `require('express')` — dies at load without it.
        "Function" => function_ctor(&args),
        "RegExp" => regexp_ctor(&args),
        "BigInt" => Err(host::type_error("BigInt is not a constructor")),
        "Error" => make_error_checked(name, &args),
        // `new DOMException(message, name)` — the name is an ARGUMENT, and the
        // legacy numeric `code` follows from it.
        "DOMException" => Ok(dom_exception(&args)),
        n if host::ERROR_NAMES.contains(&n) => make_error_checked(name, &args),
        _ => Err(host::type_error(&format!("{name} is not a constructor"))),
    }
}

/// The legacy numeric `DOMException.code` a WHATWG error name maps to. A name
/// outside the table — including the default `"Error"` — reports 0.
pub const DOM_EXCEPTION_CODES: &[(&str, f64)] = &[
    ("IndexSizeError", 1.0),
    ("DOMStringSizeError", 2.0),
    ("HierarchyRequestError", 3.0),
    ("WrongDocumentError", 4.0),
    ("InvalidCharacterError", 5.0),
    ("NoDataAllowedError", 6.0),
    ("NoModificationAllowedError", 7.0),
    ("NotFoundError", 8.0),
    ("NotSupportedError", 9.0),
    ("InUseAttributeError", 10.0),
    ("InvalidStateError", 11.0),
    ("SyntaxError", 12.0),
    ("InvalidModificationError", 13.0),
    ("NamespaceError", 14.0),
    ("InvalidAccessError", 15.0),
    ("ValidationError", 16.0),
    ("TypeMismatchError", 17.0),
    ("SecurityError", 18.0),
    ("NetworkError", 19.0),
    ("AbortError", 20.0),
    ("URLMismatchError", 21.0),
    ("QuotaExceededError", 22.0),
    ("TimeoutError", 23.0),
    ("InvalidNodeTypeError", 24.0),
    ("DataCloneError", 25.0),
];

/// The static name a `DOMException` code is exposed under: the error name minus
/// its `Error` suffix, upper-snake-cased, plus `_ERR` — `AbortError` becomes
/// `ABORT_ERR`, `IndexSizeError` becomes `INDEX_SIZE_ERR`.
fn legacy_code_name(error_name: &str) -> String {
    let stem = error_name.strip_suffix("Error").unwrap_or(error_name);
    let mut out = String::new();
    for (i, c) in stem.chars().enumerate() {
        if c.is_ascii_uppercase() && i > 0 {
            out.push('_');
        }
        out.push(c.to_ascii_uppercase());
    }
    out.push_str("_ERR");
    out
}

/// `new DOMException(message, name)`.
///
/// The class node's `AbortSignal.reason` rejects with. Its `name` is the second
/// ARGUMENT (defaulting to `"Error"`), not the class name, and its `code` is the
/// legacy number that name maps to.
pub fn dom_exception(args: &[Value]) -> Value {
    let message = match args.first() {
        None | Some(Value::Undef) => String::new(),
        Some(v) => with_host(|h| h.str_of(v)),
    };
    let name = match args.get(1) {
        None | Some(Value::Undef) => "Error".to_string(),
        Some(v) => with_host(|h| h.str_of(v)),
    };
    with_host(|h| dom_exception_with(h, &name, &message))
}

/// `dom_exception` for a caller that already holds the host borrow.
pub(crate) fn dom_exception_with(h: &mut host::JsHost, name: &str, message: &str) -> Value {
    let name = name.to_string();
    let message = message.to_string();
    let code = DOM_EXCEPTION_CODES
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, c)| *c)
        .unwrap_or(0.0);
    let head = if message.is_empty() {
        name.clone()
    } else {
        format!("{name}: {message}")
    };
    let e = synth_error(h, &head);
    {
        let nv = h.new_str(name);
        let mv = h.new_str(message);
        let sv = h.new_str(head);
        if let Some(JsObj::Object(p)) = h.get_mut(&e) {
            // `name`, `message` and `code` are PROTOTYPE accessors over internal
            // slots in node, so `stack` is the instance's only own property.
            // Storing them as own keys would show up in
            // `Object.getOwnPropertyNames`, which reports just `['stack']`.
            p.shift_remove("message");
            p.insert("@@domName".into(), nv);
            p.insert("@@domMessage".into(), mv);
            p.insert("@@domCode".into(), Value::Float(code));
            p.insert("stack".into(), sv);
        }
        h.ensure_error_protos();
        if let Some(proto) = host::error_proto_of(h, "DOMException") {
            h.set_proto(&e, proto);
        }
    }
    e
}

/// A `DOMException`'s `name`/`message`/`code`, which live in internal slots
/// rather than as own properties. `None` for anything else.
pub fn dom_exception_slot(recv: &Value, name: &str) -> Option<Value> {
    let slot = match name {
        "name" => "@@domName",
        "message" => "@@domMessage",
        "code" => "@@domCode",
        _ => return None,
    };
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) if p.contains_key("@@domName") => p.get(slot).cloned(),
        _ => None,
    })
}

/// Build an `Error` object carrying `msg`, for stdlib callers that need to
/// throw a value with extra own properties on it.
pub(crate) fn make_error_pub(name: &str, msg: &str) -> Value {
    let m = with_host(|h| h.new_str(msg.to_string()));
    make_error_inner(name, &[m])
}

/// [`make_error`] with the message's `ToString` allowed to FAIL. A symbol
/// refuses it (20.5.1.1 step 3), so `new Error(sym)` is a TypeError where this
/// rendered `Symbol(desc)` into `.message`.
fn make_error_checked(name: &str, args: &[Value]) -> Result<Value, String> {
    if let Some(m) = args.first().filter(|m| !matches!(m, Value::Undef)) {
        // AggregateError's message is its SECOND argument.
        let idx = usize::from(name == "AggregateError");
        if idx == 0 {
            host::to_string_value(m)?;
        } else if let Some(m2) = args.get(idx).filter(|m| !matches!(m, Value::Undef)) {
            host::to_string_value(m2)?;
        }
    }
    Ok(make_error_inner(name, args))
}

fn make_error_inner(name: &str, args: &[Value]) -> Value {
    // `new AggregateError(errors, message)` takes the causes FIRST; every other
    // error constructor takes the message first.
    let agg = name == "AggregateError";
    let (errors, args) = if agg {
        (
            Some(args.first().cloned().unwrap_or(Value::Undef)),
            args.get(1..).unwrap_or(&[]),
        )
    } else {
        (None, args)
    };
    with_host(|h| {
        h.ensure_error_protos();
        let mut props: IndexMap<String, Value> = IndexMap::new();
        let msg = args
            .first()
            .filter(|a| !matches!(a, Value::Undef))
            .map(|a| h.str_of(a));
        if let Some(m) = &msg {
            let mv = h.new_str(m.clone());
            props.insert("message".into(), mv);
        }
        // `.stack` is engine-specific; a simple `Name: message` header line
        // suffices for parity (the fuzzer never prints raw stacks).
        //
        // V8 formats that header LAZILY, on the first read, from whatever `name`
        // and `message` the error carries at that moment — which is why the
        // near-universal
        //
        //     class MyErr extends Error { constructor(m) { super(m); this.name = 'MyErr'; } }
        //
        // reports `MyErr: boom` and not the `Error: boom` this built eagerly,
        // inside `super()`, before the subclass had renamed anything. `@@stackRaw`
        // carries the frames so the read can redo it; see `materialize_stack`.
        let frames = h.stack_frames();
        let stack = match &msg {
            Some(m) if !m.is_empty() => format!("{name}: {m}{frames}"),
            _ => format!("{name}{frames}"),
        };
        let sv = h.new_str(stack);
        props.insert("stack".into(), sv);
        let raw = h.new_str(frames);
        props.insert("@@stackRaw".into(), raw);
        if let Some(errs) = errors {
            // Materialize the iterable into the own `errors` array property.
            let items = h.iter_vec(&errs).unwrap_or_default();
            let arr = h.new_array(items);
            props.insert("errors".into(), arr);
        }
        // `new Error(msg, { cause })` (ES2022): installed only when the options
        // bag actually has a `cause` key, so `new Error(m, {})` leaves none.
        let opts = args.get(1);
        if let Some(cause) = opts.and_then(|o| match h.get(o) {
            Some(JsObj::Object(p)) => p.get("cause").cloned(),
            _ => None,
        }) {
            props.insert("cause".into(), cause);
        }
        let e = h.new_object(props);
        if let Some(p) = host::error_proto_of(h, name) {
            h.set_proto(&e, p);
        }
        // Every own slot an error constructor installs is non-enumerable in V8,
        // which is why `Object.keys(err)` is `[]` and `JSON.stringify(err)` is
        // `{}` — properties a *script* later assigns stay enumerable.
        for k in ["message", "stack", "errors", "cause", "@@stackRaw"] {
            h.hide_prop(&e, k);
        }
        e
    })
}

fn print_line(args: &[Value], stderr: bool) -> Result<(), String> {
    // Node's console.log(...args) === util.format(...args): printf-style
    // substitution when the first arg is a format string, else inspect-and-join.
    // A directive can THROW (`console.log('%j', 1n)`), and node lets that reach
    // the caller instead of printing a line — so nothing is written on failure.
    let line: String = crate::stdlib::util::format(args)?;
    with_host(|h| h.write_out(&format!("{line}\n"), stderr));
    Ok(())
}

fn arg0(args: &[Value]) -> Value {
    args.first().cloned().unwrap_or(Value::Undef)
}
/// `ToString(arg)` for a builtin's argument — fallible, because a SYMBOL
/// refuses the conversion (7.1.17). Every site that reached for `str_of`
/// instead rendered `Symbol(desc)` into its result and reported nothing.
fn arg_to_string(args: &[Value], i: usize) -> Result<String, String> {
    let v = args.get(i).cloned().unwrap_or(Value::Undef);
    let sv = host::to_string_value(&v)?;
    Ok(with_host(|h| h.str_of(&sv)))
}

fn arg_num(args: &[Value], i: usize) -> f64 {
    with_host(|h| h.to_number(&args.get(i).cloned().unwrap_or(Value::Undef)))
}

fn is_integer(v: Value) -> bool {
    match v {
        Value::Int(_) => true,
        Value::Float(f) => f.is_finite() && f.fract() == 0.0,
        _ => false,
    }
}
fn is_safe_integer(v: Value) -> bool {
    match v {
        Value::Float(f) => f.is_finite() && f.fract() == 0.0 && f.abs() <= 9007199254740991.0,
        Value::Int(_) => true,
        _ => false,
    }
}

/// `encodeURI`/`encodeURIComponent`: percent-encode `s`'s UTF-8 bytes, leaving
/// the unreserved set unescaped. `encodeURI` additionally preserves the reserved
/// URI characters (`;,/?:@&=+$#`) that delimit a URI's structure.
fn uri_encode(s: &str, uri: bool) -> Result<Value, String> {
    // Always-unescaped (`encodeURIComponent`'s unreserved set), per the spec.
    const UNRESERVED: &[u8] =
        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~*'()";
    // Reserved characters `encodeURI` leaves intact on top of the unreserved set.
    const RESERVED: &[u8] = b";,/?:@&=+$#";
    let mut out = String::with_capacity(s.len());
    for &b in s.as_bytes() {
        if UNRESERVED.contains(&b) || (uri && RESERVED.contains(&b)) {
            out.push(b as char);
        } else {
            out.push('%');
            out.push(
                char::from_digit((b >> 4) as u32, 16)
                    .unwrap()
                    .to_ascii_uppercase(),
            );
            out.push(
                char::from_digit((b & 0xf) as u32, 16)
                    .unwrap()
                    .to_ascii_uppercase(),
            );
        }
    }
    Ok(with_host(|h| h.new_str(out)))
}

/// `decodeURI`/`decodeURIComponent`: reverse `%XX` escapes back to UTF-8 text.
/// For `decodeURI`, escapes of the reserved delimiters are left as-is (the spec's
/// asymmetry with `encodeURI`). Throws `URIError` on a malformed escape.
fn uri_decode(s: &str, uri: bool) -> Result<Value, String> {
    const RESERVED: &[u8] = b";,/?:@&=+$#";
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err("URIError: URI malformed".into());
            }
            let hi = (bytes[i + 1] as char).to_digit(16);
            let lo = (bytes[i + 2] as char).to_digit(16);
            match (hi, lo) {
                (Some(h), Some(l)) => {
                    let byte = (h * 16 + l) as u8;
                    // decodeURI keeps reserved-delimiter escapes literal.
                    if uri && RESERVED.contains(&byte) {
                        out.extend_from_slice(&bytes[i..i + 3]);
                    } else {
                        out.push(byte);
                    }
                    i += 3;
                }
                _ => return Err("URIError: URI malformed".into()),
            }
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    match String::from_utf8(out) {
        Ok(decoded) => Ok(with_host(|h| h.new_str(decoded))),
        Err(_) => Err("URIError: URI malformed".into()),
    }
}

/// `escape` (Annex B.2.1.1) — the pre-`encodeURIComponent` legacy encoder, still
/// present in every engine and still reached by old libraries (jQuery's cookie
/// plugin, `querystring`-era code). It works on UTF-16 CODE UNITS, not UTF-8
/// bytes, which is what separates it from `encodeURIComponent`: a unit below
/// `0x100` becomes `%XX`, anything above becomes `%uXXXX`, so an astral
/// character yields the two escapes of its surrogate pair
/// (`escape("\u{1D4B3}")` is `"%uD835%uDCB3"` on node v26.7.0).
///
/// The unescaped set is frozen by the spec and is NOT the URI unreserved set —
/// it keeps `@*_+-./` and drops `!~'()`.
fn legacy_escape(s: &str) -> Result<Value, String> {
    const KEEP: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./";
    let mut out = String::with_capacity(s.len());
    for u in s.encode_utf16() {
        if u < 0x100 {
            if KEEP.contains(&(u as u8)) {
                out.push(u as u8 as char);
            } else {
                out.push_str(&format!("%{u:02X}"));
            }
        } else {
            out.push_str(&format!("%u{u:04X}"));
        }
    }
    Ok(with_host(|h| h.new_str(out)))
}

/// `unescape` (Annex B.2.1.2) — the inverse of [`legacy_escape`]. Unlike
/// `decodeURIComponent` it never throws: a `%` that does not begin a well-formed
/// `%XX` or `%uXXXX` escape is passed through literally
/// (`unescape("%u0041%42%zz%2")` is `"AB%zz%2"` on node v26.7.0).
///
/// Decoding is done in code-unit space and re-joined at the end so a
/// `%uD835%uDCB3` pair recomposes into the one astral character it came from.
fn legacy_unescape(s: &str) -> Result<Value, String> {
    let b = s.as_bytes();
    let hex = |i: usize, n: usize| -> Option<u16> {
        if i + n > b.len() {
            return None;
        }
        let mut v: u16 = 0;
        for &c in &b[i..i + n] {
            v = v.checked_mul(16)? + (c as char).to_digit(16)? as u16;
        }
        Some(v)
    };
    let units: Vec<u16> = s.encode_utf16().collect();
    let mut out: Vec<u16> = Vec::with_capacity(units.len());
    let mut i = 0;
    while i < b.len() {
        // Escapes are pure ASCII, so a byte index is a unit index up to here —
        // but the tail may not be, so non-`%` bytes are re-decoded as chars.
        if b[i] == b'%' {
            if let Some(u) = hex(i + 1, 2) {
                out.push(u);
                i += 3;
                continue;
            }
            if b.get(i + 1) == Some(&b'u') {
                if let Some(u) = hex(i + 2, 4) {
                    out.push(u);
                    i += 6;
                    continue;
                }
            }
        }
        let c = s[i..].chars().next().unwrap_or('%');
        let mut buf = [0u16; 2];
        out.extend_from_slice(c.encode_utf16(&mut buf));
        i += c.len_utf8();
    }
    Ok(with_host(|h| {
        h.new_str(crate::utf16::to_string_lossy(&out))
    }))
}

/// `parseInt` begins with `ToString(argument)` (19.2.5 step 1), and that step can
/// THROW — a Symbol has no string form, so `parseInt([Symbol()])` is a TypeError
/// rather than `NaN`. Reading the argument with `str_of` took the object's brand
/// instead of converting it, which both swallowed that throw and ignored any
/// `toString` the value defines.
fn parse_int(args: &[Value]) -> Result<f64, String> {
    // Converted BEFORE the host borrow: `to_string_value` can call back into JS.
    let sv = host::to_string_value(&arg0(args))?;
    // 19.2.5 step 2 is `ToInt32(radix)`, which runs a user `valueOf` — the
    // infallible read below does no `ToPrimitive`, so an object radix came out
    // as NaN and the parse silently fell back to auto-detection.
    let radix = match args.get(1) {
        Some(r) if !matches!(r, Value::Undef) => {
            vec![arg0(args), Value::Float(to_number_arg(args, 1)?)]
        }
        _ => args.to_vec(),
    };
    Ok(parse_int_str(&with_host(|h| h.str_of(&sv)), &radix))
}

fn parse_int_str(s: &str, args: &[Value]) -> f64 {
    // 19.2.5 step 8: an EXPLICIT radix outside 2..=36 is `NaN`, it does not fall
    // back to auto-detection. The old `.filter()` silently discarded a bad radix,
    // so `parseInt("10", 37)` answered 10 where every engine says NaN.
    let radix_arg = args
        .get(1)
        .map(|r| with_host(|h| host::to_int32(h.to_number(r))));
    let radix = match radix_arg {
        Some(0) | None => None,
        Some(r) if (2..=36).contains(&r) => Some(r as u32),
        Some(_) => return f64::NAN,
    };
    let t = crate::utf16::js_trim_start(s);
    let (neg, digits) = match t.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, t.strip_prefix('+').unwrap_or(t)),
    };
    let (radix, digits) = match radix {
        Some(16) => (
            16u32,
            digits
                .strip_prefix("0x")
                .or_else(|| digits.strip_prefix("0X"))
                .unwrap_or(digits),
        ),
        Some(r) => (r, digits),
        None => {
            if let Some(hex) = digits
                .strip_prefix("0x")
                .or_else(|| digits.strip_prefix("0X"))
            {
                (16, hex)
            } else {
                (10, digits)
            }
        }
    };
    let valid: String = digits.chars().take_while(|c| c.is_digit(radix)).collect();
    if valid.is_empty() {
        return f64::NAN;
    }
    // Accumulate in `f64`, not `i64`. `i64::from_str_radix` OVERFLOWS past ~19
    // digits and the error was mapped to `NaN`, so
    // `parseInt("999999999999999999999999")` was NaN instead of 1e+24. The spec
    // asks for the mathematical value rounded to a Number, which is what
    // repeated multiply-accumulate in `f64` produces.
    let n = if radix == 10 {
        // Rust's decimal float parser is correctly rounded; digit-by-digit
        // multiply-accumulate is not, and drifted a ULP on long inputs
        // (`parseInt("999999999999999999999999")` came out
        // 1.0000000000000003e+24 rather than 1e+24).
        valid.parse::<f64>().unwrap_or(f64::NAN)
    } else {
        let mut n = 0.0f64;
        for c in valid.chars() {
            n = n * radix as f64 + c.to_digit(radix).unwrap_or(0) as f64;
        }
        n
    };
    if neg {
        -n
    } else {
        n
    }
}

/// `parseFloat` likewise starts from `ToString(argument)`; see `parse_int`.
fn parse_float(args: &[Value]) -> Result<f64, String> {
    let sv = host::to_string_value(&arg0(args))?;
    Ok(parse_float_str(&with_host(|h| h.str_of(&sv))))
}

fn parse_float_str(s: &str) -> f64 {
    let t = crate::utf16::js_trim_start(s);
    // `Infinity` / `+Infinity` / `-Infinity` are valid parseFloat prefixes.
    let inf_body = t
        .strip_prefix('+')
        .or_else(|| t.strip_prefix('-'))
        .unwrap_or(t);
    if inf_body.starts_with("Infinity") {
        return if t.starts_with('-') {
            f64::NEG_INFINITY
        } else {
            f64::INFINITY
        };
    }
    // The LONGEST prefix that is itself a complete `StrDecimalLiteral`, which is
    // not the same as the longest run of characters that could appear in one:
    // `"1e"` and `"1e+"` are `1` in every engine, because the exponent part is
    // only valid once a digit follows `e`. Tracking `end` at every character
    // accepted the dangling `e`, `parse::<f64>` then failed, and the whole call
    // came back NaN.
    let mut end = 0;
    let bytes = t.as_bytes();
    let mut seen_dot = false;
    let mut seen_e = false;
    let mut digits_before_dot = false;
    for (i, &c) in bytes.iter().enumerate() {
        match c {
            b'0'..=b'9' => {
                if !seen_dot && !seen_e {
                    digits_before_dot = true;
                }
                end = i + 1;
            }
            // A sign is only meaningful leading, or straight after the exponent
            // marker; it never completes a literal on its own.
            b'+' | b'-' if i == 0 || bytes[i - 1] == b'e' || bytes[i - 1] == b'E' => {}
            // `1.` is a complete literal; a bare `.` is not.
            b'.' if !seen_dot && !seen_e => {
                seen_dot = true;
                if digits_before_dot {
                    end = i + 1;
                }
            }
            b'e' | b'E' if !seen_e && end > 0 => seen_e = true,
            _ => break,
        }
    }
    if end == 0 {
        return f64::NAN;
    }
    t[..end].parse::<f64>().unwrap_or(f64::NAN)
}

/// ECMA-262 `Number::exponentiate` (6.1.6.1.3), backing both `Math.pow` and the
/// `**` operator. Three clauses differ from IEEE-754 `pow`, which is what Rust's
/// `powf` implements: a NaN exponent is NaN even for base 1, a NaN base is NaN
/// for any non-zero exponent, and `|base| == 1` with an infinite exponent is NaN
/// rather than 1.
pub(crate) fn js_pow(base: f64, exp: f64) -> f64 {
    if exp == 0.0 {
        return 1.0;
    }
    if base.is_nan() || exp.is_nan() {
        return f64::NAN;
    }
    if base.abs() == 1.0 && exp.is_infinite() {
        return f64::NAN;
    }
    base.powf(exp)
}

fn math_fn(fname: &str, args: &[Value]) -> Result<Value, String> {
    // Every `Math` function coerces its arguments with `ToNumber`, and `ToNumber`
    // of a BigInt is a TypeError (7.1.4 step 2) — the whole point of BigInt being
    // a separate numeric type. `arg_num` reads a BigInt's magnitude instead, so
    // `Math.max(1n)` quietly answered 1 where V8 throws. `Math.random` is the one
    // exception: it never reads an argument, so `Math.random(1n)` is fine.
    // A BigInt WRAPPER converts to a BigInt and is rejected just as the
    // primitive is: `Math.abs(Object(9n))` is a TypeError where it answered NaN.
    // The boxed value is read BEFORE the borrow — `wrapped_primitive` borrows
    // the host itself and cannot run inside another borrow.
    let is_bigint = |a: &Value| {
        if with_host(|h| matches!(h.get(a), Some(JsObj::BigInt(_)))) {
            return true;
        }
        match wrapped_primitive(a) {
            Some(p) => with_host(|h| matches!(h.get(&p), Some(JsObj::BigInt(_)))),
            None => false,
        }
    };
    if fname != "random" && args.iter().any(is_bigint) {
        return Err(host::type_error(
            "Cannot convert a BigInt value to a number",
        ));
    }
    // Every argument is `ToNumber`d (21.3.2.x), which runs a user `valueOf` and
    // can throw from it. `arg_num` does no `ToPrimitive` at all, so
    // `Math.max({valueOf: () => 1}, 0)` answered NaN.
    // EVERY argument, not a fixed prefix: `Math.max`/`min`/`hypot` are
    // variadic, and coercing only the first few silently DROPPED the rest —
    // `Math.max(...gen)` over five values answered for four of them.
    let mut coerced = Vec::with_capacity(args.len());
    for a in args {
        if matches!(a, Value::Undef) {
            coerced.push(a.clone());
            continue;
        }
        let p = host::to_primitive(a, "number")?;
        coerced.push(Value::Float(with_host(|h| h.to_number(&p))));
    }
    let args: &[Value] = &coerced;
    let x = arg_num(args, 0);
    let r = match fname {
        "floor" => x.floor(),
        "ceil" => x.ceil(),
        // ECMA-262 `Math.round` (21.3.2.28) transcribed clause by clause. The
        // obvious `(x + 0.5).floor()` is NOT this function: the addition rounds
        // before the floor sees it, so it answers 1 for the largest double below
        // 0.5 (`Math.round(0.49999999999999994)` is 0 in every engine) and it
        // perturbs integers above 2^52, where `x + 0.5` is no longer
        // representable (`Math.round(4503599627370497)` must be the input).
        // Splitting the zero-band cases out first also carries the signed zero
        // the spec asks for without a post-hoc patch.
        "round" => {
            if !x.is_finite() || x == 0.0 {
                x
            } else if x > 0.0 && x < 0.5 {
                0.0
            } else if (-0.5..0.0).contains(&x) {
                -0.0
            } else {
                // |x| >= 0.5, so `floor` and the subtraction are both exact
                // (every double >= 2^52 is already an integer and yields 0 here).
                let f = x.floor();
                if x - f >= 0.5 {
                    f + 1.0
                } else {
                    f
                }
            }
        }
        "trunc" => x.trunc(),
        "abs" => x.abs(),
        "sign" => {
            if x.is_nan() {
                f64::NAN
            } else if x > 0.0 {
                1.0
            } else if x < 0.0 {
                -1.0
            } else {
                x
            }
        }
        "sqrt" => x.sqrt(),
        "cbrt" => x.cbrt(),
        "exp" => x.exp(),
        "log" => x.ln(),
        "log2" => x.log2(),
        "log10" => x.log10(),
        "sin" => x.sin(),
        "cos" => x.cos(),
        "tan" => x.tan(),
        "asin" => x.asin(),
        "acos" => x.acos(),
        "atan" => x.atan(),
        "atan2" => x.atan2(arg_num(args, 1)),
        // Rust `powf` is IEEE-754 `pow`, which is NOT JS `**`/`Math.pow`: IEEE
        // makes `pow(x, ±0)` and `pow(±1, y)` return 1 unconditionally, so
        // `(-1) ** Infinity` and `1 ** NaN` come back 1 where the spec
        // (6.1.6.1.3 Number::exponentiate) says NaN. Only the exponent-is-zero
        // clause is shared.
        "pow" => js_pow(x, arg_num(args, 1)),
        // Hyperbolics and the two precision-preserving log/exp forms.
        "sinh" => x.sinh(),
        "cosh" => x.cosh(),
        "tanh" => x.tanh(),
        "asinh" => x.asinh(),
        "acosh" => x.acosh(),
        "atanh" => x.atanh(),
        "log1p" => x.ln_1p(),
        "expm1" => x.exp_m1(),
        // C-style 32-bit integer multiply: ToInt32 both operands, multiply with
        // wraparound, reinterpret as a signed 32-bit result.
        "imul" => (host::to_int32(x).wrapping_mul(host::to_int32(arg_num(args, 1)))) as f64,
        "hypot" => {
            // Scale by the largest magnitude before squaring — this avoids the
            // last-ULP error of the naive `sqrt(Σ xᵢ²)` and matches V8's result.
            let xs: Vec<f64> = args.iter().map(|a| with_host(|h| h.to_number(a))).collect();
            let mut max = 0.0f64;
            for x in &xs {
                if x.abs() > max {
                    max = x.abs();
                }
            }
            if xs.iter().any(|x| x.is_infinite()) {
                f64::INFINITY
            } else if max == 0.0 || !max.is_finite() {
                max
            } else {
                let s: f64 = xs.iter().map(|x| (x / max) * (x / max)).sum();
                max * s.sqrt()
            }
        }
        "random" => pseudo_random(),
        "max" => {
            if args.is_empty() {
                f64::NEG_INFINITY
            } else {
                let mut m = f64::NEG_INFINITY;
                for a in args {
                    let n = with_host(|h| h.to_number(a));
                    if n.is_nan() {
                        return Ok(Value::Float(f64::NAN));
                    }
                    // `>` cannot separate the zeroes (`0.0 > -0.0` is false), but
                    // the spec ranks +0 above -0, so `Math.max(-0, 0)` is +0 and
                    // must not keep the -0 the first iteration installed.
                    if n > m || (n == m && n == 0.0 && n.is_sign_positive()) {
                        m = n;
                    }
                }
                m
            }
        }
        "min" => {
            if args.is_empty() {
                f64::INFINITY
            } else {
                let mut m = f64::INFINITY;
                for a in args {
                    let n = with_host(|h| h.to_number(a));
                    if n.is_nan() {
                        return Ok(Value::Float(f64::NAN));
                    }
                    // Mirror of `max`: -0 ranks below +0 even though `<` says
                    // they are equal, so `Math.min(0, -0)` is -0.
                    if n < m || (n == m && n == 0.0 && n.is_sign_negative()) {
                        m = n;
                    }
                }
                m
            }
        }
        // Count leading zero bits of ToUint32(x) (Math.clz32(1) === 31).
        "clz32" => {
            let u = if x.is_finite() {
                x.trunc().rem_euclid(4294967296.0) as u32
            } else {
                0
            };
            u.leading_zeros() as f64
        }
        // Round to the nearest single-precision float.
        "fround" => (x as f32) as f64,
        _ => return Err(host::type_error(&format!("Math.{fname} is not a function"))),
    };
    Ok(Value::Float(r))
}

/// A small deterministic PRNG for `Math.random` (output is non-reproducible vs
/// Node by nature; kept simple).
fn pseudo_random() -> f64 {
    use std::cell::Cell;
    thread_local!(static SEED: Cell<u64> = const { Cell::new(0x2545F4914F6CDD1D) });
    SEED.with(|s| {
        let mut x = s.get();
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        s.set(x);
        (x >> 11) as f64 / (1u64 << 53) as f64
    })
}

// ── Object.* ──────────────────────────────────────────────────────────────────

/// The characters of a string PRIMITIVE, as the `ToObject` wrapper's own index
/// properties (10.4.3 `StringExoticObject`).
///
/// `getOwnPropertyDescriptor` begins with `ToObject`, which boxes a string into
/// an exotic object whose own keys are its code-unit indices plus `length`;
/// this is the descriptor half of that. (The KEY half lives in
/// `JsHost::own_enum_data_keys`, the single source every enumeration path
/// reads.) Indices are UTF-16 code units, matching `.length` and `s[i]`.
///
/// A boxed `String` object is deliberately NOT routed here: it can carry
/// ordinary own properties too (`const s = new String('ab'); s.x = 1`), and its
/// existing path already reports them alongside the indices.
fn string_primitive_units(v: &Value) -> Option<Vec<String>> {
    // A JS string primitive rides as a `Value::Obj` handle to `JsObj::Str` (see
    // `host.rs`); a BOXED `new String(...)` is a different heap object, so this
    // never catches one.
    let s = match v {
        Value::Str(s) => (**s).clone(),
        _ => with_host(|h| match h.get(v) {
            Some(JsObj::Str(s)) => Some(s.clone()),
            _ => None,
        })?,
    };
    let units = crate::utf16::Units::of(&s);
    Some((0..units.len()).filter_map(|i| units.unit_str(i)).collect())
}

fn object_keys(args: Vec<Value>, mode: u8) -> Result<Value, String> {
    let v = arg0(&args);
    require_object_coercible(&v)?;
    // A Proxy answers from its `ownKeys` trap. `getOwnPropertyNames` (mode 3)
    // reports every own STRING key the trap named; the enumerating modes
    // additionally filter by each key's `[[GetOwnProperty]]`, so both traps run.
    if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
        if mode == 3 {
            let keys = crate::proxy::own_keys(&v)?.unwrap_or_default();
            return Ok(with_host(|h| {
                let out: Vec<Value> = keys
                    .into_iter()
                    .filter(|k| !host::is_symbol_key(k))
                    .map(|k| h.new_str(k))
                    .collect();
                h.new_array(out)
            }));
        }
        // `Object.keys` (mode 0) must run `ownKeys` and `getOwnPropertyDescriptor`
        // and STOP — 7.3.23 never performs `[[Get]]` when only keys are wanted.
        // Going through `own_enum_entries` fired the `get` trap once per key, so
        // the observable trap sequence carried a trailing `get` node does not
        // emit, and a trap with side effects ran when it should not have.
        if mode == 0 {
            let keys = crate::proxy::own_enum_string_keys(&v)?;
            return Ok(with_host(|h| {
                let out: Vec<Value> = keys.into_iter().map(|k| h.new_str(k)).collect();
                h.new_array(out)
            }));
        }
        let entries = crate::proxy::own_enum_entries(&v)?;
        return Ok(with_host(|h| {
            let out: Vec<Value> = entries
                .into_iter()
                .map(|(k, val)| match mode {
                    0 => h.new_str(k),
                    1 => val,
                    _ => {
                        let ks = h.new_str(k);
                        h.new_array(vec![ks, val])
                    }
                })
                .collect();
            h.new_array(out)
        }));
    }
    // An intrinsic prototype this host built as a REAL OBJECT — `Symbol
    // .prototype`, `String.prototype`, the error hierarchy — answers from the
    // generated table too. It was answering from its own property map instead,
    // which carries neither the right names nor V8's order: `Symbol.prototype`
    // reported `toLocaleString` and omitted `description`, and
    // `String.prototype` omitted `length` and every Annex B HTML method.
    //
    // `ns` is the namespace SPELLING, so the arm below is shared verbatim —
    // the two representations of a prototype cannot answer differently.
    let real_proto_ns = with_host(|h| h.intrinsic_proto_ctor(&v).map(|c| format!("{c}.prototype")))
        .filter(|ns| intrinsic_proto_members(ns).is_some());
    // A builtin prototype namespace that exposes enumerable methods for copying
    // (`Object.getOwnPropertyNames(EventEmitter.prototype)` — express's mixin).
    if let Some(ns) = real_proto_ns.or_else(|| {
        with_host(|h| match h.get(&v) {
            Some(JsObj::Builtin(ns)) => Some(ns.clone()),
            _ => None,
        })
    }) {
        // An INTRINSIC prototype (`Map.prototype`, `URL.prototype`). Members are
        // non-enumerable on an ECMAScript builtin and enumerable on a WebIDL
        // interface, which the table records per name.
        if let Some(members) = intrinsic_proto_members(&ns) {
            let ctor = ns.trim_end_matches(".prototype");
            let mut names: Vec<String> = members
                .iter()
                .filter(|m| mode == 3 || m.starts_with('+'))
                .map(|m| m.strip_prefix('+').unwrap_or(m).to_string())
                // `getOwnPropertyNames` reports STRING keys only; the table's
                // `@@` entries are symbol-keyed members and belong to
                // `getOwnPropertySymbols` instead.
                .filter(|m| !m.starts_with("@@"))
                .collect();
            // Plus whatever a script patched onto this prototype under a NEW
            // name — an ordinary enumerable own property, so it lists in every
            // mode. Without it `Object.keys(Array.prototype)` stayed `[]` after
            // an assignment that `Array.prototype.patch` read back happily.
            //
            // Assigning over an EXISTING member is a `[[Set]]`, which leaves
            // that member's attributes alone: restoring a saved `join` must not
            // turn it into an enumerable key.
            for k in with_host(|h| h.builtin_static_keys(&ns)) {
                if !intrinsic_proto_member(&ns, &k) && !names.contains(&k) {
                    names.push(k);
                }
            }
            return Ok(with_host(|h| {
                let out: Vec<Value> = names
                    .iter()
                    .map(|name| {
                        // An accessor member has no thunk — `Map.prototype.size`
                        // is not a function — so a VALUE read of one answers
                        // undefined rather than synthesizing a callable.
                        let val = |h: &mut host::JsHost| {
                            if let Some(v) = h.builtin_static(&ns, name) {
                                return v;
                            }
                            let key = format!("@proto:{ctor}:{name}");
                            if builtin_meta(&key).is_some() {
                                h.alloc(JsObj::Builtin(key))
                            } else {
                                Value::Undef
                            }
                        };
                        match mode {
                            1 => val(h),
                            2 => {
                                let ks = h.new_str(name.clone());
                                let v = val(h);
                                h.new_array(vec![ks, v])
                            }
                            _ => h.new_str(name.clone()),
                        }
                    })
                    .collect();
                h.new_array(out)
            }));
        }
        if let Some(names) = builtin_proto_method_names(&ns) {
            return Ok(with_host(|h| {
                let out: Vec<Value> = names
                    .iter()
                    .map(|name| match mode {
                        1 => h.alloc(JsObj::Builtin(format!(
                            "@proto:{}:{name}",
                            ns.trim_end_matches(".prototype")
                        ))),
                        2 => {
                            let ks = h.new_str(*name);
                            let val = h.alloc(JsObj::Builtin(format!(
                                "@proto:{}:{name}",
                                ns.trim_end_matches(".prototype")
                            )));
                            h.new_array(vec![ks, val])
                        }
                        _ => h.new_str(*name),
                    })
                    .collect();
                h.new_array(out)
            }));
        }
        // A stdlib namespace (`Buffer`, `require('buffer')`): its own enumerable
        // keys are the members node-js implements, each resolved to the same
        // first-class value a property read would give.
        let mut names = crate::stdlib::namespace_keys(&ns);
        // A core namespace (`Reflect`, `Math`, `JSON`) has no stdlib key list —
        // its members live in the builtin dispatch table. They are
        // non-enumerable in V8, so they surface only under
        // `getOwnPropertyNames`/`Reflect.ownKeys` (mode 3), never `Object.keys`.
        if names.is_empty() && mode == 3 {
            let prefix = format!("{ns}.");
            // A builtin constructor's own `length`/`name`/`prototype` come
            // first, as they do in V8.
            if is_builtin_ctor(&ns) {
                names.extend(["length", "name", "prototype"].map(str::to_string));
            }
            names.extend(
                NS_METHODS
                    .iter()
                    .filter_map(|q| q.strip_prefix(&prefix))
                    .map(|m| m.to_string()),
            );
            // The numeric constants are members too. Without them
            // `getOwnPropertyNames(Math)` reported 35 of the 43 names node-js
            // actually answers — the eight it dropped being `PI` and its
            // siblings, which read fine and now own a descriptor as well.
            names.extend(
                namespace_constants(&ns)
                    .iter()
                    .map(|(k, _)| (*k).to_string()),
            );
        }
        // A builtin FUNCTION owns exactly `length` and `name` (10.3.3-4), so
        // `Object.getOwnPropertyNames(Math.max)` is `[ 'length', 'name' ]` — it
        // was `[]`, which said the function had no properties at all while both
        // of them read back a value. `length` is listed only where the intrinsic
        // table has an arity, so the names never advertise a read that answers
        // `undefined`.
        if names.is_empty() && mode == 3 && host::builtin_is_callable(&ns) {
            if builtin_meta(&ns).is_some() {
                names.push("length".to_string());
            }
            names.push("name".to_string());
        }
        // Whatever a script assigned onto the namespace, in assignment order and
        // after the built-in members — an ordinary enumerable own property, so
        // it surfaces under `Object.keys` too and not only `ownKeys`. These were
        // missing from every listing, which made a patched prototype read as
        // unpatched to any code that enumerates rather than reads.
        for k in with_host(|h| h.builtin_static_keys(&ns)) {
            if !names.contains(&k) {
                names.push(k);
            }
        }
        if !names.is_empty() {
            let entries: Vec<(String, Value)> = names
                .into_iter()
                .map(|k| {
                    let val = namespace_property(&ns, &k);
                    (k, val)
                })
                .collect();
            return Ok(with_host(|h| {
                let out: Vec<Value> = entries
                    .into_iter()
                    .map(|(k, val)| match mode {
                        1 => val,
                        2 => {
                            let ks = h.new_str(k);
                            h.new_array(vec![ks, val])
                        }
                        _ => h.new_str(k),
                    })
                    .collect();
                h.new_array(out)
            }));
        }
    }
    // mode 3 (`getOwnPropertyNames`) reports every own string key including the
    // non-enumerable ones, plus the exotic `length` an array carries.
    let entries: Vec<(String, Value)> = with_host(|h| {
        if mode == 3 {
            // An array's exotic `length` is already placed (after the indices,
            // before the ordinary string keys) by `own_key_names`.
            return h
                .own_key_names(&v, false)
                .into_iter()
                .map(|k| (k, Value::Undef))
                .collect();
        }
        Vec::new()
    });
    // `Object.keys` (mode 0) wants NAMES. `own_enum_entries_deep` returns
    // key/value pairs, so asking it for them ran every enumerable getter —
    // 20.1.2.17 -> 7.3.23 EnumerableOwnProperties only needs `[[GetOwnProperty]]`
    // for the enumerable flag, never `[[Get]]`, and a getter can throw or have
    // side effects:
    //
    //     let n = 0; const o = { get g() { n++; return 1 } };
    //     Object.keys(o); n   // was 1, node says 0
    //
    // `values`/`entries` (modes 1 and 2) do read, and still do.
    let entries = match mode {
        3 => entries,
        0 => with_host(|h| h.own_enum_key_names(&v))
            .into_iter()
            .map(|k| (k, Value::Undef))
            .collect(),
        _ => host::own_enum_entries_deep(&v)?,
    };
    Ok(with_host(|h| {
        let out: Vec<Value> = entries
            .into_iter()
            .map(|(k, val)| match mode {
                0 | 3 => h.new_str(k),
                1 => val,
                _ => {
                    let ks = h.new_str(k);
                    h.new_array(vec![ks, val])
                }
            })
            .collect();
        h.new_array(out)
    }))
}

fn object_assign(args: Vec<Value>) -> Result<Value, String> {
    let target = arg0(&args);
    // 20.1.2.1 step 1 is `ToObject(target)`, so a nullish TARGET throws while a
    // nullish SOURCE is skipped (`Object.assign({}, null)` is `{}`).
    require_object_coercible(&target)?;
    for src in args.iter().skip(1) {
        // `Object.assign` copies own *enumerable* properties, running any getter
        // — symbol-keyed ones included (7.3.25).
        let entries = host::own_enum_entries_deep(src)?;
        let syms = with_host(|h| h.own_symbol_entries(src));
        // A plain object target is filled in place (one borrow, then a single
        // re-canonicalization of the integer-index keys).
        let filled = with_host(|h| {
            if let Some(JsObj::Object(p)) = h.get_mut(&target) {
                for (k, v) in entries.iter().cloned().chain(syms.iter().cloned()) {
                    p.insert(k, v);
                }
                host::canonicalize_own_keys(p);
                return true;
            }
            false
        });
        // Any OTHER target — an array being the common one — goes through the
        // ordinary Set path. The in-place branch above matched `JsObj::Object`
        // only, so `Object.assign([1,2], {extra:9})` silently copied NOTHING and
        // returned the untouched array: no error, just a missing property. The
        // Set path is what an `arr.extra = 9` assignment already used, so index
        // and non-index keys land where they do for a direct write.
        if !filled {
            for (k, v) in entries.into_iter().chain(syms) {
                set_property(&target, &k, v)?;
            }
        }
    }
    Ok(target)
}

fn object_from_entries(args: Vec<Value>) -> Result<Value, String> {
    let pairs = with_host(|h| h.iter_vec(&arg0(&args))).unwrap_or_default();
    let mut props: IndexMap<String, Value> = IndexMap::new();
    for p in pairs {
        let kv = with_host(|h| h.iter_vec(&p)).unwrap_or_default();
        let key = with_host(|h| h.str_of(&kv.first().cloned().unwrap_or(Value::Undef)));
        let val = kv.get(1).cloned().unwrap_or(Value::Undef);
        props.insert(key, val);
    }
    Ok(with_host(|h| h.new_object(props)))
}

/// `Object.groupBy(items, cb)` — group the iterable `items` into a null-prototype
/// object. Keys are `ToPropertyKey(cb(item, index))`; values are arrays of the
/// members mapped to that key, in first-seen key order.
fn object_group_by(args: Vec<Value>) -> Result<Value, String> {
    group_by_check_iterable(&arg0(&args), "Object.groupBy")?;
    let cb = args.get(1).cloned().unwrap_or(Value::Undef);
    let mut groups: IndexMap<String, Vec<Value>> = IndexMap::new();
    // Stepped, not drained: the callback runs per element, so a throwing one
    // stops at the first. Draining first meant an infinite source never reached
    // the callback at all and the call HUNG.
    host::iter_for_each(&arg0(&args), |item, i| {
        let key_v = host::invoke(&cb, vec![item.clone(), Value::Float(i as f64)], None)?;
        let key = with_host(|h| h.property_key(&key_v));
        groups.entry(key).or_default().push(item);
        Ok(())
    })?;
    let props: IndexMap<String, Value> = with_host(|h| {
        groups
            .into_iter()
            .map(|(k, v)| (k, h.new_array(v)))
            .collect()
    });
    let obj = with_host(|h| h.new_object(props));
    // A null-prototype object (as Node returns), so it has no inherited members.
    with_host(|h| {
        let nv = h.null();
        h.set_proto(&obj, nv);
    });
    Ok(obj)
}

/// The `groupBy` family words a non-iterable argument its OWN way — a third
/// vocabulary, alongside the array-literal spread's and the call spread's:
///
/// ```text
/// null / undefined   "<Name> called on null or undefined"
/// anything else      "<typeof> [value ]is not iterable (cannot read property
///                     Symbol(Symbol.iterator))"
/// ```
///
/// A plain object, a symbol and a bigint name only their TYPE; a number, a
/// string and a boolean name the value too.
fn group_by_check_iterable(v: &Value, name: &str) -> Result<(), String> {
    if with_host(|h| h.is_nullish(v)) {
        return Err(host::type_error(&format!(
            "{name} called on null or undefined"
        )));
    }
    // Asked WITHOUT consuming anything: `iter_all` would drain the iterator
    // here, so the stepping loop below then saw an exhausted one — the finite
    // case returned an empty group and the infinite case was back to hanging.
    let iter_fn = get_property(v, "@@iterator").unwrap_or(Value::Undef);
    if with_host(|h| host::is_callable(h, &iter_fn)) {
        return Ok(());
    }
    Err(host::type_error(&not_iterable_typed(v)))
}

/// The `<type> <value> is not iterable (cannot read property
/// Symbol(Symbol.iterator))` wording, which node uses wherever the source has
/// no name to report: a plain object, a symbol and a bigint name only their
/// TYPE; a number, a string and a boolean name the value too.
pub(crate) fn not_iterable_typed(v: &Value) -> String {
    let shown = with_host(|h| {
        let kind = h.type_of(v);
        match kind {
            "object" | "symbol" | "bigint" => kind.to_string(),
            "string" => format!("string \"{}\"", h.str_of(v)),
            _ => format!("{kind} {}", h.str_of(v)),
        }
    });
    format!("{shown} is not iterable (cannot read property Symbol(Symbol.iterator))")
}

/// `Map.groupBy(items, cb)` — like `Object.groupBy` but returns a `Map` keyed by
/// the raw `cb(item, index)` value under SameValueZero (so object/any keys work).
fn map_group_by(args: Vec<Value>) -> Result<Value, String> {
    group_by_check_iterable(&arg0(&args), "Map.groupBy")?;
    let cb = args.get(1).cloned().unwrap_or(Value::Undef);
    let m = with_host(|h| {
        h.alloc(JsObj::Map {
            entries: IndexMap::new(),
            weak: false,
        })
    });
    // Stepped for the same reason `Object.groupBy` is.
    host::iter_for_each(&arg0(&args), |item, i| {
        let key_v = host::invoke(&cb, vec![item.clone(), Value::Float(i as f64)], None)?;
        let existing = map_method(&m, "get", vec![key_v.clone()])?;
        if matches!(existing, Value::Undef) {
            let arr = with_host(|h| h.new_array(vec![item]));
            map_method(&m, "set", vec![key_v, arr])?;
        } else {
            with_host(|h| {
                if let Some(JsObj::Array(a)) = h.get_mut(&existing) {
                    a.push(item);
                }
            });
        }
        Ok(())
    })?;
    Ok(m)
}

/// `Array.fromAsync(items[, mapFn])` — a Promise for an array, awaiting each
/// element and each `mapFn` result.
///
/// Written in JavaScript and compiled once, because the operation IS an async
/// function: a Rust builtin runs outside any coroutine and has no way to await,
/// so draining a promise from there would mean running the microtask queue by
/// hand. Delegating to the engine's own `async`/`for await` keeps the
/// suspension semantics — and the ordering they imply — exactly the language's.
///
/// The source may be an async iterable, a sync iterable, a bare iterator, or an
/// array-like. Everything iterable goes through `for await`, which awaits a sync
/// source's elements individually — that is what makes
/// `Array.fromAsync([1, Promise.resolve(2)])` answer `[1, 2]`. A bare `.next` is
/// accepted because an async generator object does not expose
/// `Symbol.asyncIterator` on this frontend.
fn array_from_async(args: Vec<Value>) -> Result<Value, String> {
    thread_local! {
        static IMPL: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
    }
    const SRC: &str = "(async function (items, mapFn, thisArg) {\n\
        const out = []; let i = 0;\n\
        const step = async (v) => { const a = await v; out.push(mapFn ? await mapFn.call(thisArg, a, i) : a); i++; };\n\
        const iterable = items != null && (typeof items[Symbol.asyncIterator] === 'function'\n\
            || typeof items[Symbol.iterator] === 'function' || typeof items.next === 'function');\n\
        if (iterable) {\n\
            for await (const v of items) { out.push(mapFn ? await mapFn.call(thisArg, v, i) : v); i++; }\n\
            return out;\n\
        }\n\
        const len = items == null ? 0 : (Math.trunc(Number(items.length)) || 0);\n\
        while (i < len) { await step(items[i]); }\n\
        return out;\n\
    })";
    let f = IMPL.with(|c| c.borrow().clone());
    let f = match f {
        Some(f) => f,
        None => {
            let f = crate::eval_in_global_scope(SRC)?;
            IMPL.with(|c| *c.borrow_mut() = Some(f.clone()));
            f
        }
    };
    host::invoke(&f, args, None)
}

fn array_from(args: Vec<Value>) -> Result<Value, String> {
    // `Array.from` accepts generators and user iterables, plus array-likes with a
    // numeric `.length`.
    let src = arg0(&args);
    if let Some(cb) = args.get(1).cloned() {
        // Stepped, not drained: the mapper runs per element as the iterator
        // yields it (23.1.2.1 step 6.e). Materializing the whole sequence first
        // meant `Array.from(infiniteIterator, fn)` never reached the mapper at
        // all and HUNG, and a throwing mapper could not close the iterator.
        let this = this_arg(&args, 2);
        let mut out = Vec::new();
        let mapped = host::iter_for_each(&src, |v, i| {
            out.push(host::invoke(
                &cb,
                vec![v, Value::Float(i as f64)],
                this.clone(),
            )?);
            Ok(())
        });
        match mapped {
            Ok(()) => {}
            // An array-LIKE has no iterator; fall back to its indexed items.
            Err(e) if host::user_iterator_fn(&src).is_none() && e.ends_with(" is not iterable") => {
                out.clear();
                for (i, it) in array_like_items(&src).into_iter().enumerate() {
                    out.push(host::invoke(
                        &cb,
                        vec![it, Value::Float(i as f64)],
                        this.clone(),
                    )?);
                }
            }
            Err(e) => return Err(e),
        }
        return construct_array_like(host::current_static_this(), out);
    }
    let items = match host::iter_all(&src) {
        Ok(v) => v,
        Err(_) => array_like_items(&src),
    };
    // 23.1.2.1 step 5: `Array.from` builds through `this`, so on a subclass the
    // result is an instance of it. It always allocated a plain array, which is
    // also why `A.from([1]).map(f) instanceof A` was false — the species chain
    // never started.
    construct_array_like(host::current_static_this(), items)
}

/// Items of an array-like `{ length, 0, 1, … }` object (for `Array.from`).
pub(crate) fn array_like_items(src: &Value) -> Vec<Value> {
    // `LengthOfArrayLike` is `ToLength(Get(O, "length"))`, and `ToNumber` runs a
    // user `valueOf` — `Array.from({length: {valueOf: () => 1}})` was empty
    // because the infallible read does no `ToPrimitive`. A throw from it is
    // swallowed here for the same reason the `length` read is: this helper has
    // no way to report one, and every caller treats an unreadable length as 0.
    let len = get_property(src, "length")
        .ok()
        .and_then(|l| host::to_primitive(&l, "number").ok())
        .map(|l| with_host(|h| h.to_number(&l)))
        .unwrap_or(0.0);
    if !len.is_finite() || len <= 0.0 {
        return Vec::new();
    }
    (0..len as usize)
        .map(|i| get_property(src, &i.to_string()).unwrap_or(Value::Undef))
        .collect()
}

// ── JSON ──────────────────────────────────────────────────────────────────────

fn json_stringify(args: Vec<Value>) -> Result<Value, String> {
    // A CALLABLE second argument is the replacer function, and it is checked
    // before the array form (`IsCallable` precedes `IsArray` in the spec), so a
    // callable never also reaches the key-filter path below.
    let replacer = args
        .get(1)
        .filter(|r| with_host(|h| host::is_callable(h, r)))
        .cloned();
    // `toJSON` and the replacer run BEFORE serialization and are user code, so
    // the tree is rewritten first — outside the host borrow `json_str` holds,
    // and before the BigInt walk, which has no cycle guard of its own.
    //
    // The top-level value is a property of a synthetic wrapper `{ "": value }`
    // under key `""`, which is exactly the holder the replacer receives as
    // `this` on its first call.
    let root = arg0(&args);
    let wrapper = with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        m.insert(String::new(), root.clone());
        h.new_object(m)
    });
    let v = apply_to_json(&wrapper, "", &root, &mut Vec::new(), replacer.as_ref())?;
    // A BigInt anywhere in a serializable position is a TypeError (JSON has no
    // bigint form), matching Node's exact message.
    if with_host(|h| json_has_bigint(h, &v)) {
        return Err(host::type_error("Do not know how to serialize a BigInt"));
    }
    let indent = match args.get(2) {
        Some(Value::Float(f)) => " ".repeat((*f as usize).min(10)),
        Some(other) => with_host(|h| h.as_str(other)).unwrap_or_default(),
        None => String::new(),
    };
    // A replacer array (args[1]) restricts which object keys are serialized.
    let keys: Option<Vec<String>> = args.get(1).and_then(|r| {
        with_host(|h| match h.get(r) {
            Some(JsObj::Array(items)) => {
                Some(items.iter().map(|k| h.str_of(k)).collect::<Vec<_>>())
            }
            _ => None,
        })
    });
    let s = with_host(|h| json_str(h, &v, &indent, 0, keys.as_deref()));
    match s {
        Some(s) => Ok(with_host(|h| h.new_str(s))),
        None => Ok(Value::Undef),
    }
}

/// One `SerializeJSONProperty(key, holder)` step: rewrite `v` (the value read
/// from `holder[key]`) by calling its `toJSON(key)` and then the replacer
/// function as `replacer.call(holder, key, value)`, then recurse into whatever
/// object survives. Applies to user methods, class methods, and the native
/// `Date`/`Buffer`/`URL` accessors alike.
///
/// Returns a fresh tree; the input is never mutated. `path` carries the chain of
/// objects currently being walked so a cyclic structure is reported rather than
/// spinning forever.
///
/// `toJSON` is called on the value ONCE and is NOT re-applied to its own result
/// — `{toJSON(){ return {toJSON(){ return 1 }} }}` serializes as `{}` in Node,
/// because the inner method is a plain (unserializable) function property of the
/// returned object, not a second conversion hook.
fn apply_to_json(
    holder: &Value,
    key: &str,
    v: &Value,
    path: &mut JsonPath,
    rep: Option<&Value>,
) -> Result<Value, String> {
    let mut v = v.clone();
    if matches!(v, Value::Obj(_)) {
        let tag = crate::stdlib::native_tag(&v);
        // 25.5.2.1 step 2: `toJSON` is looked up with `[[Get]]`, so a PROXY
        // supplies one through its `get` trap. `lookup_chain` walks the
        // property map and never asks the handler, so a proxy carrying a
        // `toJSON` was serialized as a plain object instead of by its own
        // method — and node's trap log starts with that `get`.
        let to_json = if with_host(|h| h.kind_of(&v)) == Some(ObjKind::Proxy) {
            get_property(&v, "toJSON")?
        } else {
            with_host(|h| host::lookup_chain(h, &v, "toJSON")).unwrap_or(Value::Undef)
        };
        let has_to_json = with_host(|h| host::is_callable(h, &to_json))
            || tag
                .as_deref()
                .map(crate::stdlib::has_to_json)
                .unwrap_or(false);
        if has_to_json {
            let k = with_host(|h| h.new_str(key.to_string()));
            v = host::call_method(&v, "toJSON", vec![k])?;
        }
    }
    if let Some(rep) = rep {
        let k = with_host(|h| h.new_str(key.to_string()));
        v = host::invoke(rep, vec![k, v.clone()], Some(holder.clone()))?;
    }
    // How `v` was reached from its holder, as V8 names the step in a
    // circular-structure message: `index 1` under an array, else `property 'k'`.
    let via = if matches!(with_host(|h| h.get(holder).cloned()), Some(JsObj::Array(_))) {
        format!("index {key}")
    } else {
        format!("property '{key}'")
    };
    json_walk_children(&v, path, &via, rep)
}

/// The objects `JSON.stringify` is inside of, outermost first, each with the
/// step that reached it from its holder (`property 'x'` / `index 1`).
type JsonPath = Vec<(String, Value)>;

/// V8's `ConstructCircularStructureErrorMessage`: the cycle from the object it
/// starts at to the key that closes it. At most the first two and the last one
/// intermediate step are listed, with `|     ...` standing for the rest.
fn circular_json_message(path: &JsonPath, start: usize, closing: &str) -> String {
    const PREFIX: usize = 2;
    const POSTFIX: usize = 1;
    let ctor = |v: &Value| -> String {
        with_host(|h| match h.get(v) {
            Some(JsObj::Array(_)) if h.proto_of(v).is_none() => "Array".to_string(),
            _ => match h.ctor_name(v) {
                n if n.is_empty() => "Object".to_string(),
                n => n,
            },
        })
    };
    let line = |i: usize| {
        format!(
            "\n    |     {} -> object with constructor '{}'",
            path[i].0,
            ctor(&path[i].1)
        )
    };
    let mut msg = format!(
        "Converting circular structure to JSON\n    --> starting at object with constructor '{}'",
        ctor(&path[start].1)
    );
    let prefix_end = path.len().min(start + 1 + PREFIX);
    for i in start + 1..prefix_end {
        msg.push_str(&line(i));
    }
    if path.len() > prefix_end + POSTFIX {
        msg.push_str("\n    |     ...");
    }
    for i in prefix_end.max(path.len().saturating_sub(POSTFIX))..path.len() {
        msg.push_str(&line(i));
    }
    msg.push_str(&format!("\n    --- {closing} closes the circle"));
    msg
}

/// Whether a raw property key of a host object is one `json_str` serializes. The
/// internal slots (`@@`-prefixed symbol keys, `#`-prefixed private fields) are
/// invisible to JSON, so the replacer must not be invoked for them either.
fn json_visible_key(k: &str) -> bool {
    !k.starts_with("@@") && !k.starts_with('#')
}

/// Recurse into the elements/properties of an already-converted value, running
/// `apply_to_json` for each with this value as the holder.
fn json_walk_children(
    v: &Value,
    path: &mut JsonPath,
    via: &str,
    rep: Option<&Value>,
) -> Result<Value, String> {
    if !matches!(v, Value::Obj(_)) {
        return Ok(v.clone());
    }
    // A value that contains itself has no JSON form.
    if let Some(start) = with_host(|h| path.iter().position(|(_, p)| h.strict_eq(p, v))) {
        return Err(host::type_error(&circular_json_message(path, start, via)));
    }
    // A Proxy owns no property map, so it is snapshotted through its traps into
    // the plain array/object `SerializeJSONArray`/`SerializeJSONObject` describe
    // — which read every member through `[[Get]]`, exactly as the snapshot does.
    if with_host(|h| h.kind_of(v)) == Some(ObjKind::Proxy) {
        let snap = crate::proxy::json_snapshot(v)?;
        path.push((via.to_string(), v.clone()));
        let out = json_walk_children(&snap, path, via, rep);
        path.pop();
        return out;
    }
    let obj = with_host(|h| h.get(v).cloned());
    path.push((via.to_string(), v.clone()));
    let out = (|| match obj {
        Some(JsObj::Array(items)) => {
            // Read the elements through the accessor-aware funnel: an index
            // with a getter must be SERIALIZED as what the getter returns, and
            // the backing vector still holds the stale slot.
            let mut resolved = items;
            // An index with a getter must be SERIALIZED as what the getter
            // returns, and it also forces a rebuild below: keeping the original
            // array would hand the serializer back the stale backing vector.
            let had_accessor = resolve_index_accessors(v, &mut resolved);
            let items = resolved;
            let mut out = Vec::with_capacity(items.len());
            let mut changed = had_accessor;
            for (i, it) in items.iter().enumerate() {
                let nv = apply_to_json(v, &i.to_string(), it, path, rep)?;
                changed |= !with_host(|h| h.strict_eq(&nv, it));
                out.push(nv);
            }
            // Keep identity when nothing changed, so an enclosing object is not
            // needlessly rebuilt (which would drop its property attributes).
            if changed {
                Ok(with_host(|h| h.new_array(out)))
            } else {
                Ok(v.clone())
            }
        }
        Some(JsObj::Object(props)) => {
            // An enumerable own accessor must have its getter RUN and the result
            // serialized. That cannot happen inside `json_str` (which holds the
            // host borrow), so materialize here — the same reason `toJSON` is
            // applied in this pass.
            let has_accessor = with_host(|h| {
                h.own_accessor_keys(v)
                    .iter()
                    .any(|k| h.prop_attrs(v, k).enumerable)
            });
            if has_accessor {
                let mut next: IndexMap<String, Value> = IndexMap::new();
                for (k, val) in host::own_enum_entries_deep(v)? {
                    let nv = if json_visible_key(&k) {
                        apply_to_json(v, &k, &val, path, rep)?
                    } else {
                        val
                    };
                    next.insert(k, nv);
                }
                return Ok(with_host(|h| h.new_object(next)));
            }
            // Only rebuild when a descendant actually changed, so plain data keeps
            // its identity (and its prototype / native tag).
            let mut next: IndexMap<String, Value> = IndexMap::new();
            let mut changed = false;
            for (k, val) in &props {
                let nv = if json_visible_key(k) {
                    apply_to_json(v, k, val, path, rep)?
                } else {
                    val.clone()
                };
                changed |= !with_host(|h| h.strict_eq(&nv, val));
                next.insert(k.clone(), nv);
            }
            if changed {
                Ok(with_host(|h| {
                    let o = h.new_object(next);
                    h.copy_prop_attrs(v, &o);
                    o
                }))
            } else {
                Ok(v.clone())
            }
        }
        _ => Ok(v.clone()),
    })();
    path.pop();
    out
}

/// Whether a value tree contains a `BigInt` in a position `JSON.stringify` would
/// try to serialize (a value in an array/object) — such a value throws.
fn json_has_bigint(h: &host::JsHost, v: &Value) -> bool {
    match h.get(v) {
        Some(JsObj::BigInt(_)) => true,
        Some(JsObj::Array(items)) => items.iter().any(|x| json_has_bigint(h, x)),
        Some(JsObj::Object(props)) => props
            .iter()
            .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
            .any(|(_, val)| json_has_bigint(h, val)),
        _ => false,
    }
}

fn json_str(
    h: &host::JsHost,
    v: &Value,
    indent: &str,
    depth: usize,
    keys: Option<&[String]>,
) -> Option<String> {
    let sep = if indent.is_empty() { ":" } else { ": " };
    match v {
        Value::Undef => None,
        Value::Bool(b) => Some(if *b { "true".into() } else { "false".into() }),
        Value::Int(n) => Some(n.to_string()),
        Value::Float(f) => Some(if f.is_finite() {
            host::fmt_number(*f)
        } else {
            "null".into()
        }),
        Value::Str(s) => Some(json_quote(s)),
        Value::Obj(_) => match h.get(v) {
            Some(JsObj::Str(s)) => Some(json_quote(s)),
            Some(JsObj::Null) => Some("null".into()),
            // A `JSON.rawJSON` marker contributes its text VERBATIM — that is the
            // whole point of it, and it is why a number wider than a `double`
            // can survive a round trip.
            _ if h.fn_prop(v, "@@rawJSON").is_some() => match h.get(v) {
                Some(JsObj::Object(p)) => p.get("rawJSON").map(|r| h.str_of(r)),
                _ => None,
            },
            // A Map/Set has no ENTRIES to serialize (they are internal slots),
            // but any own property a script attached is serialized like an
            // ordinary object's: `JSON.stringify(Object.assign(new Map(), {a:1}))`
            // is `{"a":1}`.
            Some(JsObj::Map { .. })
            | Some(JsObj::Set { .. })
            | Some(JsObj::RegExp(_))
            // A Promise and a generator are ORDINARY objects to the serializer:
            // their state is internal slots, so they contribute no entries and
            // render as `{}`. They were being omitted entirely instead, so a
            // promise in an array became `null` and one in an object vanished.
            | Some(JsObj::Promise { .. })
            | Some(JsObj::Generator { .. }) => {
                let parts: Vec<String> = h
                    .own_enum_entries(v)
                    .into_iter()
                    .filter(|(k, _)| !k.starts_with("@@") && !host::is_symbol_key(k))
                    .filter_map(|(k, val)| {
                        json_str(h, &val, indent, depth + 1, keys)
                            .map(|s| format!("{}{sep}{s}", json_quote(&k)))
                    })
                    .collect();
                Some(wrap(&parts, "{", "}", indent, depth))
            }
            // A NON-callable builtin is a namespace object, not a function, so
            // it serializes as one: `JSON.stringify(Math)` is `{}` (its members
            // are all non-enumerable), where omitting it made the whole property
            // disappear from its holder.
            Some(JsObj::Builtin(n)) if !host::builtin_is_callable(n) => {
                let parts: Vec<String> = crate::stdlib::namespace_keys(n)
                    .into_iter()
                    .filter_map(|k| {
                        let val = h.builtin_static(n, &k)?;
                        json_str(h, &val, indent, depth + 1, keys)
                            .map(|s| format!("{}{sep}{s}", json_quote(&k)))
                    })
                    .collect();
                Some(wrap(&parts, "{", "}", indent, depth))
            }
            // Functions and symbols are omitted (undefined) as values.
            Some(JsObj::Func(_))
            | Some(JsObj::Builtin(_))
            | Some(JsObj::BoundMethod { .. })
            | Some(JsObj::BoundFunc { .. })
            | Some(JsObj::Class(_))
            | Some(JsObj::Symbol { .. }) => None,
            Some(JsObj::Array(items)) => {
                if items.is_empty() {
                    return Some("[]".into());
                }
                let parts: Vec<String> = items
                    .iter()
                    .map(|x| {
                        json_str(h, x, indent, depth + 1, keys).unwrap_or_else(|| "null".into())
                    })
                    .collect();
                Some(wrap(&parts, "[", "]", indent, depth))
            }
            Some(JsObj::Object(props)) if props.contains_key("@@primitive") => {
                // 25.5.2.2 step 4: a String/Number/Boolean wrapper serializes as
                // the primitive it boxes, not as the object holding it —
                // `JSON.stringify(new Number(1))` is `1`, not `{}`.
                json_str(h, &props["@@primitive"].clone(), indent, depth, keys)
            }
            Some(JsObj::Object(props)) => {
                // A replacer array restricts (and orders) which keys are emitted.
                let parts: Vec<String> = match keys {
                    Some(allow) => allow
                        .iter()
                        .filter_map(|k| {
                            props.get(k).and_then(|val| {
                                json_str(h, val, indent, depth + 1, keys)
                                    .map(|vs| format!("{}{sep}{vs}", json_quote(k)))
                            })
                        })
                        .collect(),
                    None => h
                        .own_enum_entries(v)
                        .iter()
                        .filter_map(|(k, val)| {
                            json_str(h, val, indent, depth + 1, keys)
                                .map(|vs| format!("{}{sep}{vs}", json_quote(k)))
                        })
                        .collect(),
                };
                if parts.is_empty() {
                    return Some("{}".into());
                }
                Some(wrap(&parts, "{", "}", indent, depth))
            }
            _ => Some("null".into()),
        },
        _ => Some("null".into()),
    }
}

fn wrap(parts: &[String], open: &str, close: &str, indent: &str, depth: usize) -> String {
    if indent.is_empty() {
        format!("{open}{}{close}", parts.join(","))
    } else {
        let pad = indent.repeat(depth + 1);
        let pad_close = indent.repeat(depth);
        format!(
            "{open}\n{pad}{}\n{pad_close}{close}",
            parts.join(&format!(",\n{pad}"))
        )
    }
}

fn json_quote(s: &str) -> String {
    let mut out = String::from("\"");
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            // QuoteJSONString (25.5.2.2) names SIX short escapes, not four.
            // Backspace and form feed were missing, so they fell through to the
            // `\uXXXX` arm below and `JSON.stringify("\b")` produced
            // `""` where node produces `"\b"`. Both parse back to the same
            // string, so the difference is invisible to a round trip and shows
            // up only as a byte mismatch against a fixture or a checksum.
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}

fn json_parse(args: Vec<Value>) -> Result<Value, String> {
    let s = with_host(|h| h.str_of(&arg0(&args)));
    let mut p = JsonParser {
        chars: s.chars().collect(),
        pos: 0,
        prims: Vec::new(),
        record: args
            .get(1)
            .is_some_and(|r| with_host(|h| host::is_callable(h, r))),
    };
    p.skip_ws();
    if p.peek().is_none() {
        return Err("SyntaxError: Unexpected end of JSON input".into());
    }
    let v = p.parse_value()?;
    let value_end = p.pos;
    p.skip_ws();
    // Anything after the top-level value is an error — the parser used to accept
    // and silently discard it, so `JSON.parse('{"a":1}x')` succeeded.
    if let Some(c) = p.peek() {
        // V8 names the token kind only when it butts directly against the value
        // (`01` -> "Unexpected number at position 1"); with whitespace between
        // it is just a non-whitespace character (`1 2`).
        // Only a digit butted directly against a completed number literal —
        // V8's number scanner is still in number context there. `5"x"` and
        // `[0,1]0` exit the scanner cleanly and get the generic message.
        let after_number = value_end > 0
            && p.pos == value_end
            && p.chars[value_end - 1].is_ascii_digit()
            && c.is_ascii_digit();
        return Err(if after_number {
            p.err_at("Unexpected number", p.pos)
        } else {
            p.err_trailing(p.pos)
        });
    }
    // Optional reviver: walk bottom-up, transforming each (key, value).
    if let Some(reviver) = args
        .get(1)
        .filter(|r| with_host(|h| host::is_callable(h, r)))
        .cloned()
    {
        // The top-level holder is a fresh `{ "": value }` wrapper, as the spec
        // constructs before the walk.
        let root = with_host(|h| {
            let mut m: IndexMap<String, Value> = IndexMap::new();
            m.insert(String::new(), v.clone());
            h.new_object(m)
        });
        return json_revive("", v, &reviver, &root, &p.prims, &mut 0);
    }
    Ok(v)
}

/// `JSON.parse` reviver walk: recurse into children first, then call
/// `reviver(key, value)`; a returned `undefined` drops the property.
///
/// The reviver runs with the HOLDER as `this` (25.5.1.1
/// InternalizeJSONProperty) — the object or array the key lives in, and at the
/// top level a wrapper `{ "": value }`. It was being called with no receiver,
/// so `this` was undefined and a reviver could not reach its siblings.
/// `JSON.rawJSON(text)` — a marker object whose text `JSON.stringify` emits
/// VERBATIM, so a number too large for a `double` survives a round trip
/// (`JSON.stringify({n: JSON.rawJSON("12345678901234567890")})`).
///
/// The validation is not "does `JSON.parse` accept it": node's rule, measured
/// across the whole matrix, is
///
/// ```text
/// ""                 -> SyntaxError: Invalid value for JSON.rawJSON
/// leading whitespace -> the parse error for that first character
/// a complete literal -> ok
/// anything left over -> SyntaxError: Invalid value for JSON.rawJSON
/// a broken literal   -> the parse error the scanner raised
/// ```
///
/// so `" 1"` reports an unexpected token while `"1 "` and `"1,2"` report the
/// invalid-value message even though `JSON.parse` accepts the former and gives
/// a token error for the latter.
fn json_raw(args: Vec<Value>) -> Result<Value, String> {
    const INVALID: &str = "SyntaxError: Invalid value for JSON.rawJSON";
    let s = with_host(|h| h.str_of(&arg0(&args)));
    if s.is_empty() {
        return Err(INVALID.into());
    }
    let mut p = JsonParser {
        chars: s.chars().collect(),
        pos: 0,
        prims: Vec::new(),
        record: false,
    };
    // An object or an array is rejected where it starts, as leading whitespace
    // is — both are "not a primitive", but node reports the token.
    if matches!(p.peek(), Some('{') | Some('[')) || p.peek().is_some_and(|c| c.is_whitespace()) {
        return Err(p.err_token(0));
    }
    p.parse_value()?;
    if p.pos != p.chars.len() {
        // A digit butted against a completed number is still in the number
        // scanner, so `"01"` reports the scanner's error rather than leftover
        // input — the same distinction `json_parse` draws for trailing text.
        if p.chars[p.pos - 1].is_ascii_digit() && p.chars[p.pos].is_ascii_digit() {
            return Err(p.err_at("Unexpected number", p.pos));
        }
        return Err(INVALID.into());
    }
    // A null prototype and one own `rawJSON` property, frozen — the brand is a
    // hidden slot so `Object.keys` stays `["rawJSON"]`.
    Ok(with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        let text = h.new_str(s);
        m.insert("rawJSON".into(), text);
        let o = h.new_object(m);
        let null = h.null();
        h.set_proto(&o, null);
        h.set_fn_prop(&o, "@@rawJSON", Value::Bool(true));
        h.seal_object(&o, true);
        o
    }))
}

/// `JSON.isRawJSON(v)` — the brand check. A hand-built `{ rawJSON: "1" }` is
/// NOT one, which is why the marker is a hidden slot rather than the property.
fn json_is_raw(args: Vec<Value>) -> Result<Value, String> {
    Ok(Value::Bool(is_raw_json(&arg0(&args))))
}

fn is_raw_json(v: &Value) -> bool {
    with_host(|h| h.fn_prop(v, "@@rawJSON")).is_some()
}

fn json_revive(
    key: &str,
    val: Value,
    reviver: &Value,
    holder: &Value,
    prims: &[String],
    next: &mut usize,
) -> Result<Value, String> {
    // A PRIMITIVE claims the next recorded source slice before its children
    // would — it has none — and a container claims nothing. The walk descends in
    // the same order the parse produced them, so one cursor lines the two up.
    let is_container =
        with_host(|h| matches!(h.get(&val), Some(JsObj::Array(_)) | Some(JsObj::Object(_))));
    let source = if !is_container {
        let s = prims.get(*next).cloned();
        if s.is_some() {
            *next += 1;
        }
        s
    } else {
        None
    };
    match with_host(|h| h.get(&val).cloned()) {
        Some(JsObj::Array(items)) => {
            for i in 0..items.len() {
                let elem = with_host(|h| match h.get(&val) {
                    Some(JsObj::Array(it)) => it[i].clone(),
                    _ => Value::Undef,
                });
                let nv = json_revive(&i.to_string(), elem, reviver, &val, prims, next)?;
                with_host(|h| {
                    if let Some(JsObj::Array(it)) = h.get_mut(&val) {
                        it[i] = nv;
                    }
                });
            }
        }
        Some(JsObj::Object(props)) => {
            let keys: Vec<String> = props
                .keys()
                .filter(|k| !k.starts_with("@@"))
                .cloned()
                .collect();
            for k in keys {
                let elem = with_host(|h| match h.get(&val) {
                    Some(JsObj::Object(p)) => p.get(&k).cloned().unwrap_or(Value::Undef),
                    _ => Value::Undef,
                });
                let nv = json_revive(&k, elem, reviver, &val, prims, next)?;
                with_host(|h| {
                    if let Some(JsObj::Object(p)) = h.get_mut(&val) {
                        if matches!(nv, Value::Undef) {
                            p.shift_remove(&k);
                        } else {
                            p.insert(k.clone(), nv);
                        }
                    }
                });
            }
        }
        _ => {}
    }
    let kv = with_host(|h| h.new_str(key.to_string()));
    // 25.5.1.1 step 2.b: the reviver's THIRD argument. `{ source }` for a
    // primitive, an empty object for an array or an object — node passes it
    // either way, and code reading `ctx.source` used to die on `undefined`
    // because only two arguments were passed.
    let ctx = with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        if let Some(s) = source {
            let sv = h.new_str(s);
            m.insert("source".into(), sv);
        }
        h.new_object(m)
    });
    host::invoke(reviver, vec![kv, val, ctx], Some(holder.clone()))
}

struct JsonParser {
    chars: Vec<char>,
    pos: usize,
    /// Source text of each PRIMITIVE value, in parse order — what the reviver's
    /// third argument reports as `context.source` (25.5.1.1). Only collected
    /// when a reviver was supplied.
    ///
    /// A flat list rather than a parallel tree because the reviver walk visits
    /// primitives in the same depth-first order the parse produced them, so an
    /// index into this is enough to line them up.
    prims: Vec<String>,
    record: bool,
}
impl JsonParser {
    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    /// `at position N (line L column C)` — the location suffix V8 appends to the
    /// positional JSON parse errors. Positions are in UTF-16-ish code units;
    /// node-js counts `char`s, which agree for the BMP.
    fn at(&self, pos: usize) -> String {
        let mut line = 1usize;
        let mut col = 1usize;
        for c in &self.chars[..pos.min(self.chars.len())] {
            if *c == '\n' {
                line += 1;
                col = 1;
            } else {
                col += 1;
            }
        }
        format!(" at position {pos} (line {line} column {col})")
    }

    /// A positional error (`Expected ':' after property name in JSON at …`).
    fn err_at(&self, what: &str, pos: usize) -> String {
        format!("SyntaxError: {what} in JSON{}", self.at(pos))
    }

    /// The one positional message V8 does NOT suffix with `in JSON`.
    fn err_trailing(&self, pos: usize) -> String {
        format!(
            "SyntaxError: Unexpected non-whitespace character after JSON{}",
            self.at(pos)
        )
    }

    /// V8's default parse error: the offending character plus a window of the
    /// source. The whole input is quoted when it is short (<= 20 chars);
    /// otherwise a 10-character context window either side of `pos` is shown,
    /// elided with `...` on whichever side was cut.
    fn err_token(&self, pos: usize) -> String {
        const MAX_WHOLE: usize = 20;
        const CONTEXT: usize = 10;
        let len = self.chars.len();
        let Some(c) = self.chars.get(pos) else {
            return "SyntaxError: Unexpected end of JSON input".into();
        };
        // V8 reports the whole input for the JS literals that are famously not
        // JSON, without naming an offending character.
        let whole: String = self.chars.iter().collect();
        if matches!(
            whole.as_str(),
            "undefined" | "NaN" | "Infinity" | "-Infinity"
        ) {
            return format!("SyntaxError: \"{whole}\" is not valid JSON");
        }
        let snippet = if len <= MAX_WHOLE {
            format!("\"{whole}\"")
        } else {
            let start = pos.saturating_sub(CONTEXT);
            let end = (pos + CONTEXT).min(len);
            let body: String = self.chars[start..end].iter().collect();
            let head = if start > 0 { "..." } else { "" };
            let tail = if end < len { "..." } else { "" };
            format!("{head}\"{body}\"{tail}")
        };
        format!("SyntaxError: Unexpected token '{c}', {snippet} is not valid JSON")
    }

    fn skip_ws(&mut self) {
        while matches!(
            self.peek(),
            Some(' ') | Some('\n') | Some('\t') | Some('\r')
        ) {
            self.pos += 1;
        }
    }
    fn parse_value(&mut self) -> Result<Value, String> {
        self.skip_ws();
        let start = self.pos;
        let prim = matches!(self.peek(), Some(c) if c != '{' && c != '[');
        let v = match self.peek() {
            Some('{') => self.parse_object(),
            Some('[') => self.parse_array(),
            Some('"') => {
                let s = self.parse_string()?;
                Ok(with_host(|h| h.new_str(s)))
            }
            Some('t') | Some('f') => self.parse_bool(),
            Some('n') => {
                self.expect_lit("null")?;
                Ok(with_host(|h| h.null()))
            }
            Some(c) if c == '-' || c.is_ascii_digit() => self.parse_number(),
            None => Err("SyntaxError: Unexpected end of JSON input".into()),
            _ => Err(self.err_token(self.pos)),
        }?;
        if prim && self.record {
            self.prims
                .push(self.chars[start..self.pos].iter().collect());
        }
        Ok(v)
    }
    fn expect_lit(&mut self, lit: &str) -> Result<(), String> {
        for ch in lit.chars() {
            match self.peek() {
                Some(c) if c == ch => self.pos += 1,
                // V8 reports the first character that broke the literal, which is
                // why `foo` complains about `'o'` (index 2) and not `'f'`.
                None => return Err("SyntaxError: Unexpected end of JSON input".into()),
                _ => return Err(self.err_token(self.pos)),
            }
        }
        Ok(())
    }
    fn parse_bool(&mut self) -> Result<Value, String> {
        if self.peek() == Some('t') {
            self.expect_lit("true")?;
            Ok(Value::Bool(true))
        } else {
            self.expect_lit("false")?;
            Ok(Value::Bool(false))
        }
    }
    /// JSON's number grammar: `-? (0 | [1-9][0-9]*) (. [0-9]+)? ([eE] [+-]? [0-9]+)?`.
    /// A leading zero does NOT swallow the following digits — `01` parses as `0`
    /// and the stray `1` becomes a trailing-token error, which is how V8 reports
    /// it. Each way the grammar can run out has its own message.
    fn parse_number(&mut self) -> Result<Value, String> {
        let start = self.pos;
        if self.peek() == Some('-') {
            self.pos += 1;
            if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
                return Err(self.err_at("No number after minus sign", self.pos));
            }
        }
        if self.peek() == Some('0') {
            self.pos += 1;
        } else {
            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
                self.pos += 1;
            }
        }
        if self.peek() == Some('.') {
            self.pos += 1;
            if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
                return Err(self.err_at("Unterminated fractional number", self.pos));
            }
            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
                self.pos += 1;
            }
        }
        if matches!(self.peek(), Some('e') | Some('E')) {
            self.pos += 1;
            if matches!(self.peek(), Some('+') | Some('-')) {
                self.pos += 1;
            }
            if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
                return Err(self.err_at("Exponent part is missing a number", self.pos));
            }
            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
                self.pos += 1;
            }
        }
        let s: String = self.chars[start..self.pos].iter().collect();
        s.parse::<f64>()
            .map(Value::Float)
            .map_err(|_| self.err_at("Unexpected number", start))
    }
    fn parse_string(&mut self) -> Result<String, String> {
        self.pos += 1; // opening quote
        let mut out = String::new();
        loop {
            match self.peek() {
                None => return Err(self.err_at("Unterminated string", self.pos)),
                Some('"') => {
                    self.pos += 1;
                    break;
                }
                Some('\\') => {
                    self.pos += 1;
                    match self.peek() {
                        Some('n') => out.push('\n'),
                        Some('t') => out.push('\t'),
                        Some('r') => out.push('\r'),
                        Some('"') => out.push('"'),
                        Some('\\') => out.push('\\'),
                        Some('/') => out.push('/'),
                        Some('b') => out.push('\u{08}'),
                        Some('f') => out.push('\u{0C}'),
                        Some('u') => {
                            let h: String = self.chars
                                [self.pos + 1..(self.pos + 5).min(self.chars.len())]
                                .iter()
                                .collect();
                            if let Ok(n) = u32::from_str_radix(&h, 16) {
                                if let Some(ch) = char::from_u32(n) {
                                    out.push(ch);
                                }
                            }
                            self.pos += 4;
                        }
                        _ => {}
                    }
                    self.pos += 1;
                }
                // A raw control character is not legal inside a JSON string; it
                // has to be escaped. V8 rejects it rather than passing it through.
                Some(c) if (c as u32) < 0x20 => {
                    return Err(self.err_at("Bad control character in string literal", self.pos))
                }
                Some(c) => {
                    out.push(c);
                    self.pos += 1;
                }
            }
        }
        Ok(out)
    }
    fn parse_array(&mut self) -> Result<Value, String> {
        self.pos += 1; // [
        let mut items = Vec::new();
        self.skip_ws();
        if self.peek() == Some(']') {
            self.pos += 1;
            return Ok(with_host(|h| h.new_array(items)));
        }
        loop {
            items.push(self.parse_value()?);
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    self.pos += 1;
                }
                Some(']') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err(self.err_at("Expected ',' or ']' after array element", self.pos)),
            }
        }
        Ok(with_host(|h| h.new_array(items)))
    }
    fn parse_object(&mut self) -> Result<Value, String> {
        self.pos += 1; // {
        let mut props: IndexMap<String, Value> = IndexMap::new();
        self.skip_ws();
        if self.peek() == Some('}') {
            self.pos += 1;
            return Ok(with_host(|h| h.new_object(props)));
        }
        loop {
            self.skip_ws();
            if self.peek() != Some('"') {
                // The first key uses the "or '}'" wording (an empty object is
                // still legal there); a key after a comma does not. End of input
                // reports the same expectation, at the end position.
                return Err(if props.is_empty() {
                    self.err_at("Expected property name or '}'", self.pos)
                } else {
                    self.err_at("Expected double-quoted property name", self.pos)
                });
            }
            let key = self.parse_string()?;
            self.skip_ws();
            if self.peek() != Some(':') {
                return Err(match self.peek() {
                    None => "SyntaxError: Unexpected end of JSON input".into(),
                    _ => self.err_at("Expected ':' after property name", self.pos),
                });
            }
            self.pos += 1;
            let val = self.parse_value()?;
            props.insert(key, val);
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    self.pos += 1;
                }
                Some('}') => {
                    self.pos += 1;
                    break;
                }
                _ => return Err(self.err_at("Expected ',' or '}' after property value", self.pos)),
            }
        }
        Ok(with_host(|h| h.new_object(props)))
    }
}

// ══ type methods (array / string / number) ═══════════════════════════════════

fn is_array_method(name: &str) -> bool {
    matches!(
        name,
        "push"
            | "pop"
            | "shift"
            | "unshift"
            | "map"
            | "filter"
            | "forEach"
            | "join"
            | "slice"
            | "indexOf"
            | "lastIndexOf"
            | "includes"
            | "reduce"
            | "concat"
            | "reverse"
            | "sort"
            | "find"
            | "findIndex"
            | "some"
            | "every"
            | "flat"
            | "fill"
            | "splice"
            | "keys"
            | "values"
            | "entries"
            | "flatMap"
            | "at"
            | "toString"
            | "reduceRight"
            | "findLast"
            | "findLastIndex"
            | "copyWithin"
    )
}
/// Every `String.prototype` method node-js implements.
///
/// A LIST rather than a `matches!` arm because the same set has to be installed
/// on the real `String.prototype` object: a method read off the prototype
/// (`String.prototype.trim.call(s)`, the generic-borrowing idiom libraries use)
/// found nothing there, so the two views of "which methods exist" would drift
/// if they were written twice.
pub(crate) const STRING_PROTO_METHODS: &[&str] = &[
    "toUpperCase",
    "toLowerCase",
    "charAt",
    "charCodeAt",
    "codePointAt",
    "indexOf",
    "lastIndexOf",
    "includes",
    "slice",
    "substring",
    "substr",
    "split",
    "trim",
    "trimStart",
    "trimEnd",
    "replace",
    "replaceAll",
    "repeat",
    "startsWith",
    "endsWith",
    "padStart",
    "padEnd",
    "concat",
    "at",
    "toString",
    "toLocaleString",
    "valueOf",
    "match",
    "matchAll",
    "search",
    "normalize",
    "localeCompare",
    "toLocaleUpperCase",
    "toLocaleLowerCase",
    "isWellFormed",
    "toWellFormed",
];

fn is_string_method(name: &str) -> bool {
    STRING_PROTO_METHODS.contains(&name)
}

/// Every SYMBOL-keyed intrinsic method the generated table lists for `ctor`,
/// spelled the way this frontend spells the key (`@@iterator`).
///
/// A prototype built as a REAL object (`String.prototype`, `URLSearchParams
/// .prototype`) installs its methods from a list, and only the string-keyed
/// list was walked — so `String.prototype[Symbol.iterator]` read `undefined`
/// while `Array.prototype[Symbol.iterator]`, which resolves through the
/// `Builtin` namespace and its table gate, answered a function. Derived from
/// the table rather than written out, so it cannot name a method node does not
/// define nor miss one it does.
pub(crate) fn proto_symbol_methods(ctor: &str) -> Vec<&'static str> {
    let prefix = format!("@proto:{ctor}:");
    crate::arity::BUILTIN_ARITY
        .iter()
        .filter_map(|(k, _, _)| k.strip_prefix(prefix.as_str()))
        .filter(|m| m.starts_with("@@"))
        .collect()
}

/// The builtin constructors whose `.prototype` object is BRANDED — every other
/// `<C>.prototype` is an ordinary object and reports `[object Object]`.
///
/// Measured on node v26.8.1 over every constructor this frontend knows:
///
/// ```text
/// Array/Object/Number/String/Boolean/Function   the ES5 legacy slot prototypes
/// Symbol/BigInt/Map/Set/WeakMap/WeakSet         carry an own @@toStringTag
/// Promise/Iterator/ArrayBuffer/DataView         "
/// WeakRef/FinalizationRegistry/URL              "
/// URLSearchParams/TextEncoder/TextDecoder       "
/// Date/RegExp/Error/TypeError/Uint8Array/…      [object Object]
/// ```
///
/// The rule this replaces branded EVERY `<C>.prototype` as `C`, so
/// `Object.prototype.toString.call(Date.prototype)` read `[object Date]` — and
/// a `Date.prototype.toString` call on a plain object named `[object Date]` in
/// its own failure message where node names `[object Object]`.
pub(crate) const BRANDED_PROTOS: &[&str] = &[
    "Array",
    "ArrayBuffer",
    "BigInt",
    "Boolean",
    "DataView",
    "FinalizationRegistry",
    "Function",
    "Iterator",
    "Map",
    "Number",
    "Object",
    "Promise",
    "Set",
    "SharedArrayBuffer",
    "String",
    "Symbol",
    "TextDecoder",
    "TextEncoder",
    "URL",
    "URLSearchParams",
    "WeakMap",
    "WeakRef",
    "WeakSet",
];

/// Whether `v` is a `RegExp` value (drives the regex path of `match`/`replace`/…).
/// A user `Symbol.match`/`replace`/`search`/`split`/`matchAll` method on the
/// ARGUMENT, which the string method must delegate to (22.1.3.x step 2).
///
/// `"abc".match(o)` where `o` defines `Symbol.match` calls that method rather
/// than coercing `o` to a pattern — the protocol every regexp-like library
/// implements. None of the five were consulted, so a custom matcher was
/// silently stringified instead.
fn symbol_protocol(arg: &Value, sym: &str) -> Option<Value> {
    if matches!(arg, Value::Undef) || with_host(|h| h.is_null(arg)) {
        return None;
    }
    let f = get_property(arg, sym).ok()?;
    with_host(|h| host::is_callable(h, &f)).then_some(f)
}

fn is_regexp_arg(v: &Value) -> bool {
    // 7.2.8 `IsRegExp` asks `Symbol.match` FIRST, so an object can declare
    // itself a regexp — or a real one can disown the label. Only the heap kind
    // was checked, so `"a".startsWith({[Symbol.match]: true})` did not throw
    // the TypeError the spec requires.
    if let Ok(m) = get_property(v, "@@match") {
        if !matches!(m, Value::Undef) {
            return with_host(|h| h.truthy(&m));
        }
    }
    with_host(|h| h.kind_of(v)) == Some(ObjKind::RegExp)
}

/// `str.replace(strPattern, fn)` — a function replacer against a literal (string)
/// pattern: replace the first (or all) occurrence, calling `fn(match, offset, s)`.
fn replace_str_fn(s: &str, pat: &str, repl: &Value, all: bool) -> Result<String, String> {
    if pat.is_empty() {
        return Ok(s.to_string());
    }
    let mut out = String::new();
    let mut rest = s;
    let mut base = 0usize;
    while let Some(pos) = rest.find(pat) {
        out.push_str(&rest[..pos]);
        let offset = base + pos;
        let m = with_host(|h| h.new_str(pat.to_string()));
        let str_arg = with_host(|h| h.new_str(s.to_string()));
        let r = host::invoke(repl, vec![m, Value::Float(offset as f64), str_arg], None)?;
        out.push_str(&with_host(|h| h.str_of(&r)));
        let consumed = pos + pat.len();
        base += consumed;
        rest = &rest[consumed..];
        if !all {
            break;
        }
    }
    out.push_str(rest);
    Ok(out)
}
/// Every `Number.prototype` method node-js implements — a list for the same
/// reason [`STRING_PROTO_METHODS`] is one.
pub(crate) const NUMBER_PROTO_METHODS: &[&str] = &[
    "toFixed",
    "toExponential",
    "toString",
    "toPrecision",
    "toLocaleString",
    "valueOf",
];

fn is_number_method(name: &str) -> bool {
    NUMBER_PROTO_METHODS.contains(&name)
}

/// The exotic kinds whose own dispatch table does NOT already reach the
/// `Object.prototype` methods, so the inherited ones have to be routed to.
///
/// An allowlist rather than a catch-all: a primitive receiver also reaches this
/// function, and a Number's `toString` is `Number.prototype.toString` — routing
/// it to the object form made `(255).toString(16)` report `[object Number]`.
fn inherits_object_methods(recv: &Value) -> bool {
    matches!(
        with_host(|h| h.kind_of(recv)),
        Some(
            ObjKind::Map
                | ObjKind::Set
                | ObjKind::Promise
                | ObjKind::RegExp
                | ObjKind::Generator
                | ObjKind::Symbol
                | ObjKind::BigInt
                | ObjKind::Iter
        )
    )
}

/// Whether `recv`'s own prototype defines `name`, shadowing the
/// `Object.prototype` method of that name — `RegExp.prototype.toString` does,
/// `Map.prototype` does not.
fn overrides_object_method(recv: &Value, name: &str) -> bool {
    match with_host(|h| h.kind_of(recv)) {
        Some(ObjKind::Map) => is_map_method(name),
        Some(ObjKind::Set) => is_set_method(name),
        Some(ObjKind::RegExp) => crate::regexp::is_regexp_method(name),
        // A Symbol has its own `toString`; `valueOf` is the inherited one,
        // which returns the receiver — exactly what a symbol needs.
        Some(ObjKind::Symbol) => matches!(name, "toString" | "valueOf" | "@@toPrimitive"),
        Some(ObjKind::BigInt) => matches!(name, "toString" | "valueOf" | "toLocaleString"),
        _ => false,
    }
}

/// Dispatch `recv.name(args)` for the built-in prototype methods.
pub fn call_type_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    // A USER method on the receiver's prototype chain wins over the builtin of
    // the same name — that is how a `class X extends Array` method is reached,
    // since the dispatch below goes straight to the builtin table and has no
    // entry for it.
    //
    // Deliberately restricted to a user function: the shared `Object.prototype`
    // carries real `@proto:Object:*` thunks, so accepting any callable made a
    // bare `map.toString()` resolve to the object form instead of the builtin
    // one the exotic is supposed to use.
    if let Some(f) = with_host(|h| host::lookup_chain(h, recv, name)) {
        if matches!(
            with_host(|h| h.kind_of(&f)),
            Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc)
        ) {
            return host::invoke(&f, args, Some(recv.clone()));
        }
    }
    // A method synthesized from the receiver's KIND is unreachable once its
    // intrinsic prototype is off the chain. The read already answers
    // `undefined` for one; dispatch has its own table and would still have
    // called it, so `Object.setPrototypeOf(a, {}); a.join()` returned "1,2"
    // while `a.join` was `undefined` — the read and the call disagreeing again,
    // in the opposite direction from the monkey-patch case below.
    if !own_intrinsic_reachable(recv)
        && inherited_method_owner(recv, name).is_none()
        && !has_own_for_shadow(recv, name)
        && inherited_builtin_static(recv, name).is_none()
        && with_host(|h| host::lookup_chain(h, recv, name)).is_none()
    {
        return Err(host::type_error(&format!("{name} is not a function")));
    }
    // A method monkey-patched onto the receiver's intrinsic prototype. The READ
    // path resolves these, but dispatch goes straight to the builtin table and
    // never consults it, so `Array.prototype.last = f; [1].last()` threw "is not
    // a function" while `[1].last` WAS `f` — the read and the call disagreeing
    // about the same name, on the one path a polyfill actually uses.
    if !name.starts_with("@@") && !has_own_for_shadow(recv, name) {
        if let Some(f) = inherited_builtin_static(recv, name) {
            if with_host(|h| host::is_callable(h, &f)) {
                return host::invoke(&f, args, Some(recv.clone()));
            }
        }
    }
    // Every object INHERITS the `Object.prototype` methods, and an exotic that
    // does not define its own reaches them the same way. Each kind's dispatch
    // table below only knows its own methods, so `new Map().toString()`,
    // `promise.hasOwnProperty(k)` and `sym.toLocaleString()` all reported "is
    // not a function" — `Object.prototype.toString.call(m)` worked while
    // `m.toString()` did not.
    // The allowlist is the kinds whose own dispatch table below would otherwise
    // claim the name. Every OTHER receiver reaches an `Object.prototype` method
    // the same way — a function, a class and a bound function included, where
    // `f.hasOwnProperty(k)` reported "is not a function" even though the READ
    // resolved it. `inherited_method_owner` decides which prototype owns the
    // name, so a kind that defines its own still gets its own.
    if is_object_builtin_method(name)
        && (inherited_method_owner(recv, name) == Some("Object")
            || (inherits_object_methods(recv) && !overrides_object_method(recv, name)))
    {
        // `toString` goes through the branded form (20.1.3.6), which reads
        // `Symbol.toStringTag` and falls back to the receiver's own brand —
        // `[object Map]`, not the generic stringification.
        if name == "toString" {
            return proto_method(recv, "Object:toString", args);
        }
        return object_builtin_method(recv, name, args);
    }
    // `Object.prototype.valueOf` is inherited by every exotic that does not
    // override it (an Array does not), and returns the receiver. Without this
    // the `ToPrimitive` probe on `[o] + ''` reached `array_method("valueOf")`
    // and threw `valueOf is not a function`.
    if name == "valueOf"
        && matches!(
            with_host(|h| h.kind_of(recv)),
            Some(
                ObjKind::Array
                    | ObjKind::Map
                    | ObjKind::Set
                    | ObjKind::Generator
                    | ObjKind::Promise
                    | ObjKind::Iter
                    | ObjKind::RegExp
            )
        )
    {
        return Ok(recv.clone());
    }
    // Only the tag is needed to pick the branch — cloning the receiver here made
    // every `arr.push(x)` copy the whole array, so a fill loop was O(n^2).
    match with_host(|h| h.kind_of(recv)) {
        Some(ObjKind::Array) => array_method(recv, name, args),
        Some(ObjKind::Str) => {
            // `string_method` consumes the text itself, so this clone is the
            // payload, not a tag probe.
            let s = peek(recv, |o| match o {
                JsObj::Str(s) => Some(s.clone()),
                _ => None,
            })
            .unwrap_or_default();
            string_method(&s, name, args)
        }
        Some(ObjKind::Map) => map_method(recv, name, args),
        Some(ObjKind::Set) => set_method(recv, name, args),
        Some(ObjKind::Generator) if crate::stdlib::iterator::is_helper(name) => {
            crate::stdlib::iterator::call(recv, name, &args)
        }
        Some(ObjKind::Generator) => generator_method(recv, name, args),
        Some(ObjKind::Promise) => promise_method(recv, name, args),
        Some(ObjKind::Iter) if crate::stdlib::iterator::is_helper(name) => {
            crate::stdlib::iterator::call(recv, name, &args)
        }
        Some(ObjKind::Iter) => iter_method(recv, name, args),
        Some(ObjKind::Symbol) => symbol_method(recv, name, args),
        Some(ObjKind::BigInt) => {
            let b = peek(recv, |o| match o {
                JsObj::BigInt(b) => Some(b.clone()),
                _ => None,
            })
            .unwrap_or_default();
            bigint_method(&b, name, args)
        }
        Some(ObjKind::RegExp) => crate::regexp::regexp_method(recv, name, args),
        Some(ObjKind::Func) | Some(ObjKind::Class) | Some(ObjKind::BoundFunc) => {
            match function_builtin_method(recv, name, &args)? {
                Some(v) => Ok(v),
                None => Err(host::type_error(&format!("{name} is not a function"))),
            }
        }
        Some(ObjKind::Object) => {
            if let Some(f) = peek(recv, |o| match o {
                JsObj::Object(p) => p.get(name).cloned(),
                _ => None,
            }) {
                host::invoke(&f, args, Some(recv.clone()))
            } else if name == "hasOwnProperty" {
                let k = with_host(|h| h.str_of(&arg0(&args)));
                let has = peek(recv, |o| match o {
                    JsObj::Object(p) => Some(p.contains_key(&k)),
                    _ => None,
                })
                .unwrap_or(false);
                Ok(Value::Bool(has))
            } else if name == "toString" {
                Ok(with_host(|h| h.new_str("[object Object]")))
            } else {
                Err(host::type_error(&format!("{} is not a function", name)))
            }
        }
        _ => {
            // Primitive number/bool/string coercions.
            if let Value::Float(_) | Value::Int(_) = recv {
                return number_method(with_host(|h| h.to_number(recv)), name, args);
            }
            if let Some(s) = with_host(|h| h.as_str(recv)) {
                return string_method(&s, name, args);
            }
            // `Boolean.prototype` (20.3.3): a boolean is not a heap object here,
            // so it reached no branch at all and `true.toString()` threw `is not
            // a function`. Its three methods are `toString`, `valueOf`, and the
            // inherited `Object.prototype.toLocaleString` — which
            // `[1,'a',true].toLocaleString()` invokes per element, so the hole
            // was reachable from the array form too.
            if let Value::Bool(b) = recv {
                return match name {
                    "toString" | "toLocaleString" => {
                        Ok(new_s(if *b { "true" } else { "false" }.to_string()))
                    }
                    "valueOf" => Ok(Value::Bool(*b)),
                    _ => Err(host::type_error(&format!("{name} is not a function"))),
                };
            }
            Err(host::type_error(&format!("{} is not a function", name)))
        }
    }
}

/// A copy of the whole backing store, for the methods that genuinely consume
/// every element (`map`, `filter`, `join`, …). Never call it just to read
/// `.len()` — use [`array_len`], or `push`/`unshift` become O(n) per call.
/// A LIVE iterator over a `Map` or `Set`.
///
/// Node's collection iterators see the collection as it is at each step: an
/// entry added during iteration IS visited, and one deleted before it is
/// reached is NOT. Ours materialized every entry up front, so both were wrong —
/// a loop that deletes as it goes still processed the entries it had removed.
///
/// The cursor is the last key yielded plus the index it was at. On each step
/// the key is located again in the CURRENT order: if it is still there the next
/// entry follows it, and if it was itself deleted the stored index now names
/// the entry that shifted into its place. That reproduces node for the cases
/// its own tests turn on — add-during, delete-ahead, delete-self,
/// delete-behind, delete-the-rest and clear — without giving `Map` the
/// tombstoned entry list node uses internally.
fn collection_iterator(coll: &Value, kind: &str) -> Value {
    with_host(|h| {
        let mut m = IndexMap::new();
        m.insert(
            "@@native".into(),
            h.new_str("CollectionIterator".to_string()),
        );
        m.insert("@@coll".into(), coll.clone());
        m.insert("@@kind".into(), h.new_str(kind.to_string()));
        m.insert("@@started".into(), Value::Bool(false));
        m.insert("@@lastIdx".into(), Value::Float(0.0));
        h.new_object(m)
    })
}

/// One step of a live collection iterator.
pub(crate) fn collection_iterator_next(recv: &Value) -> Result<Value, String> {
    let slot = |k: &str| {
        with_host(|h| match h.get(recv) {
            Some(JsObj::Object(p)) => p.get(k).cloned(),
            _ => None,
        })
    };
    let coll = slot("@@coll").unwrap_or(Value::Undef);
    let kind = slot("@@kind")
        .map(|v| with_host(|h| h.str_of(&v)))
        .unwrap_or_default();
    let started = slot("@@started").is_some_and(|v| with_host(|h| h.truthy(&v)));
    let last_idx = slot("@@lastIdx")
        .map(|v| with_host(|h| h.to_number(&v)) as usize)
        .unwrap_or(0);
    let last_key = slot("@@lastKey");

    let next_idx = if !started {
        0
    } else {
        match last_key
            .as_ref()
            .and_then(|k| with_host(|h| collection_index_of(h, &coll, k)))
        {
            // Still present: continue after it.
            Some(i) => i + 1,
            // Deleted since: whatever shifted into its slot is next.
            None => last_idx,
        }
    };
    let entry = with_host(|h| collection_entry_at(h, &coll, next_idx));
    let Some((k, v)) = entry else {
        return Ok(iter_result(Value::Undef, true));
    };
    with_host(|h| {
        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
            p.insert("@@started".into(), Value::Bool(true));
            p.insert("@@lastIdx".into(), Value::Float(next_idx as f64));
            p.insert("@@lastKey".into(), k.clone());
        }
    });
    let out = match kind.as_str() {
        "keys" => k,
        "values" => v,
        _ => with_host(|h| h.new_array(vec![k, v])),
    };
    Ok(iter_result(out, false))
}

/// The (key, value) at `idx` in a Map, or (value, value) in a Set.
fn collection_entry_at(h: &host::JsHost, coll: &Value, idx: usize) -> Option<(Value, Value)> {
    match h.get(coll) {
        Some(JsObj::Map { entries, .. }) => entries.get_index(idx).map(|(_, kv)| kv.clone()),
        Some(JsObj::Set { entries, .. }) => {
            entries.get_index(idx).map(|(_, v)| (v.clone(), v.clone()))
        }
        _ => None,
    }
}

/// Where `key` currently sits in the collection's order.
fn collection_index_of(h: &host::JsHost, coll: &Value, key: &Value) -> Option<usize> {
    let mk = host::map_key(h, key);
    match h.get(coll) {
        Some(JsObj::Map { entries, .. }) => entries.get_index_of(&mk),
        Some(JsObj::Set { entries, .. }) => entries.get_index_of(&mk),
        _ => None,
    }
}

/// The `thisArg` an iteration method was given, if any.
///
/// `[1].forEach(fn, thisArg)` binds `thisArg` as the callback's `this`, and so
/// do `map`/`filter`/`some`/`every`/`find`/`findIndex`/`findLast`/
/// `findLastIndex`/`flatMap`, `Map`/`Set`/TypedArray `forEach`, and
/// `Array.from`'s map function. Every one of them was invoking the callback
/// with no receiver, so `this` inside it was undefined and the argument did
/// nothing.
fn this_arg(args: &[Value], idx: usize) -> Option<Value> {
    args.get(idx)
        .filter(|v| !matches!(v, Value::Undef))
        .cloned()
}

/// The elements of an array, with any INDEX ACCESSOR resolved.
///
/// `Object.defineProperty(arr, 1, { get })` stores the getter in the accessor
/// table, and an array's elements live in a backing vector — so every method
/// reading that vector directly (`join`, `map`, `indexOf`, …) saw the stale
/// slot and never called the getter, while a plain `arr[1]` read did.
///
/// An array with no accessors pays one lookup returning an empty list, so the
/// ordinary case is unchanged. The getters are invoked OUTSIDE the host borrow,
/// since calling one re-enters.
/// Walk `recv` the way an `Array.prototype` iteration method does: the LENGTH
/// is captured once at entry (LengthOfArrayLike, step 3), but each element is
/// read LIVE at its index, and an index that no longer exists is skipped.
///
/// Snapshotting the whole array instead meant a callback that mutated it was
/// not observed: `[1,2,3].forEach(v => a.shift())` visited 1, 2, 3 where node
/// visits 1 and 3, and `filter` kept elements the callback had already removed.
///
/// `f` returns `Some(x)` to stop early with `x`.
fn array_walk<T>(
    recv: &Value,
    mut f: impl FnMut(usize, Value) -> Result<Option<T>, String>,
) -> Result<Option<T>, String> {
    let len = array_len(recv);
    for i in 0..len {
        // A HOLE — and an index a shrinking mutation has dropped — is skipped
        // without calling the callback.
        if index_absent(recv, i) || i >= array_len(recv) {
            continue;
        }
        let v = get_property(recv, &i.to_string())?;
        if let Some(out) = f(i, v)? {
            return Ok(Some(out));
        }
    }
    Ok(None)
}

/// `array_walk`'s descending twin, for `reduceRight`/`findLast*`: the same
/// capture-length-once, read-each-element-live rule walked from the end. A
/// callback that SHRINKS the array is observed by every later step, so the
/// indices it drops are skipped rather than served from a stale copy.
fn array_walk_rev<T>(
    recv: &Value,
    from: usize,
    mut f: impl FnMut(usize, Value) -> Result<Option<T>, String>,
) -> Result<Option<T>, String> {
    for i in (0..from).rev() {
        if index_absent(recv, i) || i >= array_len(recv) {
            continue;
        }
        let v = get_property(recv, &i.to_string())?;
        if let Some(out) = f(i, v)? {
            return Ok(Some(out));
        }
    }
    Ok(None)
}

/// The live read behind `indexOf`/`includes`/`join`: the element at `i`, or
/// `undefined` once a mutation has shrunk the array past it.
fn array_elem_live(recv: &Value, i: usize) -> Result<Value, String> {
    if i >= array_len(recv) {
        return Ok(Value::Undef);
    }
    get_property(recv, &i.to_string())
}

fn array_items(recv: &Value) -> Vec<Value> {
    let mut items = with_host(|h| match h.get(recv) {
        Some(JsObj::Array(items)) => items.clone(),
        _ => Vec::new(),
    });
    resolve_index_accessors(recv, &mut items);
    items
}

/// Replace each slot that has an own accessor with what its getter returns.
pub(crate) fn resolve_index_accessors_pub(recv: &Value, items: &mut [Value]) {
    resolve_index_accessors(recv, items);
}

/// Returns whether any slot was replaced, which the JSON walk needs: it keeps
/// the ORIGINAL array when nothing changed, and the original still holds the
/// stale slots.
fn resolve_index_accessors(recv: &Value, items: &mut [Value]) -> bool {
    let mut indices: Vec<usize> = with_host(|h| h.own_accessor_keys(recv))
        .into_iter()
        .filter_map(|k| k.parse::<usize>().ok())
        .filter(|i| *i < items.len())
        .collect();
    // An ELIDED index the prototype chain supplies is stale in the backing
    // vector too — it holds `undefined` where `[[Get]]` answers the inherited
    // value. Spread and `JSON.stringify` both read through here, and both
    // rendered the hole rather than what `a[i]` reads.
    let inherited: Vec<usize> = with_host(|h| h.hole_indices(recv))
        .into_iter()
        .filter(|i| *i < items.len() && !indices.contains(i))
        .filter(|i| has_property(recv, &i.to_string()).unwrap_or(false))
        .collect();
    indices.extend(inherited);
    let mut replaced = false;
    for i in indices {
        if let Ok(v) = get_property(recv, &i.to_string()) {
            items[i] = v;
            replaced = true;
        }
    }
    replaced
}

/// The ELIDED positions of array `recv` as a membership set. A dense array —
/// which is nearly every array — answers with an empty set after a single
/// negative hash probe and allocates nothing.
///
/// The iteration methods split into two groups, and the split is not a matter of
/// taste: the ones spec'd through `HasProperty` (`forEach`, `map`, `filter`,
/// `some`, `every`, `reduce`, `indexOf`, `flat`, `sort`) SKIP a hole, while the
/// ones spec'd through a bare `Get` (`for…of`, spread, `find`, `includes`,
/// `join`, `entries`, `Array.from`) see the `undefined` a hole reads back as.
fn hole_set(recv: &Value) -> rustc_hash::FxHashSet<usize> {
    with_host(|h| h.hole_indices(recv)).into_iter().collect()
}

/// The indices `recv` genuinely has NO property at — the elided ones the
/// prototype chain does not supply either.
///
/// Every array method tests `HasProperty` before deciding to skip a position
/// (23.1.3.x, uniformly), and `HasProperty` walks the chain. Testing elision
/// alone made an inherited element invisible to all of them: with
/// `Array.prototype[1] = 'p'`, `[1,,3].map(v => v)` produced a hole where node
/// produces `'p'`, and `flat`/`concat`/`slice`/`sort`/`indexOf` each dropped
/// the same position.
///
/// `hole_set` remains the elision record itself, which is what `splice` moves
/// around — that bookkeeping is about the array's OWN storage and must not
/// consult the chain.
fn absent_set(recv: &Value) -> rustc_hash::FxHashSet<usize> {
    hole_set(recv)
        .into_iter()
        .filter(|i| !has_property(recv, &i.to_string()).unwrap_or(false))
        .collect()
}

/// The single-index form of [`absent_set`], for the walkers that test one
/// position at a time.
fn index_absent(recv: &Value, i: usize) -> bool {
    with_host(|h| h.is_hole(recv, i)) && !has_property(recv, &i.to_string()).unwrap_or(false)
}

/// The element count, without copying the elements.
fn array_len(recv: &Value) -> usize {
    peek(recv, |o| match o {
        JsObj::Array(items) => Some(items.len()),
        _ => None,
    })
    .unwrap_or(0)
}

/// `ArraySpeciesCreate(originalArray, length)` (23.1.3.4) — the constructor an
/// array method builds its RESULT with.
///
/// `map`, `filter`, `slice`, `concat`, `splice`, `flat` and `flatMap` all
/// produce an array of the receiver's own species, so on a `class A extends
/// Array` the result is an `A`. Every one of them allocated a plain array
/// instead, so `A.from([1]).map(x => x) instanceof A` was false.
///
/// The default `get [Symbol.species]() { return this }` is what makes the
/// subclass the species; a class overriding it with `Array` gets a plain array
/// back, which is the documented way to opt out.
/// Build an array-shaped result through `ctor`, or a plain array when there is
/// none to build through.
///
/// The constructor is called with the LENGTH and the elements written after, as
/// 23.1.2.1 and 23.1.3.4 both specify — which is what lets a subclass
/// constructor observe the allocation.
fn construct_array_like(ctor: Option<Value>, items: Vec<Value>) -> Result<Value, String> {
    let Some(ctor) = ctor.filter(|c| {
        matches!(
            with_host(|h| h.kind_of(c)),
            Some(ObjKind::Class) | Some(ObjKind::Func)
        )
    }) else {
        return Ok(with_host(|h| h.new_array(items)));
    };
    let out = host::construct(&ctor, vec![Value::Float(items.len() as f64)])?;
    write_elements(&out, items);
    Ok(out)
}

/// Write `items` into a freshly constructed array-shaped `out`, clearing the
/// hole marks the length-only construction left behind.
///
/// `new A(3)` on `class A extends Array` really does produce three HOLES, and
/// the elements written over them stayed marked — so every subclass result of
/// `map`/`filter`/`flat` read back as holes: `A.from([1,2,3]).map(x => x * 2)`
/// had length 3 and printed `[null,null,null]`, and `0 in` it was false.
fn write_elements(out: &Value, items: Vec<Value>) {
    with_host(|h| {
        h.clear_holes(out);
        if let Some(JsObj::Array(dst)) = h.get_mut(out) {
            *dst = items;
        }
    });
}

fn array_species_create(recv: &Value, items: Vec<Value>) -> Result<Value, String> {
    let plain = || with_host(|h| h.new_array(items.clone()));
    // Only a subclass instance can have a species of its own: a plain array's
    // `constructor` is the `Array` builtin, whose species is `Array`.
    // A chain lookup, not `get_property`: an Array receiver resolves its
    // properties through the stdlib funnel, which has no `constructor` entry,
    // so the read alone reports `undefined` for every subclass instance. A
    // Proxy is the exception — it has no property map to walk, and its
    // `constructor` comes from the `get` trap, so a proxied subclass array
    // produced plain arrays.
    let ctor = if with_host(|h| h.kind_of(recv)) == Some(ObjKind::Proxy) {
        get_property(recv, "constructor").unwrap_or(Value::Undef)
    } else {
        with_host(|h| host::lookup_chain(h, recv, "constructor")).unwrap_or(Value::Undef)
    };
    if !matches!(
        with_host(|h| h.kind_of(&ctor)),
        Some(ObjKind::Class) | Some(ObjKind::Func)
    ) {
        return Ok(plain());
    }
    // An explicit `@@species` wins; absent one, the constructor itself is the
    // species, as the inherited accessor returns `this`.
    let species = match get_property(&ctor, "@@species") {
        Ok(Value::Undef) => ctor,
        Ok(s) if with_host(|h| h.is_null(&s)) => return Ok(plain()),
        Ok(s) => s,
        Err(_) => ctor,
    };
    if !matches!(
        with_host(|h| h.kind_of(&species)),
        Some(ObjKind::Class) | Some(ObjKind::Func)
    ) {
        return Ok(plain());
    }
    let out = host::construct(&species, vec![Value::Float(items.len() as f64)])?;
    // The constructor is called with the LENGTH, so the elements are written
    // afterwards — which is also what lets a subclass constructor observe the
    // allocation, as node's does.
    write_elements(&out, items);
    Ok(out)
}

fn array_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    array_method_on(recv, recv, name, args)
}

/// The `Array.prototype` methods that WRITE to their receiver, and so need the
/// generic path to copy the result back onto the array-like.
const ARRAY_MUTATORS: &[&str] = &[
    "push",
    "pop",
    "shift",
    "unshift",
    "splice",
    "sort",
    "reverse",
    "fill",
    "copyWithin",
];

/// Run `Array.prototype.<method>` against an array-LIKE (`{0: 'a', length: 1}`,
/// a DOM-ish collection, `arguments`).
///
/// 23.1.3 defines every one of these over `LengthOfArrayLike(O)` and `Get(O, k)`
/// rather than over an Array's element vector, so the receiver only has to have
/// a `length`. The elements are read out into a temporary Array, the ordinary
/// implementation runs on that, and a MUTATING method writes the result back —
/// which keeps one implementation of each method rather than a second, generic
/// one that could drift from it.
///
/// An index the receiver does not own is a HOLE in the temporary, so the
/// methods that skip holes skip it here too, exactly as `HasProperty` makes them.
fn array_generic(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
    let len = match get_property(recv, "length") {
        Ok(v) => host::to_array_length(&v).unwrap_or(0),
        Err(_) => 0,
    };
    // A STRING receiver owns every index of its length; `has_property` answers
    // for objects and reports none of them, which made `[].map.call('abc', f)`
    // an array of three holes.
    let dense = with_host(|h| h.as_str(recv)).is_some();
    let mut items = Vec::with_capacity(len);
    let mut holes: rustc_hash::FxHashSet<usize> = rustc_hash::FxHashSet::default();
    for i in 0..len {
        let k = i.to_string();
        if dense || has_property(recv, &k)? {
            items.push(get_property(recv, &k)?);
        } else {
            holes.insert(i);
            items.push(Value::Undef);
        }
    }
    let tmp = with_host(|h| {
        let a = h.new_array(items);
        h.install_holes(&a, holes);
        a
    });
    let out = array_method_on(&tmp, recv, method, args)?;
    if ARRAY_MUTATORS.contains(&method) {
        let result = with_host(|h| match h.get(&tmp) {
            Some(JsObj::Array(items)) => items.clone(),
            _ => Vec::new(),
        });
        for (i, v) in result.iter().enumerate() {
            set_property(recv, &i.to_string(), v.clone())?;
        }
        set_property(recv, "length", Value::Float(result.len() as f64))?;
    }
    Ok(out)
}

/// `Array.prototype.<name>` on `recv`.
///
/// `this_value` is what a callback receives as its third argument and what a
/// mutating method returns — the same object as `recv` for an ordinary array
/// call, but the ORIGINAL array-like when `array_generic` runs a method against
/// a temporary copy (`Array.prototype.slice.call(arguments)`).
fn array_method_on(
    recv: &Value,
    this_value: &Value,
    name: &str,
    args: Vec<Value>,
) -> Result<Value, String> {
    let args = coerce_numeric_args(ARRAY_METHOD_NUMERIC_ARGS, name, args)?;
    match name {
        "push" => {
            // 23.1.3.23 step 4 defines each new element through
            // `CreateDataPropertyOrThrow`, so a NON-EXTENSIBLE array refuses it:
            // `Object.seal(a)` / `preventExtensions(a)` then `a.push(x)` is a
            // TypeError. The elements were appended to the backing vector
            // regardless, so sealing an array did not seal it.
            if !args.is_empty() && !with_host(|h| h.is_extensible(recv)) {
                let at = array_len(recv);
                return Err(host::type_error(&format!(
                    "Cannot add property {at}, object is not extensible"
                )));
            }
            // Step 5 then SETS `length`, so a non-writable one refuses the push
            // too — `defineProperty(a, 'length', {writable: false})` makes an
            // array append-proof without sealing it.
            if !args.is_empty() && !with_host(|h| h.prop_attrs(recv, "length").writable) {
                return Err(host::type_error(
                    "Cannot assign to read only property 'length' of object '[object Array]'",
                ));
            }
            // `push` returns the new length; take it from the same mutable
            // borrow rather than copying the array back out to count it.
            let len = with_host(|h| {
                if let Some(JsObj::Array(items)) = h.get_mut(recv) {
                    items.extend(args.iter().cloned());
                    items.len()
                } else {
                    0
                }
            });
            Ok(Value::Float(len as f64))
        }
        "pop" => Ok(with_host(|h| {
            let popped = if let Some(JsObj::Array(items)) = h.get_mut(recv) {
                items.pop().unwrap_or(Value::Undef)
            } else {
                Value::Undef
            };
            let len = match h.get(recv) {
                Some(JsObj::Array(items)) => items.len(),
                _ => 0,
            };
            h.truncate_holes(recv, len);
            popped
        })),
        "shift" => Ok(with_host(|h| {
            let shifted = if let Some(JsObj::Array(items)) = h.get_mut(recv) {
                if items.is_empty() {
                    Value::Undef
                } else {
                    items.remove(0)
                }
            } else {
                Value::Undef
            };
            h.remap_holes(recv, |i| i.checked_sub(1));
            shifted
        })),
        "unshift" => {
            with_host(|h| {
                if let Some(JsObj::Array(items)) = h.get_mut(recv) {
                    for (i, a) in args.iter().enumerate() {
                        items.insert(i, a.clone());
                    }
                }
                let n = args.len();
                h.remap_holes(recv, |i| Some(i + n));
            });
            Ok(Value::Float(array_len(recv) as f64))
        }
        "join" => {
            let sep = if args.is_empty() || matches!(args[0], Value::Undef) {
                ",".to_string()
            } else {
                arg_to_string(&args, 0)?
            };
            join_array(recv, &sep)
        }
        // `Array.prototype.toLocaleString` (23.1.3.32): comma-join the elements'
        // OWN `toLocaleString` results, with `null`/`undefined` contributing the
        // empty string. It threw `is not a function` — the whole method was
        // missing — so `[1234.5, 'x'].toLocaleString()` was unreachable.
        "toLocaleString" => {
            // Shares `join`'s JoinStack: measured on node v26.7.0, `h=[1]`
            // `h.push(h)` makes `h.toLocaleString()` `"1,"`, not a stack overflow.
            if !host::join_stack_push(recv) {
                return Ok(with_host(|h| h.new_str(String::new())));
            }
            let items = array_items(recv);
            let mut parts: Vec<String> = Vec::with_capacity(items.len());
            for it in &items {
                if with_host(|h| h.is_nullish(it)) {
                    parts.push(String::new());
                    continue;
                }
                let v = match host::call_method(it, "toLocaleString", Vec::new()) {
                    Ok(v) => v,
                    Err(e) => {
                        host::join_stack_pop();
                        return Err(e);
                    }
                };
                parts.push(with_host(|h| h.str_of(&v)));
            }
            host::join_stack_pop();
            Ok(with_host(|h| h.new_str(parts.join(","))))
        }
        // `indexOf`/`lastIndexOf` are spec'd through `HasProperty`, so a hole is
        // never a match: `[1,,3].indexOf(undefined)` is `-1`, while the
        // `Get`-based `includes` reports `true` for the same array.
        "indexOf" => {
            let target = arg0(&args);
            let len = array_len(recv);
            let start = search_start(arg_num(&args, 1), len);
            let mut idx = None;
            for i in start..len {
                // 23.1.3.17 steps 8a-8b: HasProperty first, so a hole — and an
                // index a mutation has since dropped — is skipped, not compared.
                if index_absent(recv, i) || i >= array_len(recv) {
                    continue;
                }
                let x = get_property(recv, &i.to_string())?;
                if with_host(|h| h.strict_eq(&x, &target)) {
                    idx = Some(i);
                    break;
                }
            }
            Ok(Value::Float(idx.map(|i| i as f64).unwrap_or(-1.0)))
        }
        "lastIndexOf" => {
            let items = array_items(recv);
            let holes = absent_set(recv);
            let target = arg0(&args);
            let from = (args.len() > 1).then(|| arg_num(&args, 1));
            let idx = match search_start_last(from, items.len()) {
                None => None,
                Some(start) => with_host(|h| {
                    items[..=start]
                        .iter()
                        .enumerate()
                        .rev()
                        .find(|(i, x)| !holes.contains(i) && h.strict_eq(x, &target))
                        .map(|(i, _)| i)
                }),
            };
            Ok(Value::Float(idx.map(|i| i as f64).unwrap_or(-1.0)))
        }
        "includes" => {
            // Array.includes uses SameValueZero: unlike `===`, NaN matches NaN.
            // Unlike `indexOf` it has no HasProperty step (23.1.3.16 step 5b), so
            // a hole reads as `undefined` and `[,].includes(undefined)` is true.
            let target = arg0(&args);
            let tnan = matches!(target, Value::Float(f) if f.is_nan());
            let len = array_len(recv);
            let start = search_start(arg_num(&args, 1), len);
            let mut found = false;
            for i in start..len {
                let x = array_elem_live(recv, i)?;
                if (tnan && matches!(x, Value::Float(f) if f.is_nan()))
                    || with_host(|h| h.strict_eq(&x, &target))
                {
                    found = true;
                    break;
                }
            }
            Ok(Value::Bool(found))
        }
        "slice" => {
            let items = array_items(recv);
            let (lo, hi) = slice_bounds(&args, items.len());
            let out = array_species_create(this_value, items[lo..hi].to_vec())?;
            with_host(|h| h.copy_holes(recv, &out, |i| (i >= lo && i < hi).then(|| i - lo)));
            Ok(out)
        }
        "concat" => {
            // `Symbol.isConcatSpreadable` (23.1.3.1) decides whether a value
            // is spread, overriding `IsArray` in BOTH directions: a plain
            // array-like opts IN, and an array opts OUT.
            let spreadable = |a: &Value| -> bool {
                let flag = get_property(a, "@@isConcatSpreadable").unwrap_or(Value::Undef);
                if matches!(flag, Value::Undef) {
                    matches!(with_host(|h| h.get(a).cloned()), Some(JsObj::Array(_)))
                        && !is_arguments(a)
                } else {
                    with_host(|h| h.truthy(&flag))
                }
            };
            // Step 5 iterates `« O » ++ items`, so the receiver takes the same
            // test: a non-spreadable `this` (`concat.call("ab", 1)`) is ONE
            // element, its `ToObject` box, not the characters `array_generic`
            // read out of it. A hole in a spread receiver or argument stays a
            // hole in the result, at its shifted position.
            let (mut out, mut holes) = if spreadable(this_value) {
                (array_items(recv), absent_set(recv))
            } else {
                (vec![to_object(this_value)], Default::default())
            };
            let mut sources: Vec<(Value, usize)> = Vec::new();
            for a in &args {
                if !spreadable(a) {
                    out.push(a.clone());
                    continue;
                }
                match with_host(|h| h.get(a).cloned()) {
                    // Read off the backing vector rather than through
                    // `array_items`, so the resolve that does for the receiver
                    // has to be done here too: 23.1.3.1 step 5.c.iv is a
                    // `[[Get]]`, and an index with a getter — or an elided one
                    // the chain supplies — is stale in that vector.
                    Some(JsObj::Array(mut items)) => {
                        resolve_index_accessors(a, &mut items);
                        sources.push((a.clone(), out.len()));
                        out.extend(items);
                    }
                    // An opted-in array-LIKE spreads by its `length` and index
                    // properties rather than by a backing vector it has none of.
                    _ => {
                        let len = get_property(a, "length").unwrap_or(Value::Undef);
                        let n = with_host(|h| h.to_number(&len));
                        let n = if n.is_finite() {
                            n.max(0.0) as usize
                        } else {
                            0
                        };
                        for i in 0..n {
                            out.push(get_property(a, &i.to_string()).unwrap_or(Value::Undef));
                        }
                    }
                }
            }

            for (src, base) in sources {
                holes.extend(
                    with_host(|h| h.hole_indices(&src))
                        .into_iter()
                        .map(|i| i + base),
                );
            }
            let arr = array_species_create(this_value, out)?;
            with_host(|h| h.install_holes(&arr, holes));
            Ok(arr)
        }
        "reverse" => {
            let len = array_len(recv);
            with_host(|h| {
                if let Some(JsObj::Array(items)) = h.get_mut(recv) {
                    items.reverse();
                }
                h.remap_holes(recv, |i| Some(len - 1 - i));
            });
            Ok(this_value.clone())
        }
        "fill" => {
            // fill(value[, start[, end]]) — negative indices count from the end.
            let val = arg0(&args);
            let len = array_len(recv) as i64;
            let norm =
                |v: i64| -> usize { (if v < 0 { (len + v).max(0) } else { v.min(len) }) as usize };
            let start = if args.len() >= 2 {
                norm(arg_num(&args, 1) as i64)
            } else {
                0
            };
            let end = if args.len() >= 3 {
                norm(arg_num(&args, 2) as i64)
            } else {
                len as usize
            };
            with_host(|h| {
                if let Some(JsObj::Array(items)) = h.get_mut(recv) {
                    for it in items.iter_mut().take(end).skip(start) {
                        *it = val.clone();
                    }
                }
                // Every filled position now holds a real value.
                h.remap_holes(recv, |i| (i < start || i >= end).then_some(i));
            });
            Ok(this_value.clone())
        }
        "copyWithin" => {
            // copyWithin(target, start[, end]) — copy a slice within the array.
            let items = array_items(recv);
            let len = items.len() as i64;
            let norm =
                |v: i64| -> usize { (if v < 0 { (len + v).max(0) } else { v.min(len) }) as usize };
            let target = norm(arg_num(&args, 0) as i64);
            let start = if args.len() >= 2 {
                norm(arg_num(&args, 1) as i64)
            } else {
                0
            };
            let end = if args.len() >= 3 {
                norm(arg_num(&args, 2) as i64)
            } else {
                len as usize
            };
            let slice: Vec<Value> = items[start..end.max(start)].to_vec();
            let copied = slice.len();
            // A copied position takes its SOURCE's hole-ness (10.4.2 copyWithin
            // deletes the target when the source has no such property);
            // everything outside the written range keeps its own.
            let src_holes = absent_set(recv);
            with_host(|h| {
                if let Some(JsObj::Array(a)) = h.get_mut(recv) {
                    for (k, v) in slice.into_iter().enumerate() {
                        if target + k < a.len() {
                            a[target + k] = v;
                        }
                    }
                }
                let len = len as usize;
                let mut holes: rustc_hash::FxHashSet<usize> = src_holes
                    .iter()
                    .copied()
                    .filter(|i| *i < target || *i >= (target + copied).min(len))
                    .collect();
                for k in 0..copied {
                    if target + k < len && src_holes.contains(&(start + k)) {
                        holes.insert(target + k);
                    }
                }
                h.install_holes(recv, holes);
            });
            Ok(this_value.clone())
        }
        "at" => {
            let items = array_items(recv);
            let mut i = arg_num(&args, 0) as i64;
            if i < 0 {
                i += items.len() as i64;
            }
            Ok(if i >= 0 && (i as usize) < items.len() {
                items[i as usize].clone()
            } else {
                Value::Undef
            })
        }
        // 23.1.3.21: the callback runs only where `HasProperty` holds, and the
        // result array is created with the SAME holes — `[1,,3].map(f)` calls `f`
        // twice and yields `[2, <1 empty item>, 6]`.
        "map" => {
            let holes = absent_set(recv);
            let cb = arg0(&args);
            // The result keeps the source's LENGTH, so a skipped index still
            // occupies a slot; `array_walk` only tells us which ones ran.
            let mut out = vec![Value::Undef; array_len(recv)];
            array_walk(recv, |i, it| {
                let v = host::invoke(
                    &cb,
                    vec![it, Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                if i < out.len() {
                    out[i] = v;
                }
                Ok(None::<()>)
            })?;
            let arr = array_species_create(this_value, out)?;
            with_host(|h| h.install_holes(&arr, holes));
            Ok(arr)
        }
        "flatMap" => {
            let cb = arg0(&args);
            let thisarg = this_arg(&args, 1);
            let mut out = Vec::new();
            array_walk(recv, |i, v| {
                let r = host::invoke(
                    &cb,
                    vec![v, Value::Float(i as f64), this_value.clone()],
                    thisarg.clone(),
                )?;
                match with_host(|h| h.get(&r).cloned()) {
                    Some(JsObj::Array(inner)) => out.extend(inner),
                    _ => out.push(r),
                }
                Ok(None::<()>)
            })?;
            array_species_create(this_value, out)
        }
        "filter" => {
            let cb = arg0(&args);
            let mut out = Vec::new();
            array_walk(recv, |i, it| {
                let keep = host::invoke(
                    &cb,
                    vec![it.clone(), Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                if with_host(|h| h.truthy(&keep)) {
                    out.push(it);
                }
                Ok(None::<()>)
            })?;
            array_species_create(this_value, out)
        }
        "forEach" => {
            let cb = arg0(&args);
            array_walk(recv, |i, it| {
                host::invoke(
                    &cb,
                    vec![it, Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                Ok(None::<()>)
            })?;
            Ok(Value::Undef)
        }
        "find" => {
            let items = array_items(recv);
            let cb = arg0(&args);
            for (i, it) in items.iter().enumerate() {
                let m = host::invoke(
                    &cb,
                    vec![it.clone(), Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                if with_host(|h| h.truthy(&m)) {
                    return Ok(it.clone());
                }
            }
            Ok(Value::Undef)
        }
        "findIndex" => {
            let items = array_items(recv);
            let cb = arg0(&args);
            for (i, it) in items.iter().enumerate() {
                let m = host::invoke(
                    &cb,
                    vec![it.clone(), Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                if with_host(|h| h.truthy(&m)) {
                    return Ok(Value::Float(i as f64));
                }
            }
            Ok(Value::Float(-1.0))
        }
        "some" => {
            let cb = arg0(&args);
            let thisarg = this_arg(&args, 1);
            let hit = array_walk(recv, |i, v| {
                let m = host::invoke(
                    &cb,
                    vec![v, Value::Float(i as f64), this_value.clone()],
                    thisarg.clone(),
                )?;
                Ok(with_host(|h| h.truthy(&m)).then_some(()))
            })?;
            Ok(Value::Bool(hit.is_some()))
        }
        "every" => {
            let cb = arg0(&args);
            let failed = array_walk(recv, |i, it| {
                let m = host::invoke(
                    &cb,
                    vec![it, Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                Ok((!with_host(|h| h.truthy(&m))).then_some(()))
            })?;
            Ok(Value::Bool(failed.is_none()))
        }
        "reduce" => {
            let items = array_items(recv);
            let holes = absent_set(recv);
            let cb = arg0(&args);
            let acc;
            let mut start = 0;
            if args.len() >= 2 {
                acc = args[1].clone();
            } else {
                // With no seed the accumulator is the first PRESENT element, so a
                // leading run of holes is skipped rather than seeding `undefined`.
                match (0..items.len()).find(|i| !holes.contains(i)) {
                    Some(i) => {
                        acc = items[i].clone();
                        start = i + 1;
                    }
                    None => {
                        return Err(host::type_error(
                            "Reduce of empty array with no initial value",
                        ))
                    }
                }
            }
            // Each element is read LIVE at its index, so a callback that
            // shrinks the array is observed — the tail is skipped rather than
            // folded from a stale snapshot.
            let mut cur = acc;
            array_walk(recv, |i, it| {
                if i < start {
                    return Ok(None::<()>);
                }
                cur = host::invoke(
                    &cb,
                    vec![
                        std::mem::replace(&mut cur, Value::Undef),
                        it,
                        Value::Float(i as f64),
                        this_value.clone(),
                    ],
                    this_arg(&args, 1),
                )?;
                Ok(None::<()>)
            })?;
            Ok(cur)
        }
        "reduceRight" => {
            let cb = arg0(&args);
            let n = array_len(recv);
            let mut acc;
            let mut from = n; // one past the next index to process (walking down)
            if args.len() >= 2 {
                acc = args[1].clone();
            } else {
                let holes = absent_set(recv);
                match (0..n).rev().find(|i| !holes.contains(i)) {
                    Some(k) => {
                        acc = get_property(recv, &k.to_string())?;
                        from = k;
                    }
                    None => {
                        return Err(host::type_error(
                            "Reduce of empty array with no initial value",
                        ))
                    }
                }
            }
            // `acc` moves into the closure and back out on every step, so it
            // lives in an Option the closure can take from and refill.
            let mut slot = Some(acc);
            array_walk_rev(recv, from, |i, v| {
                let prev = slot.take().expect("accumulator is refilled each step");
                slot = Some(host::invoke(
                    &cb,
                    vec![prev, v, Value::Float(i as f64), this_value.clone()],
                    None,
                )?);
                Ok(None::<()>)
            })?;
            acc = slot.expect("accumulator is refilled each step");
            Ok(acc)
        }
        "findLast" => {
            let items = array_items(recv);
            let cb = arg0(&args);
            for i in (0..items.len()).rev() {
                let m = host::invoke(
                    &cb,
                    vec![items[i].clone(), Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                if with_host(|h| h.truthy(&m)) {
                    return Ok(items[i].clone());
                }
            }
            Ok(Value::Undef)
        }
        "findLastIndex" => {
            let items = array_items(recv);
            let cb = arg0(&args);
            for i in (0..items.len()).rev() {
                let m = host::invoke(
                    &cb,
                    vec![items[i].clone(), Value::Float(i as f64), this_value.clone()],
                    this_arg(&args, 1),
                )?;
                if with_host(|h| h.truthy(&m)) {
                    return Ok(Value::Float(i as f64));
                }
            }
            Ok(Value::Float(-1.0))
        }
        // 23.1.3.30: `SortIndexedProperties` collects only the PRESENT elements,
        // and the holes are re-created at the tail — `[3,,1].sort()` is
        // `[1, 3, <1 empty item>]` with own keys `['0','1']`.
        "sort" => {
            let all = array_items(recv);
            let holes = absent_set(recv);
            let mut items: Vec<Value> = all
                .iter()
                .enumerate()
                .filter(|(i, _)| !holes.contains(i))
                .map(|(_, v)| v.clone())
                .collect();
            sort_values(&mut items, args.first())?;
            let present = items.len();
            // 23.1.3.30 steps 4-5 write back only the indices BELOW the length
            // captured at step 1: `Set` for each sorted element, then `Delete`
            // for the holes that followed them. Replacing the whole backing
            // vector instead discarded anything the COMPARATOR appended —
            // `a.sort((x, y) => { a.push(0); return x - y })` came back at its
            // original length with every pushed element gone.
            with_host(|h| {
                let len = all.len();
                if let Some(JsObj::Array(a)) = h.get_mut(recv) {
                    if a.len() < len {
                        a.resize(len, Value::Undef);
                    }
                    for (i, v) in items.into_iter().enumerate() {
                        a[i] = v;
                    }
                    for slot in a[present..len].iter_mut() {
                        *slot = Value::Undef;
                    }
                }
                h.install_holes(recv, (present..len).collect());
            });
            Ok(this_value.clone())
        }
        // ES2023 change-by-copy: sort a fresh copy, leaving the receiver untouched.
        "toSorted" => {
            let mut items = array_items(recv);
            sort_values(&mut items, args.first())?;
            Ok(with_host(|h| h.new_array(items)))
        }
        "toReversed" => {
            let mut items = array_items(recv);
            items.reverse();
            Ok(with_host(|h| h.new_array(items)))
        }
        "toSpliced" => {
            let mut items = array_items(recv);
            let len = items.len();
            let start = {
                let s = arg_num(&args, 0);
                if s < 0.0 {
                    ((len as f64 + s).max(0.0)) as usize
                } else {
                    (s as usize).min(len)
                }
            };
            let delete = if args.len() >= 2 {
                (arg_num(&args, 1).max(0.0) as usize).min(len - start)
            } else if args.is_empty() {
                0
            } else {
                len - start
            };
            let inserts: Vec<Value> = args.iter().skip(2).cloned().collect();
            items.splice(start..start + delete, inserts);
            Ok(with_host(|h| h.new_array(items)))
        }
        "with" => {
            let mut items = array_items(recv);
            let len = items.len() as i64;
            let rel = arg_num(&args, 0) as i64;
            let idx = if rel < 0 { len + rel } else { rel };
            if idx < 0 || idx >= len {
                return Err(host::range_error(&format!("Invalid index : {rel}")));
            }
            items[idx as usize] = args.get(1).cloned().unwrap_or(Value::Undef);
            Ok(with_host(|h| h.new_array(items)))
        }
        "flat" => {
            // depth defaults to 1; `Infinity` flattens fully. ToIntegerOrInfinity:
            // NaN → 0, otherwise truncate toward zero (negatives act as 0).
            let raw = if args.is_empty() {
                1.0
            } else {
                arg_num(&args, 0)
            };
            let depth = if raw.is_nan() {
                0.0
            } else if raw.is_infinite() {
                raw
            } else {
                raw.trunc()
            };
            let mut out = Vec::new();
            flatten_into(recv, depth, &mut out)?;
            array_species_create(this_value, out)
        }
        // Live over the array (23.1.5.1): each step reads it as it is then.
        "keys" => Ok(array_iterator(recv, host::ArrayIterKind::Keys)),
        "values" | "@@iterator" => Ok(array_iterator(recv, host::ArrayIterKind::Values)),
        "entries" => Ok(array_iterator(recv, host::ArrayIterKind::Entries)),
        "splice" => array_splice(recv, args),
        // `Array.prototype.toString` IS `join()` with the default separator
        // (23.1.3.36), so it converts each element with `ToString` too — and
        // shares its cycle cut, which is the whole reason it must not call
        // `join_parts` directly: `ToString` of a nested array lands back here.
        "toString" => join_array(recv, ","),
        // An Array inherits from `Object.prototype` too, so the methods it does
        // not override resolve there. `[].hasOwnProperty` already read back as a
        // function through the property path, but CALLING it landed here and
        // threw `is not a function`.
        _ if is_object_builtin_method(name) => object_builtin_method(recv, name, args),
        _ => Err(host::type_error(&format!("{name} is not a function"))),
    }
}

/// `Array.prototype.join` (23.1.3.18) and, with the default separator,
/// `Array.prototype.toString` (23.1.3.36) — one body so both share the cycle
/// cut, which is not optional here: `ToString` of an element that is itself an
/// array re-enters through `toString`, so guarding only `join` left
/// `a=[]; a.push(a); a.join('-')` recursing until the native stack aborted the
/// process. On node v26.7.0 that expression is `""`.
fn join_array(recv: &Value, sep: &str) -> Result<Value, String> {
    if !host::join_stack_push(recv) {
        return Ok(with_host(|h| h.new_str(String::new())));
    }
    // 23.1.3.18 step 6: the length is captured once, then each element is read
    // and STRINGIFIED before the next is read. Both halves are observable —
    // a getter or a `toString` that shrinks the array is seen by every later
    // element, which a read-all-then-convert pass misses.
    let parts = (|| -> Result<Vec<String>, String> {
        let len = array_len(recv);
        let mut out = Vec::with_capacity(len);
        for i in 0..len {
            let v = array_elem_live(recv, i)?;
            out.push(join_parts(std::slice::from_ref(&v))?.remove(0));
        }
        Ok(out)
    })();
    host::join_stack_pop();
    let s = parts?.join(sep);
    Ok(with_host(|h| h.new_str(s)))
}

/// `Array.prototype.join`'s per-element conversion (23.1.3.18 step 4): a
/// `null`/`undefined` element contributes the empty string, every other element
/// is `ToString(element)` — which for an object means invoking its `toString`,
/// so `[{ toString() { return 'x' } }].join()` is `"x"` and not
/// `"[object Object]"`.
///
/// The all-primitive array — the overwhelmingly common one — is rendered under
/// a single host borrow; only an array actually holding an object pays for the
/// re-entrant per-element conversion.
fn join_parts(items: &[Value]) -> Result<Vec<String>, String> {
    let fast = with_host(|h| {
        items
            .iter()
            .map(|x| match x {
                Value::Undef => Some(String::new()),
                _ if h.is_null(x) => Some(String::new()),
                // A SYMBOL element is primitive but has no `ToString`, so it must
                // fall through to the fallible path and throw there:
                // `[Symbol()].join()` is a TypeError on node v26.7.0.
                _ if matches!(h.get(x), Some(JsObj::Symbol { .. })) => None,
                _ if host::is_primitive(h, x) => Some(h.str_of(x)),
                _ => None,
            })
            .collect::<Vec<_>>()
    });
    if fast.iter().all(Option::is_some) {
        return Ok(fast.into_iter().flatten().collect());
    }
    let mut out = Vec::with_capacity(items.len());
    for (x, p) in items.iter().zip(fast) {
        match p {
            Some(s) => out.push(s),
            None => {
                let s = host::to_string_value(x)?;
                out.push(with_host(|h| h.str_of(&s)));
            }
        }
    }
    Ok(out)
}

/// In-place sort of `items` (shared by `sort` and `toSorted`). Stable merge
/// sort — O(n log n) comparisons — with the fallible JS comparator called from
/// the merge step; default order is by the string form of each element.
/// Propagates a comparator error.
///
/// This was an insertion sort, which is O(n²): sorting 200k numbers with a
/// comparator did not finish inside 120s (node v26.7.0: 70ms), and each
/// doubling of the input quadrupled the time — 1k/2k/4k/8k/16k measured at
/// 0.21/0.81/3.39/12.94/51.36s. The comparator contract is unchanged; only the
/// number of times it is called is.
pub(crate) fn sort_values(items: &mut [Value], cmp: Option<&Value>) -> Result<(), String> {
    // 23.1.3.30 step 1: a comparator that is neither `undefined` nor callable is
    // rejected BEFORE any comparison runs. `[2,1].sort(null)` was reaching the
    // invoke path and reporting the generic `null is not a function`.
    let cmp = match cmp {
        Some(Value::Undef) => None,
        Some(v) if !with_host(|h| host::is_callable(h, v)) => {
            // V8 renders the offending value with `NoSideEffectsToString`, not
            // with `util.inspect`: a string appears bare (`: x`) rather than
            // quoted, and an array is `[object Array]` rather than `[ 1, 2 ]`.
            let shown = no_side_effects_string(v);
            return Err(host::type_error(&format!(
                "The comparison function must be either a function or undefined: {shown}"
            )));
        }
        other => other,
    };
    // 23.1.3.30.1 SortIndexedProperties: `undefined` is never handed to the
    // comparator — it sorts to the end after the defined values are ordered.
    // `[3,undefined,1].sort((x,y)=>x-y)` is `[1,3,undefined]` with ONE call on
    // node v26.7.0; the insertion sort called the comparator twice, on
    // `undefined`, and left `[3,undefined,1]`. Every element passed over here
    // is `undefined`, so swapping keeps the defined values in input order.
    let mut defined = 0;
    for i in 0..items.len() {
        if !matches!(items[i], Value::Undef) {
            items.swap(defined, i);
            defined += 1;
        }
    }
    merge_sort(&mut items[..defined], cmp)
}

/// One SortCompare: `> 0` means `b` sorts before `a`. A comparator result runs
/// through ToNumber, so a NaN (or a comparator returning `undefined`) is not
/// `> 0` and the pair keeps its input order.
fn sort_compare(a: &Value, b: &Value, cmp: Option<&Value>) -> Result<f64, String> {
    match cmp {
        Some(cb) => {
            let v = host::invoke(cb, vec![a.clone(), b.clone()], None)?;
            Ok(with_host(|h| h.to_number(&v)))
        }
        None => {
            // 23.1.3.30.2 SortCompare with no comparator: compare the ToString
            // of each element by CODE UNIT (`utf16::cmp_units`), which differs
            // from Rust's `String` order off the BMP.
            let x = with_host(|h| h.str_of(a));
            let y = with_host(|h| h.str_of(b));
            if crate::utf16::cmp_units(&x, &y) == std::cmp::Ordering::Greater {
                Ok(1.0)
            } else {
                Ok(-1.0)
            }
        }
    }
}

/// Bottom-up stable merge sort. Bottom-up rather than recursive so a large
/// array cannot walk the native stack the JS comparator also runs on, and the
/// two buffers are swapped each pass instead of copied back.
fn merge_sort(items: &mut [Value], cmp: Option<&Value>) -> Result<(), String> {
    let n = items.len();
    if n < 2 {
        return Ok(());
    }
    let mut src = items.to_vec();
    let mut dst = src.clone();
    let mut width = 1;
    while width < n {
        let mut lo = 0;
        while lo < n {
            let mid = (lo + width).min(n);
            let hi = (lo + 2 * width).min(n);
            merge(&src[lo..mid], &src[mid..hi], &mut dst[lo..hi], cmp)?;
            lo = hi;
        }
        std::mem::swap(&mut src, &mut dst);
        width *= 2;
    }
    items.clone_from_slice(&src);
    Ok(())
}

/// Merge two sorted runs into `out`. Ties take from `left` first, which is what
/// makes the sort stable — `[{k:1},{k:0},{k:1},{k:0}].sort((x,y)=>x.k-y.k)`
/// keeps the two `k:0` entries in input order, as node does.
fn merge(
    left: &[Value],
    right: &[Value],
    out: &mut [Value],
    cmp: Option<&Value>,
) -> Result<(), String> {
    let (mut i, mut j, mut k) = (0, 0, 0);
    while i < left.len() && j < right.len() {
        if sort_compare(&left[i], &right[j], cmp)? > 0.0 {
            out[k] = right[j].clone();
            j += 1;
        } else {
            out[k] = left[i].clone();
            i += 1;
        }
        k += 1;
    }
    for v in left[i..].iter().chain(&right[j..]) {
        out[k] = v.clone();
        k += 1;
    }
    Ok(())
}

/// Recursively flatten `items` up to `depth` levels into `out`. `depth` is an
/// f64 so `Infinity` (full flatten) and finite counts share one path.
///
/// `flat` has NO cycle cut — unlike `join`, V8 lets it run out of stack, and
/// `a=[1]; a.push(a); a.flat(Infinity)` is `RangeError: Maximum call stack size
/// exceeded` on node v26.7.0. That is reproduced by checking the same native
/// stack floor the VM does, so the answer is a catchable error rather than the
/// `fatal runtime error: stack overflow` abort this used to produce.
/// `FlattenIntoArray` (23.1.3.13.1). Takes the source ARRAY rather than its
/// elements because each level tests `HasProperty` before recursing, so a hole
/// contributes nothing at any depth: `[1,,3].flat()` is the dense `[1, 3]`.
fn flatten_into(src: &Value, depth: f64, out: &mut Vec<Value>) -> Result<(), String> {
    if host::stack_exhausted() {
        return Err(host::stack_overflow_error());
    }
    let items = array_items(src);
    let holes = absent_set(src);
    for (i, it) in items.into_iter().enumerate() {
        if holes.contains(&i) {
            continue;
        }
        let nested = depth > 0.0 && with_host(|h| h.kind_of(&it)) == Some(ObjKind::Array);
        if nested {
            flatten_into(&it, depth - 1.0, out)?;
        } else {
            out.push(it);
        }
    }
    Ok(())
}

fn array_splice(recv: &Value, args: Vec<Value>) -> Result<Value, String> {
    let len = array_len(recv);
    let start = {
        let s = arg_num(&args, 0);
        if s < 0.0 {
            ((len as f64 + s).max(0.0)) as usize
        } else {
            (s as usize).min(len)
        }
    };
    let delete = if args.len() >= 2 {
        (arg_num(&args, 1).max(0.0) as usize).min(len - start)
    } else {
        len - start
    };
    let inserts: Vec<Value> = args.iter().skip(2).cloned().collect();
    let inserted = inserts.len();
    // The receiver's holes shift by (inserted - deleted) past the cut, and the
    // ones inside the cut move into the RETURNED array at their offset there.
    let holes = hole_set(recv);
    let removed = with_host(|h| {
        if let Some(JsObj::Array(items)) = h.get_mut(recv) {
            let removed: Vec<Value> = items.splice(start..start + delete, inserts).collect();
            removed
        } else {
            Vec::new()
        }
    });
    let spliced = with_host(|h| {
        h.install_holes(
            recv,
            holes
                .iter()
                .filter_map(|&i| {
                    if i < start {
                        Some(i)
                    } else if i < start + delete {
                        None
                    } else {
                        Some(i - delete + inserted)
                    }
                })
                .collect(),
        );
        (removed, holes.clone())
    });
    // The REMOVED elements come back as an array of the receiver's species
    // (23.1.3.31 step 8), so a subclass gets one of its own kind.
    let (removed, holes) = spliced;
    let out = array_species_create(recv, removed)?;
    with_host(|h| {
        h.install_holes(
            &out,
            holes
                .iter()
                .filter(|&&i| i >= start && i < start + delete)
                .map(|&i| i - start)
                .collect(),
        );
    });
    Ok(out)
}

fn slice_bounds(args: &[Value], len: usize) -> (usize, usize) {
    let norm = |v: f64| -> usize {
        if v < 0.0 {
            ((len as f64 + v).max(0.0)) as usize
        } else {
            (v as usize).min(len)
        }
    };
    let lo = if args.is_empty() || matches!(args[0], Value::Undef) {
        0
    } else {
        norm(arg_num(args, 0))
    };
    let hi = if args.len() < 2 || matches!(args[1], Value::Undef) {
        len
    } else {
        norm(arg_num(args, 1))
    };
    // A start at or past the end (`'World'.slice(2, 1)`) yields the empty range,
    // never a reversed one: JS `slice` clamps `end` up to `start`.
    (lo, hi.max(lo))
}

/// The argument positions each `String.prototype` method coerces with
/// `ToNumber` rather than `ToString`. Everything not listed is a string
/// position — which matters only for a SYMBOL argument, the one value both
/// conversions refuse, and refuse with different wording.
///
/// Measured per method and per position: `'x'.indexOf(sym)` reports the STRING
/// message and `'x'.indexOf('a', sym)` the NUMBER one, and `padStart` is the
/// pair the other way round (a length then a pad string).
const STRING_METHOD_NUMERIC_ARGS: &[(&str, &[usize])] = &[
    ("at", &[0]),
    ("charAt", &[0]),
    ("charCodeAt", &[0]),
    ("codePointAt", &[0]),
    ("endsWith", &[1]),
    ("includes", &[1]),
    ("indexOf", &[1]),
    ("lastIndexOf", &[1]),
    ("padEnd", &[0]),
    ("padStart", &[0]),
    ("repeat", &[0]),
    ("slice", &[0, 1]),
    ("split", &[1]),
    ("startsWith", &[1]),
    ("substr", &[0, 1]),
    ("substring", &[0, 1]),
];

/// Reject a SYMBOL argument before any string method coerces it. 7.1.17 and
/// 7.1.4 both refuse one, so `'x'.padStart(3, sym)` is a TypeError where this
/// rendered `Symbol(d)` into the result — silently, which is the shape of
/// mistake that makes a symbol key leak into text.
fn reject_symbol_args(name: &str, args: &[Value]) -> Result<(), String> {
    let numeric = STRING_METHOD_NUMERIC_ARGS
        .iter()
        .find(|(m, _)| *m == name)
        .map(|(_, ps)| *ps)
        .unwrap_or(&[]);
    for (i, a) in args.iter().enumerate() {
        if with_host(|h| matches!(h.get(a), Some(JsObj::Symbol { .. }))) {
            let kind = if numeric.contains(&i) {
                "number"
            } else {
                "string"
            };
            return Err(host::type_error(&format!(
                "Cannot convert a Symbol value to a {kind}"
            )));
        }
    }
    Ok(())
}

/// Coerce a string method's arguments the way 22.1.3.x does, BEFORE any arm
/// reads them: a numeric position through `ToNumber`, every other through
/// `ToString`. Both run a user `valueOf`/`toString`, and none of them ran —
/// `'x'.padStart({valueOf: () => 3})` produced `"x"` and
/// `'x'.concat({toString: () => 'y'})` produced `"x[object Object]"`.
///
/// The positions that must NOT be coerced are the ones with their own protocol:
/// a RegExp or a `Symbol.replace`/`split`/`match`/`search` carrier at position
/// 0 of the method that honours it, and a callable REPLACEMENT at position 1 of
/// `replace`/`replaceAll`. Each of those already has a path that handles the
/// value as an object, and stringifying it first would take that path away.
/// The argument positions each `Array.prototype` method coerces with
/// `ToNumber` (23.1.3.x). Everything not listed is a VALUE position and must be
/// left alone: `fill`'s first argument, `with`'s second and `splice`'s items
/// are stored as given, and `indexOf`/`includes` compare their first argument
/// without converting it.
const ARRAY_METHOD_NUMERIC_ARGS: &[(&str, &[usize])] = &[
    ("at", &[0]),
    ("copyWithin", &[0, 1, 2]),
    ("fill", &[1, 2]),
    ("flat", &[0]),
    ("includes", &[1]),
    ("indexOf", &[1]),
    ("lastIndexOf", &[1]),
    ("slice", &[0, 1]),
    ("splice", &[0, 1]),
    ("toSpliced", &[0, 1]),
    ("with", &[0]),
];

/// The same for `Number.prototype`. `toLocaleString` takes a LOCALE, not a
/// number, and is deliberately absent.
const NUMBER_METHOD_NUMERIC_ARGS: &[(&str, &[usize])] = &[
    ("toExponential", &[0]),
    ("toFixed", &[0]),
    ("toPrecision", &[0]),
    ("toString", &[0]),
];

/// Replace the listed argument positions with their `ToNumber` value, running a
/// user `valueOf` and propagating a throw from it. Every one of these read the
/// argument with an INFALLIBLE conversion that does no `ToPrimitive` at all, so
/// `[1,2,3].slice({valueOf: () => 1})` sliced from 0 and `(1.234).toFixed(obj)`
/// was a RangeError.
/// `ToNumber(args[i])`, running a user `valueOf` and propagating its throw.
fn to_number_arg(args: &[Value], i: usize) -> Result<f64, String> {
    let v = args.get(i).cloned().unwrap_or(Value::Undef);
    let p = host::to_primitive(&v, "number")?;
    Ok(with_host(|h| h.to_number(&p)))
}

fn coerce_numeric_args(
    table: &[(&str, &[usize])],
    name: &str,
    mut args: Vec<Value>,
) -> Result<Vec<Value>, String> {
    let Some((_, positions)) = table.iter().find(|(m, _)| *m == name) else {
        return Ok(args);
    };
    for &i in *positions {
        let Some(a) = args.get(i) else { continue };
        if matches!(a, Value::Undef) {
            continue;
        }
        let p = host::to_primitive(a, "number")?;
        args[i] = Value::Float(with_host(|h| h.to_number(&p)));
    }
    Ok(args)
}

/// `RegExpCreate(v, flags)` — the regexp a string method builds from a
/// non-RegExp argument. An empty/absent argument makes the empty pattern, which
/// matches at position 0.
fn regexp_from_arg(v: &Value, flags: &str) -> Result<Value, String> {
    let src = if matches!(v, Value::Undef) {
        String::new()
    } else {
        with_host(|h| h.str_of(v))
    };
    let fv = with_host(|h| h.new_str(flags.to_string()));
    let sv = with_host(|h| h.new_str(src));
    regexp_ctor(&[sv, fv])
}

fn coerce_string_args(name: &str, args: Vec<Value>) -> Result<Vec<Value>, String> {
    let numeric = STRING_METHOD_NUMERIC_ARGS
        .iter()
        .find(|(m, _)| *m == name)
        .map(|(_, ps)| *ps)
        .unwrap_or(&[]);
    let protocol = match name {
        "replace" | "replaceAll" => Some("@@replace"),
        "split" => Some("@@split"),
        "match" => Some("@@match"),
        "matchAll" => Some("@@matchAll"),
        "search" => Some("@@search"),
        // These three do not CONSUME `Symbol.match`, they reject a value that
        // carries it (22.1.3.7/23/24 step 3 — `IsRegExp`). Exempting it keeps
        // the object intact so that check still sees one; stringifying first
        // turned the TypeError into an ordinary search.
        "startsWith" | "endsWith" | "includes" => Some("@@match"),
        _ => None,
    };
    let mut out = Vec::with_capacity(args.len());
    for (i, a) in args.into_iter().enumerate() {
        if matches!(a, Value::Undef) {
            out.push(a);
            continue;
        }
        if numeric.contains(&i) {
            let p = host::to_primitive(&a, "number")?;
            out.push(Value::Float(with_host(|h| h.to_number(&p))));
            continue;
        }
        // The IsRegExp trio tests `Symbol.match` for TRUTHINESS (7.2.8 step 2),
        // not for presence: an object carrying `[Symbol.match]: false` is NOT a
        // regexp and coerces like anything else. The consuming protocols use
        // `GetMethod`, which additionally requires a callable.
        let is_regexp_like = matches!(name, "startsWith" | "endsWith" | "includes");
        let carries = |p: &str| match host::protocol_lookup(&a, p) {
            Ok(Some(m)) => {
                if is_regexp_like {
                    with_host(|h| h.truthy(&m))
                } else {
                    with_host(|h| host::is_callable(h, &m))
                }
            }
            _ => false,
        };
        let exempt = with_host(|h| matches!(h.get(&a), Some(JsObj::RegExp(_))))
            || (i == 0 && protocol.is_some_and(carries))
            || (i == 1
                && matches!(name, "replace" | "replaceAll")
                && with_host(|h| host::is_callable(h, &a)));
        if exempt {
            out.push(a);
            continue;
        }
        out.push(host::to_string_value(&a)?);
    }
    Ok(out)
}

fn string_method(s: &str, name: &str, args: Vec<Value>) -> Result<Value, String> {
    reject_symbol_args(name, &args)?;
    let args = coerce_string_args(name, args)?;
    // Every index-bearing method below counts UTF-16 code units, so they all
    // work off this one decoding rather than off `s.chars()` (code points),
    // which agrees only on the BMP. `@@iterator` is the deliberate exception.
    let u = crate::utf16::Units::of(s);
    match name {
        // `for…of` / spread over a string iterates CODE POINTS, not code units:
        // `[..."𝒳"]` is one element in node even though `"𝒳".length` is 2. This
        // is the one string operation that is specified in chars, so it stays
        // on `s.chars()` on purpose — do not "fix" it to match the others.
        "@@iterator" => {
            let items: Vec<Value> = s.chars().map(|c| new_s(c.to_string())).collect();
            Ok(with_host(|h| {
                h.alloc(JsObj::Iter {
                    items,
                    idx: 0,
                    array: None,
                })
            }))
        }
        "toUpperCase" => Ok(new_s(s.to_uppercase())),
        "toLowerCase" => Ok(new_s(s.to_lowercase())),
        // `toLocaleUpperCase`/`toLocaleLowerCase` (22.1.3.26/22.1.3.24) differ
        // from the plain forms only for the locale-specific mappings (Turkish
        // dotless i, Lithuanian accents); with no locale argument they are the
        // Unicode Default Case Conversion, which is exactly `to_uppercase`/
        // `to_lowercase`. They threw `is not a function` before, so the common
        // no-argument call — the only form this runtime can answer, since it
        // carries no ICU — failed outright rather than agreeing with node.
        // A locale ARGUMENT is accepted and ignored; `'I'.toLocaleLowerCase('tr')`
        // is `'i'` here and `'ı'` in node.
        // `String.prototype.toLocaleString` (22.1.3.27) is `toString` — a string
        // has no locale rendering. Missing it made an ARRAY of strings fail too,
        // since `Array.prototype.toLocaleString` invokes it per element.
        "toLocaleString" => Ok(new_s(s.to_string())),
        "toLocaleUpperCase" => Ok(new_s(s.to_uppercase())),
        "toLocaleLowerCase" => Ok(new_s(s.to_lowercase())),
        // Locale comparison (ASCII approximation of ICU collation): primary by
        // case-folded order, then lowercase sorts before uppercase at a tie.
        "localeCompare" => {
            let other = with_host(|h| h.str_of(&arg0(&args)));
            let (la, lb) = (s.to_lowercase(), other.to_lowercase());
            let r = match la.cmp(&lb) {
                std::cmp::Ordering::Less => -1.0,
                std::cmp::Ordering::Greater => 1.0,
                std::cmp::Ordering::Equal => {
                    let mut t = 0.0;
                    for (ca, cb) in s.chars().zip(other.chars()) {
                        if ca != cb {
                            t = if ca.is_lowercase() { -1.0 } else { 1.0 };
                            break;
                        }
                    }
                    t
                }
            };
            Ok(Value::Float(r))
        }
        // `String.prototype.normalize` (22.1.3.15) — real UAX-15 normalization.
        //
        // This used to return the receiver unchanged and only validate the FORM
        // argument, which made every one of the four forms a no-op: `"Å"` (NFC,
        // one code point) and `"Å"` (NFD, two) stayed distinct under
        // `.normalize()`, so the standard way to compare Unicode text for
        // canonical equivalence silently answered `false`, and `NFKC` never
        // folded a compatibility character (`"fi"` stayed one code point instead
        // of becoming `"fi"`). The tables come from `unicode-normalization`.
        "normalize" => {
            use unicode_normalization::UnicodeNormalization;
            let form = match args.first() {
                Some(v) if !matches!(v, Value::Undef) => with_host(|h| h.str_of(v)),
                _ => "NFC".to_string(),
            };
            let out = match form.as_str() {
                "NFC" => s.nfc().collect::<String>(),
                "NFD" => s.nfd().collect::<String>(),
                "NFKC" => s.nfkc().collect::<String>(),
                "NFKD" => s.nfkd().collect::<String>(),
                _ => {
                    return Err(host::range_error(
                        "The normalization form should be one of NFC, NFD, NFKC, NFKD.",
                    ))
                }
            };
            Ok(new_s(out))
        }
        // ES2024 well-formedness (22.1.3.9 / 22.1.3.29). A `String` here is a
        // Rust `String`, whose `char` type EXCLUDES `U+D800..=U+DFFF`, so every
        // value this runtime can hold is well-formed by construction and
        // `toWellFormed` has nothing to replace. Both answers are therefore
        // exact for every string that survives storage; the one case node
        // answers differently is a surrogate half extracted by `charAt`/`slice`,
        // which is already `U+FFFD` here — the documented lone-surrogate
        // boundary in `utf16`, not a separate gap.
        "isWellFormed" => Ok(Value::Bool(true)),
        "toWellFormed" => Ok(new_s(s.to_string())),
        // The JS `WhiteSpace` set, not Rust's — they differ on `U+FEFF`.
        "trim" => Ok(new_s(crate::utf16::js_trim(s).to_string())),
        "trimStart" => Ok(new_s(crate::utf16::js_trim_start(s).to_string())),
        "trimEnd" => Ok(new_s(crate::utf16::js_trim_end(s).to_string())),
        "toString" | "valueOf" => Ok(new_s(s.to_string())),
        "charAt" => {
            let at = unit_pos(arg_num(&args, 0)).and_then(|i| u.unit_str(i));
            Ok(new_s(at.unwrap_or_default()))
        }
        "at" => {
            let n = arg_num(&args, 0);
            // A negative position counts back from the end; `NaN` is 0. An
            // infinite position is out of range in either direction.
            let i = if n.is_nan() {
                Some(0i64)
            } else if n.is_finite() {
                let i = n.trunc() as i64;
                Some(if i < 0 { i + u.len() as i64 } else { i })
            } else {
                None
            };
            match i
                .and_then(|i| usize::try_from(i).ok())
                .and_then(|i| u.unit_str(i))
            {
                Some(c) => Ok(new_s(c)),
                None => Ok(Value::Undef),
            }
        }
        // `charCodeAt` reports the bare code UNIT — the high surrogate of an
        // astral character, not the character. `codePointAt` looks ahead one
        // unit and reports the whole scalar when the pair is well formed. They
        // agree everywhere on the BMP, which is why they used to share an arm.
        // They also disagree OUT of range: `charCodeAt` yields `NaN` while
        // `codePointAt` yields `undefined` (measured on node v26.7.0).
        "charCodeAt" => {
            let unit = unit_pos(arg_num(&args, 0)).and_then(|i| u.unit(i));
            Ok(Value::Float(unit.map(f64::from).unwrap_or(f64::NAN)))
        }
        "codePointAt" => match unit_pos(arg_num(&args, 0)).and_then(|i| u.code_point(i)) {
            Some(cp) => Ok(Value::Float(f64::from(cp))),
            None => Ok(Value::Undef),
        },
        // The search quartet all honor their optional position argument.
        // `"a&b&c".indexOf("&", 2)` must be 3, not 1 — body-parser's
        // parameterCount walks a query string with exactly that call.
        "indexOf" => {
            let needle = needle_units(&args);
            let from = clamp_pos(arg_num(&args, 1), u.len());
            Ok(Value::Float(
                search_from(u.as_slice(), needle.as_slice(), from)
                    .map(|i| i as f64)
                    .unwrap_or(-1.0),
            ))
        }
        "lastIndexOf" => {
            let needle = needle_units(&args);
            // An absent or NaN position means "search the whole string".
            let n = arg_num(&args, 1);
            let upto = if n.is_nan() {
                u.len()
            } else {
                clamp_pos(n, u.len())
            };
            Ok(Value::Float(
                search_last(u.as_slice(), needle.as_slice(), upto)
                    .map(|i| i as f64)
                    .unwrap_or(-1.0),
            ))
        }
        // 22.1.3.7/22.1.3.23/22.1.3.14 step 2: these three reject a REGEXP
        // argument outright, and `IsRegExp` is what decides — so an object
        // advertising `Symbol.match` is rejected too. None of them checked.
        "startsWith" | "endsWith" | "includes" if is_regexp_arg(&arg0(&args)) => {
            Err(host::type_error(&format!(
                "First argument to String.prototype.{name} must not be a regular expression"
            )))
        }
        "includes" => {
            let needle = needle_units(&args);
            let from = clamp_pos(arg_num(&args, 1), u.len());
            Ok(Value::Bool(
                search_from(u.as_slice(), needle.as_slice(), from).is_some(),
            ))
        }
        "startsWith" => {
            let needle = needle_units(&args);
            let from = clamp_pos(arg_num(&args, 1), u.len());
            Ok(Value::Bool(
                u.as_slice()[from..].starts_with(needle.as_slice()),
            ))
        }
        "endsWith" => {
            let needle = needle_units(&args);
            // The 2nd argument is where the string is treated as ENDING.
            let end = if args.len() < 2 || matches!(args[1], Value::Undef) {
                u.len()
            } else {
                clamp_pos(arg_num(&args, 1), u.len())
            };
            Ok(Value::Bool(
                u.as_slice()[..end].ends_with(needle.as_slice()),
            ))
        }
        "slice" => {
            let (lo, hi) = slice_bounds(&args, u.len());
            Ok(new_s(u.slice(lo, hi)))
        }
        "substring" => {
            let mut a = arg_num(&args, 0).max(0.0) as usize;
            let mut b = if args.len() < 2 || matches!(args[1], Value::Undef) {
                u.len()
            } else {
                (arg_num(&args, 1).max(0.0) as usize).min(u.len())
            };
            a = a.min(u.len());
            if a > b {
                std::mem::swap(&mut a, &mut b);
            }
            Ok(new_s(u.slice(a, b)))
        }
        "substr" => {
            // A negative start counts from the end: max(len + start, 0).
            let len = u.len() as i64;
            let mut start = arg_num(&args, 0) as i64;
            if start < 0 {
                start = (len + start).max(0);
            }
            let start = (start as usize).min(u.len());
            let count = if args.len() >= 2 {
                arg_num(&args, 1).max(0.0) as usize
            } else {
                u.len()
            };
            let end = start.saturating_add(count).min(u.len());
            Ok(new_s(u.slice(start, end)))
        }
        "repeat" => {
            let n = arg_num(&args, 0);
            // `RangeError`, not `TypeError`, and the count is named:
            // `"x".repeat(-1)` is `RangeError: Invalid count value: -1`.
            if n < 0.0 || !n.is_finite() {
                return Err(host::range_error(&format!(
                    "Invalid count value: {}",
                    host::fmt_number(n)
                )));
            }
            // The PRODUCT is what V8 bounds, so `''.repeat(2**53)` is legal (and
            // `''`) while `'ab'.repeat(268435445)` is not: measured on node
            // v26.7.0, `'ab'.repeat(268435444).length` is 536870888 and one more
            // is `RangeError: Invalid string length`.
            if n * crate::utf16::len(s) as f64 > host::MAX_STRING_LENGTH as f64 {
                return Err(host::invalid_string_length());
            }
            Ok(new_s(s.repeat(n as usize)))
        }
        "concat" => {
            let mut out = s.to_string();
            for a in &args {
                out.push_str(&with_host(|h| h.str_of(a)));
            }
            Ok(new_s(out))
        }
        "padStart" => Ok(new_s(pad(s, &args, true)?)),
        "padEnd" => Ok(new_s(pad(s, &args, false)?)),
        // Regex-taking string methods: dispatch to the regexp module when the
        // argument is a RegExp; otherwise keep the plain-string behavior.
        // 22.1.3.20 step 2.a: `replaceAll` validates the `g` flag BEFORE it
        // consults `Symbol.replace`, so a non-global regexp is a TypeError even
        // though a RegExp does define that method. Delegating first skipped the
        // check and silently did a single replacement.
        "replaceAll"
            if is_regexp_arg(&arg0(&args))
                && !with_host(
                    |h| matches!(h.get(&arg0(&args)), Some(JsObj::RegExp(r)) if r.global),
                ) =>
        {
            Err(host::type_error(
                "String.prototype.replaceAll called with a non-global RegExp argument",
            ))
        }
        "match" | "matchAll" | "search" | "split" | "replace" | "replaceAll"
            if symbol_protocol(
                &arg0(&args),
                match name {
                    "match" => "@@match",
                    "matchAll" => "@@matchAll",
                    "search" => "@@search",
                    "split" => "@@split",
                    _ => "@@replace",
                },
            )
            .is_some() =>
        {
            let sym = match name {
                "match" => "@@match",
                "matchAll" => "@@matchAll",
                "search" => "@@search",
                "split" => "@@split",
                _ => "@@replace",
            };
            let f = symbol_protocol(&arg0(&args), sym).expect("guard checked");
            let sv = with_host(|h| h.new_str(s.to_string()));
            let mut rest = vec![sv];
            rest.extend(args.iter().skip(1).cloned());
            host::invoke(&f, rest, Some(arg0(&args)))
        }
        // 22.1.3.13/14: a non-RegExp argument is turned INTO one
        // (`RegExpCreate(regexp, …)`), so `'abc'.match('b')` matches. It
        // answered `null` for every string argument, which reads as "no match"
        // — the one answer a caller cannot tell from a real failure.
        // `matchAll` builds its with `g`, which 22.1.3.14 requires.
        "match" => {
            let a = arg0(&args);
            let re = if is_regexp_arg(&a) {
                a
            } else {
                regexp_from_arg(&a, "")?
            };
            crate::regexp::str_match(s, &re)
        }
        "matchAll" => {
            let a = arg0(&args);
            let re = if is_regexp_arg(&a) {
                a
            } else {
                regexp_from_arg(&a, "g")?
            };
            crate::regexp::str_match_all(s, &re)
        }
        "search" => {
            if is_regexp_arg(&arg0(&args)) {
                crate::regexp::str_search(s, &arg0(&args))
            } else {
                // 22.1.3.17 builds a RegExp from the argument, so a
                // METACHARACTER matches as one: `'a.c'.search('.')` is 0, not
                // 1. The substring approximation this replaces agreed only for
                // a literal needle, and answered -1 for an absent argument
                // where the empty pattern matches at 0.
                let re = regexp_from_arg(&arg0(&args), "")?;
                crate::regexp::str_search(s, &re)
            }
        }
        "replace" => {
            let pat = arg0(&args);
            let repl = args.get(1).cloned().unwrap_or(Value::Undef);
            if is_regexp_arg(&pat) {
                crate::regexp::str_replace_regex(s, &pat, &repl, false)
            } else if with_host(|h| host::is_callable(h, &repl)) {
                Ok(new_s(replace_str_fn(
                    s,
                    &with_host(|h| h.str_of(&pat)),
                    &repl,
                    false,
                )?))
            } else {
                let from = with_host(|h| h.str_of(&pat));
                let to = with_host(|h| h.str_of(&repl));
                Ok(new_s(replace_str_plain(s, &from, &to, false)))
            }
        }
        "replaceAll" => {
            let pat = arg0(&args);
            let repl = args.get(1).cloned().unwrap_or(Value::Undef);
            if is_regexp_arg(&pat) {
                // 22.1.3.20 step 2: a non-global regexp is a TypeError here,
                // because `replaceAll` cannot honour "all" without `g`. This
                // used to replace only the first match and say nothing.
                let global = with_host(|h| match h.get(&pat) {
                    Some(JsObj::RegExp(r)) => r.global,
                    _ => true,
                });
                if !global {
                    return Err(host::type_error(
                        "String.prototype.replaceAll called with a non-global RegExp argument",
                    ));
                }
                crate::regexp::str_replace_regex(s, &pat, &repl, true)
            } else if with_host(|h| host::is_callable(h, &repl)) {
                Ok(new_s(replace_str_fn(
                    s,
                    &with_host(|h| h.str_of(&pat)),
                    &repl,
                    true,
                )?))
            } else {
                let from = with_host(|h| h.str_of(&pat));
                let to = with_host(|h| h.str_of(&repl));
                Ok(new_s(replace_str_plain(s, &from, &to, true)))
            }
        }
        "split" => {
            if is_regexp_arg(&arg0(&args)) {
                let limit = args
                    .get(1)
                    .filter(|v| !matches!(v, Value::Undef))
                    .map(|v| with_host(|h| h.to_number(v)) as usize);
                return crate::regexp::str_split_regex(s, &arg0(&args), limit);
            }
            let mut parts: Vec<Value> = if args.is_empty() || matches!(args[0], Value::Undef) {
                vec![new_s(s.to_string())]
            } else {
                let sep = with_host(|h| h.str_of(&args[0]));
                if sep.is_empty() {
                    // `split('')` yields one element per code UNIT, so an astral
                    // character becomes its two surrogate halves.
                    (0..u.len())
                        .filter_map(|i| u.unit_str(i))
                        .map(new_s)
                        .collect()
                } else {
                    s.split(&sep as &str)
                        .map(|p| new_s(p.to_string()))
                        .collect()
                }
            };
            // Optional limit: keep at most `limit` substrings.
            if let Some(lim) = args.get(1).filter(|v| !matches!(v, Value::Undef)) {
                let n = with_host(|h| h.to_number(lim));
                if n.is_finite() && n >= 0.0 {
                    parts.truncate(n as usize);
                }
            }
            Ok(with_host(|h| h.new_array(parts)))
        }
        _ => Err(host::type_error(&format!("{name} is not a function"))),
    }
}

/// GetSubstitution (22.1.3.19) for a STRING search value.
///
/// `String.prototype.replace`/`replaceAll` expand the same `$` patterns whether
/// the pattern is a regexp or a plain string, but the string path here did a
/// raw `str::replace` and passed the template through verbatim — so
/// `'abc'.replace('b', '[$&]')` produced `a[$&]c` instead of `a[b]c`. The
/// regexp path has always expanded them.
///
/// A string search captures nothing, so only `$$`, `$&`, `` $` `` and `$'`
/// apply; `$1` and `$<name>` have no referent and stay literal, which is also
/// what node does.
fn substitute_plain(templ: &str, matched: &str, position: usize, subject: &str) -> String {
    let chars: Vec<char> = templ.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '$' && i + 1 < chars.len() {
            match chars[i + 1] {
                '$' => {
                    out.push('$');
                    i += 2;
                    continue;
                }
                '&' => {
                    out.push_str(matched);
                    i += 2;
                    continue;
                }
                '`' => {
                    out.push_str(&subject[..position]);
                    i += 2;
                    continue;
                }
                '\'' => {
                    out.push_str(&subject[position + matched.len()..]);
                    i += 2;
                    continue;
                }
                _ => {}
            }
        }
        out.push(chars[i]);
        i += 1;
    }
    out
}

/// `replace`/`replaceAll` with a string pattern and a string replacement,
/// expanding each match's `$` patterns against its own position.
fn replace_str_plain(s: &str, from: &str, to: &str, all: bool) -> String {
    if from.is_empty() && !all {
        return format!("{}{s}", substitute_plain(to, "", 0, s));
    }
    let mut out = String::new();
    let mut rest = 0usize;
    while let Some(rel) = s[rest..].find(from) {
        let at = rest + rel;
        out.push_str(&s[rest..at]);
        out.push_str(&substitute_plain(to, from, at, s));
        rest = at + from.len();
        if !all {
            break;
        }
        // An empty pattern matches between every character; step one along so
        // the scan terminates.
        if from.is_empty() {
            if rest >= s.len() {
                break;
            }
            let step = s[rest..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
            out.push_str(&s[rest..rest + step]);
            rest += step;
        }
    }
    out.push_str(&s[rest..]);
    out
}

fn new_s(s: String) -> Value {
    with_host(|h| h.new_str(s))
}

/// Where a forward `indexOf`/`includes` search starts, given the optional
/// `fromIndex` (23.1.3.17 steps 4-6, 23.1.3.16 steps 5-7). A negative value
/// counts back from the end and clamps at 0; absent or `NaN` is 0. A start at
/// or past the end finds nothing, which callers report as `-1` / `false`.
pub(crate) fn search_start(n: f64, len: usize) -> usize {
    if n.is_nan() {
        return 0;
    }
    let n = n.trunc();
    if n >= 0.0 {
        if n >= len as f64 {
            len
        } else {
            n as usize
        }
    } else {
        let from_end = len as f64 + n;
        if from_end <= 0.0 {
            0
        } else {
            from_end as usize
        }
    }
}

/// The INCLUSIVE index a backward `lastIndexOf` starts at (23.1.3.20 steps
/// 4-6), or `None` when `fromIndex` places it before the array. Absent means
/// the last element — which is why this takes an `Option` rather than reading
/// `NaN` as "absent" the way the forward form can: an explicit `NaN` is
/// `ToIntegerOrInfinity`'d to 0 and searches only index 0.
pub(crate) fn search_start_last(from: Option<f64>, len: usize) -> Option<usize> {
    if len == 0 {
        return None;
    }
    let n = match from {
        None => return Some(len - 1),
        Some(v) if v.is_nan() => 0.0,
        Some(v) => v.trunc(),
    };
    if n >= 0.0 {
        Some(if n >= len as f64 { len - 1 } else { n as usize })
    } else {
        let k = len as f64 + n;
        if k < 0.0 {
            None
        } else {
            Some(k as usize)
        }
    }
}

/// `ToIntegerOrInfinity(n)` clamped into `0..=len` — the position argument of
/// the `String.prototype` search methods. `NaN` (an absent argument) is `0`.
fn clamp_pos(n: f64, len: usize) -> usize {
    if n.is_nan() || n <= 0.0 {
        0
    } else if n >= len as f64 {
        len
    } else {
        n.trunc() as usize
    }
}

/// `ToIntegerOrInfinity(n)` as a code-unit position, or `None` when there can be
/// no such unit. `NaN` (an absent argument) is 0; a negative or infinite
/// position is out of range — `"abc".charCodeAt(-1)` is `NaN`, not `'a'`.
fn unit_pos(n: f64) -> Option<usize> {
    if n.is_nan() {
        Some(0)
    } else if n < 0.0 || !n.is_finite() {
        None
    } else {
        Some(n.trunc() as usize)
    }
}

/// The search argument of `indexOf`/`includes`/`startsWith`/… as code units, so
/// the needle is compared in the same alphabet the haystack is indexed by.
fn needle_units(args: &[Value]) -> crate::utf16::Units {
    crate::utf16::Units::of(&with_host(|h| h.str_of(&arg0(args))))
}

/// The lowest index `>= from` at which `needle` occurs in `hay`. An empty
/// needle matches at `from` itself, as JS specifies.
fn search_from(hay: &[u16], needle: &[u16], from: usize) -> Option<usize> {
    if needle.is_empty() {
        return Some(from.min(hay.len()));
    }
    if needle.len() > hay.len() {
        return None;
    }
    (from..=hay.len().saturating_sub(needle.len())).find(|&i| &hay[i..i + needle.len()] == needle)
}

/// The highest index `<= upto` at which `needle` occurs in `hay`.
fn search_last(hay: &[u16], needle: &[u16], upto: usize) -> Option<usize> {
    if needle.is_empty() {
        return Some(upto.min(hay.len()));
    }
    if needle.len() > hay.len() {
        return None;
    }
    let last = hay.len() - needle.len();
    (0..=upto.min(last))
        .rev()
        .find(|&i| &hay[i..i + needle.len()] == needle)
}

fn pad(s: &str, args: &[Value], start: bool) -> Result<String, String> {
    let target_f = arg_num(args, 0);
    let target = if target_f.is_finite() && target_f > 0.0 {
        target_f as usize
    } else {
        0
    };
    // `targetLength` and the padding both count code units: `'𝒳'.padStart(3,'-')`
    // is `'-𝒳'` in node, not `'--𝒳'`.
    let cur = crate::utf16::len(s);
    if cur >= target {
        return Ok(s.to_string());
    }
    let filler = if args.len() >= 2 {
        with_host(|h| h.str_of(&args[1]))
    } else {
        " ".to_string()
    };
    if filler.is_empty() {
        return Ok(s.to_string());
    }
    // Checked only AFTER the two short-circuits, which is the order V8 uses:
    // measured on node v26.7.0, `'ab'.padStart(2**40, '')` is `'ab'` while
    // `'ab'.padStart(536870889, 'x')` is `RangeError: Invalid string length`.
    if target_f > host::MAX_STRING_LENGTH as f64 {
        return Err(host::invalid_string_length());
    }
    let need = target - cur;
    let fill = crate::utf16::Units::of(&filler);
    // The filler repeats and is TRUNCATED to the exact unit count, which can cut
    // a surrogate pair — node yields a lone surrogate there, we yield U+FFFD
    // (see src/utf16.rs).
    let units: Vec<u16> = (0..need)
        .filter_map(|i| fill.unit(i % fill.len()))
        .collect();
    let padding = crate::utf16::to_string_lossy(&units);
    Ok(if start {
        format!("{padding}{s}")
    } else {
        format!("{s}{padding}")
    })
}

/// V8's radix rejection, shared by `Number.prototype.toString` and
/// `BigInt.prototype.toString` — one string, because they are one message and
/// the two sites had drifted apart ("radix must be" vs V8's "radix argument
/// must be").
const RADIX_RANGE: &str = "toString() radix argument must be between 2 and 36";

/// `BigInt.prototype` methods: `toString([radix])`, `valueOf`, `toLocaleString`.
fn bigint_method(b: &num_bigint::BigInt, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "toString" => {
            let radix = match args.first() {
                None | Some(Value::Undef) => 10,
                Some(_) => {
                    let t = arg_num(&args, 0).trunc();
                    if !(2.0..=36.0).contains(&t) {
                        return Err(host::range_error(RADIX_RANGE));
                    }
                    t as u32
                }
            };
            Ok(new_s(b.to_str_radix(radix)))
        }
        // `BigInt.prototype.toLocaleString` groups thousands like the Number
        // one does — `(1234567n).toLocaleString()` is `1,234,567` in node, and
        // returning the bare digits made it the only numeric type that skipped
        // grouping. Same en-US-shaped output as `Number.prototype`; the
        // `locales`/`options` arguments are ignored (no ICU here).
        "toLocaleString" => {
            let digits = b.magnitude().to_string();
            let sign = if b.sign() == num_bigint::Sign::Minus {
                "-"
            } else {
                ""
            };
            Ok(new_s(format!("{sign}{}", group_thousands(&digits))))
        }
        "valueOf" => Ok(with_host(|h| h.new_bigint(b.clone()))),
        _ => Err(host::type_error(&format!("{name} is not a function"))),
    }
}

fn number_method(n: f64, name: &str, args: Vec<Value>) -> Result<Value, String> {
    let args = coerce_numeric_args(NUMBER_METHOD_NUMERIC_ARGS, name, args)?;
    match name {
        "toFixed" => {
            let digits = arg_num(&args, 0);
            if !(0.0..=100.0).contains(&digits.trunc()) {
                return Err(host::range_error(
                    "toFixed() digits argument must be between 0 and 100",
                ));
            }
            Ok(new_s(to_fixed(n, digits as usize)))
        }
        "toExponential" => {
            // `undefined` (or a missing argument) selects the shortest form.
            let f = match args.first() {
                None | Some(Value::Undef) => None,
                Some(_) => {
                    let d = arg_num(&args, 0).trunc();
                    if !(0.0..=100.0).contains(&d) {
                        return Err(host::range_error(
                            "toExponential() argument must be between 0 and 100",
                        ));
                    }
                    Some(d as usize)
                }
            };
            Ok(new_s(to_exponential(n, f)))
        }
        "toString" => {
            // An out-of-range radix THROWS; it does not silently fall back to
            // base 10. `(1).toString(37)` returned "1" here, so a support probe
            // was told every radix worked.
            let radix = match args.first() {
                None | Some(Value::Undef) => 10,
                Some(_) => {
                    let r = arg_num(&args, 0);
                    let t = r.trunc();
                    if !(2.0..=36.0).contains(&t) {
                        return Err(host::range_error(RADIX_RANGE));
                    }
                    t as u32
                }
            };
            if radix == 10 {
                Ok(new_s(host::fmt_number(n)))
            } else {
                Ok(new_s(to_radix(n, radix)))
            }
        }
        "toPrecision" => {
            // `undefined` (or a missing argument) behaves like `toString()`.
            match args.first() {
                None | Some(Value::Undef) => Ok(new_s(host::fmt_number(n))),
                Some(_) => {
                    let p = arg_num(&args, 0).trunc();
                    if !(1.0..=100.0).contains(&p) {
                        return Err(host::range_error(
                            "toPrecision() argument must be between 1 and 100",
                        ));
                    }
                    Ok(new_s(to_precision(n, p as usize)))
                }
            }
        }
        "toLocaleString" => Ok(new_s(to_locale_string(n))),
        "valueOf" => Ok(Value::Float(n)),
        _ => Err(host::type_error(&format!("{name} is not a function"))),
    }
}

/// `Number.prototype.toLocaleString()` with the default locale and options:
/// integer part grouped in threes with `,`, up to 3 fraction digits (rounded
/// half away from zero), trailing fractional zeros dropped. Mirrors V8's default
/// `Intl.NumberFormat().format` output (`(12345.678).toLocaleString()` ⇒
/// `"12,345.678"`; `(1234.5678)` ⇒ `"1,234.568"`). `NaN`, `±Infinity`, and `-0`
/// render as `"NaN"`, `"∞"`/`"-∞"`, and `"-0"`.
fn to_locale_string(n: f64) -> String {
    if n.is_nan() {
        return "NaN".to_string();
    }
    if n.is_infinite() {
        return if n < 0.0 { "-∞" } else { "∞" }.to_string();
    }
    let neg = n.is_sign_negative();
    // Round the magnitude to at most 3 fraction digits, then drop trailing zeros
    // (and a bare trailing point). `to_fixed` rounds half away from zero.
    // `to_fixed` falls back to `ToString` at |x| ≥ 1e21 (spec 21.1.3.3 step 6),
    // which is exponential — and the grouping below then chopped up the
    // exponent, so `(1e21).toLocaleString()` was `1e,+21` instead of node's
    // `1,000,000,000,000,000,000,000`. Expanding the SHORTEST repr is the right
    // source: node groups the shortest decimal form, so `(1e100)
    // .toLocaleString()` is 1 followed by a hundred zeros rather than the exact
    // binary value `1000…159028911…`. (`BigInt(1e100)` is the exact value, a
    // deliberately different rule — see `bigint_ctor`.)
    let fixed = expand_exponential(&to_fixed(n.abs(), 3));
    let trimmed = match fixed.split_once('.') {
        Some(_) => fixed.trim_end_matches('0').trim_end_matches('.'),
        None => fixed.as_str(),
    };
    let (int_part, frac_part) = match trimmed.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (trimmed, None),
    };
    let mut out = String::new();
    if neg {
        out.push('-'); // Intl keeps the sign even for -0.
    }
    out.push_str(&group_thousands(int_part));
    if let Some(f) = frac_part {
        out.push('.');
        out.push_str(f);
    }
    out
}

/// Write a nonnegative decimal string in plain positional form, expanding an
/// `e+NN` exponent into zeros. `"1e+21"` → `"1000000000000000000000"`,
/// `"1.5e+21"` → `"1500000000000000000000"`. A string with no exponent, or a
/// negative exponent (a magnitude below 1, which the caller has already rounded
/// to zero), is returned unchanged.
fn expand_exponential(s: &str) -> String {
    let Some((mantissa, exp)) = s.split_once(['e', 'E']) else {
        return s.to_string();
    };
    let Ok(exp) = exp.trim_start_matches('+').parse::<i32>() else {
        return s.to_string();
    };
    if exp <= 0 {
        return s.to_string();
    }
    let (int_digits, frac_digits) = match mantissa.split_once('.') {
        Some((i, f)) => (i.to_string(), f.to_string()),
        None => (mantissa.to_string(), String::new()),
    };
    let mut digits = int_digits;
    digits.push_str(&frac_digits);
    // The exponent consumes the fractional digits first; whatever is left
    // becomes trailing zeros.
    let zeros = exp as usize - frac_digits.len().min(exp as usize);
    digits.push_str(&"0".repeat(zeros));
    digits
}

/// Insert `,` as a thousands separator into a nonnegative integer digit string.
fn group_thousands(int_part: &str) -> String {
    let bytes = int_part.as_bytes();
    let n = bytes.len();
    let mut out = String::with_capacity(n + n / 3);
    for (i, &b) in bytes.iter().enumerate() {
        if i > 0 && (n - i) % 3 == 0 {
            out.push(',');
        }
        out.push(b as char);
    }
    out
}

/// `Number.prototype.toFixed(f)`: fixed-point with `f` fractional digits, rounding
/// half away from zero on the actual IEEE-754 value (so `(1.005).toFixed(2)` is
/// `"1.00"` because 1.005 is really 1.00499…). The sign of a negative input is
/// preserved even when the rounded magnitude is zero: `(-0.4).toFixed(0) === "-0"`.
///
/// The rounding is done on the value's EXACT decimal expansion (Rust's fixed
/// formatting is exact), not on `x * 10^f` — the latter loses precision for large
/// magnitudes (`(9.999999e20).toFixed(4)` must keep every integer digit).
fn to_fixed(n: f64, f: usize) -> String {
    if !n.is_finite() {
        return host::fmt_number(n);
    }
    // Spec: for |x| ≥ 10^21, toFixed falls back to ToString(x).
    if n.abs() >= 1e21 {
        return host::fmt_number(n);
    }
    let neg = n < 0.0;
    // Exact decimal with guard digits past the rounding position; then round the
    // digit string half-away-from-zero (nonneg operand ⇒ round-half-up).
    let full = format!("{:.*}", f + 25, n.abs());
    let mut body = round_decimal_string(&full, f);
    if neg {
        body.insert(0, '-'); // JS keeps the sign even for "-0" / "-0.00".
    }
    body
}

/// Round the exact decimal string `s` (`"int.frac"`, nonnegative) to `f`
/// fractional digits, half away from zero, propagating carry across the point.
fn round_decimal_string(s: &str, f: usize) -> String {
    let (int_part, frac_part) = s.split_once('.').unwrap_or((s, ""));
    let mut digits: Vec<u8> = int_part
        .bytes()
        .chain(frac_part.bytes())
        .map(|b| b - b'0')
        .collect();
    let point = int_part.len(); // digits before the decimal point
    let keep = point + f; // number of leading digits to keep

    // Round up if the first dropped digit is ≥ 5 (exact-half ⇒ up).
    if digits.get(keep).map(|&d| d >= 5).unwrap_or(false) {
        let mut i = keep;
        loop {
            if i == 0 {
                digits.insert(0, 1);
                // A new leading digit shifts the decimal point right by one.
                return assemble_decimal(&digits, point + 1, f);
            }
            i -= 1;
            if digits[i] == 9 {
                digits[i] = 0;
            } else {
                digits[i] += 1;
                break;
            }
        }
    }
    assemble_decimal(&digits, point, f)
}

/// Reassemble `digits` into `"int.frac"` keeping `f` fractional digits, given that
/// `point` digits precede the decimal point.
fn assemble_decimal(digits: &[u8], point: usize, f: usize) -> String {
    let int_str: String = digits[..point].iter().map(|d| (d + b'0') as char).collect();
    let int_str = int_str.trim_start_matches('0');
    let int_str = if int_str.is_empty() { "0" } else { int_str };
    if f == 0 {
        return int_str.to_string();
    }
    let frac: String = digits[point..point + f]
        .iter()
        .map(|d| (d + b'0') as char)
        .collect();
    format!("{int_str}.{frac}")
}

/// Round the nonnegative finite `a` to `p` significant decimal digits, half away
/// from zero, returning the `p` digits and the decimal exponent `e` such that the
/// value is `0.d…d × 10^(e+1)` (i.e. `d.d…d e±e`). Rust's `{:.*e}` rounds half to
/// EVEN (`(2.5)` at 1 digit would give "2"), but JS rounds half up ("3"), so the
/// exact digits are taken with guard positions and rounded here.
fn round_significant(a: f64, p: usize) -> (String, i32) {
    let sci = format!("{a:.*e}", p - 1 + 25);
    let (mant, exp_str) = sci.split_once('e').expect("LowerExp always has 'e'");
    let mut e: i32 = exp_str.parse().expect("LowerExp exponent is an integer");
    let all: Vec<u8> = mant
        .chars()
        .filter(|c| c.is_ascii_digit())
        .map(|c| c as u8 - b'0')
        .collect();
    let mut s: String = all[..p].iter().map(|d| (d + b'0') as char).collect();
    if all.get(p).map(|&d| d >= 5).unwrap_or(false) {
        // Round the p-digit mantissa up, propagating carry; a carry out of the
        // leading digit (`9.99 → 10`) bumps the decimal exponent by one.
        let mut d: Vec<u8> = all[..p].to_vec();
        let mut i = p;
        loop {
            if i == 0 {
                d.insert(0, 1);
                d.truncate(p);
                e += 1;
                break;
            }
            i -= 1;
            if d[i] == 9 {
                d[i] = 0;
            } else {
                d[i] += 1;
                break;
            }
        }
        s = d.iter().map(|x| (x + b'0') as char).collect();
    }
    (s, e)
}

/// `Number.prototype.toExponential(f)`: one digit before the point and `f` after,
/// with a signed decimal exponent (`(100).toExponential(2) === "1.00e+2"`). With
/// `f` omitted, as many digits as uniquely identify the value are used
/// (`(123456).toExponential() === "1.23456e+5"`). Rounding is half away from zero
/// on the exact value, matching `toPrecision`.
fn to_exponential(n: f64, f: Option<usize>) -> String {
    if !n.is_finite() {
        return host::fmt_number(n);
    }
    let neg = n < 0.0;
    let a = n.abs();
    let (s, e) = if a == 0.0 {
        // Zero has no significant digits: emit "0" padded to the requested width.
        ("0".repeat(f.unwrap_or(0) + 1), 0)
    } else {
        match f {
            Some(f) => round_significant(a, f + 1),
            None => {
                // Shortest round-tripping digits (Rust's `{:e}` is shortest).
                let sci = format!("{a:e}");
                let (mant, exp_str) = sci.split_once('e').expect("LowerExp always has 'e'");
                let digits: String = mant.chars().filter(|c| c.is_ascii_digit()).collect();
                let trimmed = digits.trim_end_matches('0');
                let digits = if trimmed.is_empty() { "0" } else { trimmed };
                (digits.to_string(), exp_str.parse().unwrap_or(0))
            }
        }
    };
    let sign = if e >= 0 { '+' } else { '-' };
    let mag = e.abs();
    let body = if s.len() == 1 {
        format!("{s}e{sign}{mag}")
    } else {
        format!("{}.{}e{sign}{mag}", &s[..1], &s[1..])
    };
    if neg {
        format!("-{body}")
    } else {
        body
    }
}

/// `Number.prototype.toPrecision(p)`: `p` significant digits, switching to
/// exponential form when the decimal exponent `e` satisfies `e < -6` or `e ≥ p`
/// (ECMAScript Number.prototype.toPrecision). Trailing zeros are significant and
/// retained (`(100).toPrecision(5) === "100.00"`).
fn to_precision(n: f64, p: usize) -> String {
    if !n.is_finite() {
        return host::fmt_number(n);
    }
    if n == 0.0 {
        return if p == 1 {
            "0".into()
        } else {
            format!("0.{}", "0".repeat(p - 1))
        };
    }
    let neg = n < 0.0;
    let (s, e) = round_significant(n.abs(), p);
    let pp = p as i32;

    let body = if e < -6 || e >= pp {
        // Exponential: first digit, optional '.rest', signed exponent.
        let sign = if e >= 0 { '+' } else { '-' };
        let mag = e.abs();
        if p == 1 {
            format!("{s}e{sign}{mag}")
        } else {
            format!("{}.{}e{sign}{mag}", &s[..1], &s[1..])
        }
    } else if e >= 0 {
        // e in 0..p-1: (e+1) integer digits, then any remaining as fraction.
        let ip = (e + 1) as usize;
        if ip == p {
            s
        } else {
            format!("{}.{}", &s[..ip], &s[ip..])
        }
    } else {
        // -6 ≤ e < 0: "0." then (−e−1) zeros then all p digits.
        format!("0.{}{}", "0".repeat((-e - 1) as usize), s)
    };
    if neg {
        format!("-{body}")
    } else {
        body
    }
}

/// `Number.prototype.toString(radix)` for radix 2..=36 (radix 10 goes through
/// `fmt_number`). Faithful port of V8's `DoubleToRadixCString`: the integer part
/// is emitted exact, and fractional digits are produced up to the input double's
/// precision (terminating via a ULP-sized `delta`), with round-half-to-even and
/// carry-over back into already-written digits (and into the integer part).
fn to_radix(n: f64, radix: u32) -> String {
    if !n.is_finite() {
        return host::fmt_number(n);
    }
    let digits = b"0123456789abcdefghijklmnopqrstuvwxyz";
    let rf = radix as f64;
    let neg = n < 0.0;
    let value = n.abs();

    let mut integer = value.floor();
    let mut fraction = value - integer;

    // Fraction digits, most-significant first.
    let mut frac: Vec<u8> = Vec::new();
    // Only compute fractional digits down to the input double's precision.
    let mut delta = 0.5 * (next_up(value) - value);
    delta = delta.max(next_up(0.0));
    if fraction >= delta {
        loop {
            // Shift up by one digit.
            fraction *= rf;
            delta *= rf;
            let digit = fraction as usize;
            frac.push(digits[digit]);
            fraction -= digit as f64;
            // Round to even.
            if (fraction > 0.5 || (fraction == 0.5 && (digit & 1) == 1)) && fraction + delta > 1.0 {
                // Carry-over: back-trace already-written fraction digits.
                loop {
                    match frac.pop() {
                        None => {
                            // Carried past the point into the integer part.
                            integer += 1.0;
                            break;
                        }
                        Some(c) => {
                            let d = if c > b'9' {
                                (c - b'a' + 10) as u32
                            } else {
                                (c - b'0') as u32
                            };
                            if d + 1 < radix {
                                frac.push(digits[(d + 1) as usize]);
                                break;
                            }
                            // digit was radix-1: drop it and keep carrying.
                        }
                    }
                }
                break;
            }
            if fraction < delta {
                break;
            }
        }
    }

    // Integer digits, least-significant first (reversed at the end).
    let mut int_out: Vec<u8> = Vec::new();
    // For magnitudes ≥ 2^53, `fmod` loses low bits: pre-fill trailing zeros.
    while v8_exponent(integer / rf) > 0 {
        integer /= rf;
        int_out.push(b'0');
    }
    loop {
        let remainder = integer % rf;
        int_out.push(digits[remainder as usize]);
        integer = (integer - remainder) / rf;
        if integer <= 0.0 {
            break;
        }
    }
    int_out.reverse();

    let mut out: Vec<u8> = Vec::new();
    if neg {
        out.push(b'-');
    }
    out.extend_from_slice(&int_out);
    if !frac.is_empty() {
        out.push(b'.');
        out.extend_from_slice(&frac);
    }
    String::from_utf8(out).unwrap()
}

/// Next representable f64 above `x` (`x` finite, `x ≥ 0`) — V8's `NextDouble`.
fn next_up(x: f64) -> f64 {
    f64::from_bits(x.to_bits() + 1)
}

/// V8's `Double::Exponent`: the binary exponent of the significand-scaled value
/// (`> 0` iff |x| ≥ 2^53). Used to detect integers past `fmod`'s exact range.
fn v8_exponent(x: f64) -> i32 {
    let biased = ((x.to_bits() >> 52) & 0x7ff) as i32;
    if biased == 0 {
        -1074 // denormal
    } else {
        biased - 1075
    }
}

// ══ Map / Set / Symbol / generator methods ═══════════════════════════════════

/// `Map.prototype.set` step 6 and `Set.prototype.add` step 4: a key of `-0` is
/// STORED as `+0`. `map_key` already treats the two as one key (SameValueZero),
/// but the value kept alongside it is what iteration and `console.log` report,
/// and node shows `0` there — `new Map().set(-0, 1)` renders `Map(1) { 0 => 1 }`.
fn normalize_zero_key(v: Value) -> Value {
    match v {
        Value::Float(f) if f == 0.0 && f.is_sign_negative() => Value::Float(0.0),
        other => other,
    }
}

fn map_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "get" => {
            let key = with_host(|h| host::map_key(h, &arg0(&args)));
            Ok(with_host(|h| match h.get(recv) {
                Some(JsObj::Map { entries, .. }) => entries
                    .get(&key)
                    .map(|(_, v)| v.clone())
                    .unwrap_or(Value::Undef),
                _ => Value::Undef,
            }))
        }
        "set" => {
            let kv = normalize_zero_key(arg0(&args));
            let vv = args.get(1).cloned().unwrap_or(Value::Undef);
            reject_non_object_weak_key(recv, &kv, "WeakMap")?;
            let key = with_host(|h| host::map_key(h, &kv));
            with_host(|h| {
                if let Some(JsObj::Map { entries, .. }) = h.get_mut(recv) {
                    entries.insert(key, (kv, vv));
                }
            });
            Ok(recv.clone())
        }
        "has" => {
            let key = with_host(|h| host::map_key(h, &arg0(&args)));
            Ok(Value::Bool(with_host(
                |h| matches!(h.get(recv), Some(JsObj::Map { entries, .. }) if entries.contains_key(&key)),
            )))
        }
        "delete" => {
            let key = with_host(|h| host::map_key(h, &arg0(&args)));
            Ok(Value::Bool(with_host(|h| match h.get_mut(recv) {
                Some(JsObj::Map { entries, .. }) => entries.shift_remove(&key).is_some(),
                _ => false,
            })))
        }
        "clear" => {
            with_host(|h| {
                if let Some(JsObj::Map { entries, .. }) = h.get_mut(recv) {
                    entries.clear();
                }
            });
            Ok(Value::Undef)
        }
        "forEach" => {
            let cb = arg0(&args);
            let pairs: Vec<(Value, Value)> = with_host(|h| match h.get(recv) {
                Some(JsObj::Map { entries, .. }) => entries.values().cloned().collect(),
                _ => Vec::new(),
            });
            for (k, v) in pairs {
                host::invoke(&cb, vec![v, k, recv.clone()], this_arg(&args, 1))?;
            }
            Ok(Value::Undef)
        }
        // LIVE, not a snapshot: an entry added during iteration is visited and
        // one deleted before it is reached is not.
        "keys" | "values" | "entries" | "@@iterator" => Ok(collection_iterator(
            recv,
            if name == "@@iterator" {
                "entries"
            } else {
                name
            },
        )),
        _ => Err(host::type_error(&format!("map.{name} is not a function"))),
    }
}

/// A weak collection can only hold objects (and unregistered symbols) — a
/// primitive key is a `TypeError`, which is how packages probe for weak support.
fn reject_non_object_weak_key(recv: &Value, key: &Value, kind: &str) -> Result<(), String> {
    let weak = with_host(|h| {
        matches!(
            h.get(recv),
            Some(JsObj::Map { weak: true, .. }) | Some(JsObj::Set { weak: true, .. })
        )
    });
    if !weak {
        return Ok(());
    }
    let is_object = with_host(|h| match key {
        Value::Obj(_) => !h.is_null(key) && h.as_str(key).is_none() && h.as_bigint(key).is_none(),
        _ => false,
    });
    if is_object {
        return Ok(());
    }
    Err(host::type_error(if kind == "WeakMap" {
        "Invalid value used as weak map key"
    } else {
        "Invalid value used in weak set"
    }))
}

/// A `Set`-like operand of the ES2025 set methods — 24.2.1.2 `GetSetRecord`.
///
/// The seven set operations do NOT require a real `Set` on the right-hand side:
/// anything with a numeric `size` and callable `has`/`keys` participates, which
/// is what lets a `Map`'s key view or a user-written set stand in. The reads
/// happen in this order (`size`, `has`, `keys`) and each failure has its own
/// diagnostic, so a bad operand reports which field was wrong rather than
/// failing later inside the iteration.
struct SetRecord {
    obj: Value,
    /// `size` truncated toward zero, as the spec's `intSize` is; the fractional
    /// part is dropped BEFORE the negative check, so `size: -0.5` truncates to
    /// `-0` and is accepted while `-1.5` reports `'-1' is an invalid size`.
    size: f64,
    has: Value,
    keys: Value,
}

fn get_set_record(other: &Value, method: &str) -> Result<SetRecord, String> {
    if !with_host(|h| is_object_like(h, other)) {
        return Err(host::type_error(&format!(
            "Set.prototype.{method} argument must be an object"
        )));
    }
    let raw = get_property(other, "size")?;
    let num = host::to_number_value(&raw)?;
    if num.is_nan() {
        return Err(host::type_error("The .size property is NaN"));
    }
    let size = num.trunc();
    if size < 0.0 {
        return Err(host::range_error(&format!("'{size}' is an invalid size")));
    }
    let has = get_property(other, "has")?;
    if !with_host(|h| host::is_callable(h, &has)) {
        return Err(host::type_error("string \"has\" is not a function"));
    }
    let keys = get_property(other, "keys")?;
    if !with_host(|h| host::is_callable(h, &keys)) {
        return Err(host::type_error("string \"keys\" is not a function"));
    }
    Ok(SetRecord {
        obj: other.clone(),
        size,
        has,
        keys,
    })
}

impl SetRecord {
    /// `Call(has, obj, [v])`, coerced to a boolean the way the spec's
    /// `ToBoolean(Call(...))` is — a set-like may answer with anything truthy.
    fn has(&self, v: &Value) -> Result<bool, String> {
        let r = host::invoke(&self.has, vec![v.clone()], Some(self.obj.clone()))?;
        Ok(with_host(|h| h.truthy(&r)))
    }

    /// The operand's elements, drained from the iterator its `keys` method
    /// returns. A non-object result is the spec's `Result of the keys method is
    /// not an object`, reported before anything is iterated.
    fn keys(&self) -> Result<Vec<Value>, String> {
        let it = host::invoke(&self.keys, Vec::new(), Some(self.obj.clone()))?;
        if !with_host(|h| is_object_like(h, &it)) {
            return Err(host::type_error(
                "Result of the keys method is not an object",
            ));
        }
        host::drain_iterator(&it)
    }
}

/// The receiver of a set operation must be a real (non-weak) `Set`: these seven
/// methods read `[[SetData]]` directly, so a look-alike cannot stand in on the
/// LEFT even though it can on the right.
fn require_set_receiver(recv: &Value, method: &str) -> Result<(), String> {
    if with_host(|h| matches!(h.get(recv), Some(JsObj::Set { weak: false, .. }))) {
        return Ok(());
    }
    Err(host::type_error(&format!(
        "Method Set.prototype.{method} called on incompatible receiver {}",
        with_host(|h| object_tag(h, recv))
    )))
}

/// The receiver's elements, READ AT THE POINT THE SPEC READS THEM.
///
/// Every one of these operations copies `[[SetData]]` *after* it has touched
/// the operand — `union` and `symmetricDifference` call the operand's `keys`
/// first — so a `keys` (or a `has`) that mutates the receiver is visible in the
/// result. Snapshotting the receiver up front instead dropped such an element:
/// node's `s.union({ keys(){ s.add(99); … } })` contains `99`.
fn set_values(recv: &Value) -> Vec<Value> {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
        _ => Vec::new(),
    })
}

fn set_size(recv: &Value) -> f64 {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Set { entries, .. }) => entries.len() as f64,
        _ => 0.0,
    })
}

/// A fresh, ordinary `Set`. The set operations are NOT species-aware: on node
/// `class S extends Set {}`, `new S([1]).union(other).constructor` is `Set`.
fn new_set(items: Vec<Value>) -> Result<Value, String> {
    let s = with_host(|h| {
        h.alloc(JsObj::Set {
            entries: IndexMap::new(),
            weak: false,
        })
    });
    for v in items {
        set_method(&s, "add", vec![v])?;
    }
    Ok(s)
}

fn set_contains(s: &Value, v: &Value) -> bool {
    let key = with_host(|h| host::map_key(h, v));
    with_host(
        |h| matches!(h.get(s), Some(JsObj::Set { entries, .. }) if entries.contains_key(&key)),
    )
}

/// The seven ES2025 set operations (24.2.4.3, .8, .5, .16, .10, .12, .7).
///
/// Each one branches on the two sizes and iterates the SMALLER side — not an
/// optimization but observable behaviour: which side is walked decides the
/// result's order and whether the operand's `has` or its `keys` is the method
/// that runs. `intersection` of a 3-element receiver with a 2-element operand
/// yields the operand's order, and its `keys` (never its `has`) is called.
fn set_operation(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    require_set_receiver(recv, name)?;
    let other = get_set_record(&arg0(&args), name)?;
    let my_size = set_size(recv);
    match name {
        "union" => {
            let keys = other.keys()?;
            let mut out = set_values(recv);
            out.extend(keys);
            new_set(out)
        }
        "intersection" => {
            let mut out = Vec::new();
            if my_size <= other.size {
                for v in set_values(recv) {
                    if other.has(&v)? {
                        out.push(v);
                    }
                }
            } else {
                for k in other.keys()? {
                    if set_contains(recv, &k) {
                        out.push(k);
                    }
                }
            }
            new_set(out)
        }
        "difference" => {
            if my_size <= other.size {
                let mut out = Vec::new();
                for v in set_values(recv) {
                    if !other.has(&v)? {
                        out.push(v);
                    }
                }
                return new_set(out);
            }
            let out = new_set(set_values(recv))?;
            for k in other.keys()? {
                set_method(&out, "delete", vec![k])?;
            }
            Ok(out)
        }
        "symmetricDifference" => {
            // The operand is drained FIRST — the spec takes the iterator before
            // it copies `[[SetData]]`, so a `keys` that mutates the receiver is
            // reflected in the result.
            let keys = other.keys()?;
            let out = new_set(set_values(recv))?;
            for k in keys {
                if set_contains(recv, &k) {
                    set_method(&out, "delete", vec![k])?;
                } else {
                    set_method(&out, "add", vec![k])?;
                }
            }
            Ok(out)
        }
        "isSubsetOf" => {
            if my_size > other.size {
                return Ok(Value::Bool(false));
            }
            for v in set_values(recv) {
                if !other.has(&v)? {
                    return Ok(Value::Bool(false));
                }
            }
            Ok(Value::Bool(true))
        }
        "isSupersetOf" => {
            if my_size < other.size {
                return Ok(Value::Bool(false));
            }
            for k in other.keys()? {
                if !set_contains(recv, &k) {
                    return Ok(Value::Bool(false));
                }
            }
            Ok(Value::Bool(true))
        }
        "isDisjointFrom" => {
            if my_size <= other.size {
                for v in set_values(recv) {
                    if other.has(&v)? {
                        return Ok(Value::Bool(false));
                    }
                }
            } else {
                for k in other.keys()? {
                    if set_contains(recv, &k) {
                        return Ok(Value::Bool(false));
                    }
                }
            }
            Ok(Value::Bool(true))
        }
        _ => Err(host::type_error(&format!("set.{name} is not a function"))),
    }
}

fn set_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "add" => {
            let vv = normalize_zero_key(arg0(&args));
            reject_non_object_weak_key(recv, &vv, "WeakSet")?;
            let key = with_host(|h| host::map_key(h, &vv));
            with_host(|h| {
                if let Some(JsObj::Set { entries, .. }) = h.get_mut(recv) {
                    entries.insert(key, vv);
                }
            });
            Ok(recv.clone())
        }
        "has" => {
            let key = with_host(|h| host::map_key(h, &arg0(&args)));
            Ok(Value::Bool(with_host(
                |h| matches!(h.get(recv), Some(JsObj::Set { entries, .. }) if entries.contains_key(&key)),
            )))
        }
        "delete" => {
            let key = with_host(|h| host::map_key(h, &arg0(&args)));
            Ok(Value::Bool(with_host(|h| match h.get_mut(recv) {
                Some(JsObj::Set { entries, .. }) => entries.shift_remove(&key).is_some(),
                _ => false,
            })))
        }
        "clear" => {
            with_host(|h| {
                if let Some(JsObj::Set { entries, .. }) = h.get_mut(recv) {
                    entries.clear();
                }
            });
            Ok(Value::Undef)
        }
        "forEach" => {
            let cb = arg0(&args);
            let vals: Vec<Value> = with_host(|h| match h.get(recv) {
                Some(JsObj::Set { entries, .. }) => entries.values().cloned().collect(),
                _ => Vec::new(),
            });
            for v in vals {
                host::invoke(&cb, vec![v.clone(), v, recv.clone()], this_arg(&args, 1))?;
            }
            Ok(Value::Undef)
        }
        "union"
        | "intersection"
        | "difference"
        | "symmetricDifference"
        | "isSubsetOf"
        | "isSupersetOf"
        | "isDisjointFrom" => set_operation(recv, name, args),
        // LIVE, as for `Map`. A Set's `keys` and `values` are the same thing.
        "keys" | "values" | "entries" | "@@iterator" => Ok(collection_iterator(
            recv,
            if name == "entries" {
                "entries"
            } else {
                "values"
            },
        )),
        _ => Err(host::type_error(&format!("set.{name} is not a function"))),
    }
}

fn generator_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    // A generator IS its own iterator: both symbol forms return the receiver.
    if matches!(name, "@@iterator" | "@@asyncIterator") {
        return Ok(recv.clone());
    }
    // An `async function*` object's methods return PROMISES of the record, and
    // its body has to be driven through the await-aware stepper (a plain
    // `gen_resume` would surface an internal `await` suspension as a bogus yield).
    if host::is_async_generator(recv) {
        // All three go through `[[AsyncGeneratorQueue]]` (ECMA-262 27.6.3.6):
        // `.return`/`.throw` must wait behind a `.next()` that is still
        // suspended on an internal `await`, or that `.next()` would report
        // `{done: true}` for a value the body had not yet reached. An uncaught
        // `.throw(e)` rejects the returned promise; it does not throw here.
        return match name {
            "next" => Ok(host::async_gen_enqueue(
                recv,
                host::GenReq::Next(arg0(&args)),
            )),
            "return" => Ok(host::async_gen_enqueue(
                recv,
                host::GenReq::Return(arg0(&args)),
            )),
            "throw" => Ok(host::async_gen_enqueue(
                recv,
                host::GenReq::Throw(arg0(&args)),
            )),
            "@@asyncIterator" => Ok(recv.clone()),
            _ => Err(host::type_error(&format!(
                "asyncGenerator.{name} is not a function"
            ))),
        };
    }
    match name {
        "next" => {
            let send = arg0(&args);
            match host::gen_resume(recv, send)? {
                host::GenStep::Yield(v) => Ok(iter_result(v, false)),
                host::GenStep::Done(v) => Ok(iter_result(v, true)),
            }
        }
        "return" => {
            // Resume with an injected return so any pending `finally` runs; the
            // completion may itself be a `finally` yield (not-done) or the value.
            match host::gen_return(recv, arg0(&args))? {
                host::GenStep::Yield(v) => Ok(iter_result(v, false)),
                host::GenStep::Done(v) => Ok(iter_result(v, true)),
            }
        }
        "throw" => {
            // Inject a throw at the suspension point: an enclosing `try/catch` in
            // the body can handle it (and any `finally` runs); otherwise it
            // propagates to the caller.
            match host::gen_throw(recv, arg0(&args))? {
                host::GenStep::Yield(v) => Ok(iter_result(v, false)),
                host::GenStep::Done(v) => Ok(iter_result(v, true)),
            }
        }
        _ => Err(host::type_error(&format!(
            "generator.{name} is not a function"
        ))),
    }
}

/// A `{ value, done }` iterator-result object.
fn iter_result(value: Value, done: bool) -> Value {
    with_host(|h| {
        let mut m: IndexMap<String, Value> = IndexMap::new();
        m.insert("value".into(), value);
        m.insert("done".into(), Value::Bool(done));
        h.new_object(m)
    })
}

/// A live iterator over array `arr` — what `keys()`, `values()`, `entries()`
/// and `Symbol.iterator` return, and what a `for-of` over an array steps.
pub(crate) fn array_iterator(arr: &Value, kind: host::ArrayIterKind) -> Value {
    with_host(|h| {
        h.alloc(JsObj::Iter {
            items: Vec::new(),
            idx: 0,
            array: Some((arr.clone(), kind)),
        })
    })
}

/// One step of a `JsObj::Iter`: `None` when `it` is not one, `Some(None)` once
/// it is exhausted, otherwise the next value.
///
/// An array iterator reads the array at every step (23.1.5.1
/// `%ArrayIteratorPrototype%.next`): the length is re-read, so an element
/// pushed during a `for-of` is visited and one popped is not, and the element
/// is read as `a[i]` reads it — an accessor runs, a hole reads through the
/// prototype. Once it reports done it stays done, even if the array grows.
pub(crate) fn iter_step(it: &Value) -> Option<Option<Value>> {
    use host::ArrayIterKind;
    // One host borrow for the common case — a snapshot, or an array slot that
    // is neither a hole nor an accessor. `Err` carries what only `[[Get]]` can
    // read: the array, the kind and the index.
    let step = with_host(|h| {
        let (arr, kind, i) = match h.get_mut(it) {
            Some(JsObj::Iter {
                items,
                idx,
                array: None,
            }) => {
                let v = items.get(*idx).cloned();
                if v.is_some() {
                    *idx += 1;
                }
                return Some(Ok(v));
            }
            Some(JsObj::Iter {
                idx,
                array: Some((arr, kind)),
                ..
            }) => (arr.clone(), *kind, *idx),
            _ => return None,
        };
        // `usize::MAX` marks an iterator that has already reported done, and
        // it stays done even if the array grows.
        let len = match h.get(&arr) {
            Some(JsObj::Array(items)) => items.len(),
            _ => 0,
        };
        let done = i == usize::MAX || i >= len;
        if let Some(JsObj::Iter { idx, .. }) = h.get_mut(it) {
            *idx = if done { usize::MAX } else { i + 1 };
        }
        if done {
            return Some(Ok(None));
        }
        let key = Value::Float(i as f64);
        let slot = match (kind, h.get(&arr)) {
            (ArrayIterKind::Keys, _) => return Some(Ok(Some(key))),
            (_, Some(JsObj::Array(items)))
                if !h.is_hole(&arr, i) && h.own_accessor_keys(&arr).is_empty() =>
            {
                items[i].clone()
            }
            _ => return Some(Err((arr, kind, i))),
        };
        Some(Ok(Some(match kind {
            ArrayIterKind::Entries => h.new_array(vec![key, slot]),
            _ => slot,
        })))
    })?;
    let (arr, kind, i) = match step {
        Ok(step) => return Some(step),
        Err(slow) => slow,
    };
    let value = get_property(&arr, &i.to_string()).unwrap_or(Value::Undef);
    Some(Some(match kind {
        ArrayIterKind::Entries => with_host(|h| h.new_array(vec![Value::Float(i as f64), value])),
        _ => value,
    }))
}

/// Built-in iterator object (`arr.values()`, `arr[Symbol.iterator]()`): a
/// cursor over a snapshot, or live over an array ([`iter_step`]).
fn iter_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "next" => Ok(match iter_step(recv).flatten() {
            Some(v) => iter_result(v, false),
            None => iter_result(Value::Undef, true),
        }),
        "return" => {
            // Exhaust the cursor and report done.
            with_host(|h| {
                if let Some(JsObj::Iter { items, idx, array }) = h.get_mut(recv) {
                    *idx = if array.is_some() {
                        usize::MAX
                    } else {
                        items.len()
                    };
                }
            });
            Ok(iter_result(arg0(&args), true))
        }
        // An iterator is its own iterable.
        "@@iterator" => Ok(recv.clone()),
        _ => Err(host::type_error(&format!(
            "iterator.{name} is not a function"
        ))),
    }
}

fn symbol_method(recv: &Value, name: &str, _args: Vec<Value>) -> Result<Value, String> {
    match name {
        "toString" => Ok(with_host(|h| {
            let s = h.str_of(recv);
            h.new_str(s)
        })),
        // 20.4.3.5: `Symbol.prototype[@@toPrimitive]` returns the symbol
        // itself for EVERY hint — it ignores its argument. That is what makes
        // `sym + ''` a TypeError rather than a concatenation: the conversion
        // succeeds and hands back a symbol, and it is `+` that then rejects it.
        "@@toPrimitive" | "valueOf" => Ok(recv.clone()),
        _ => Err(host::type_error(&format!(
            "symbol.{name} is not a function"
        ))),
    }
}

// ══ Object.* prototype helpers, `in`, deep clone ═════════════════════════════

fn object_create(args: Vec<Value>) -> Result<Value, String> {
    let proto = arg0(&args);
    // 20.1.2.2 step 1: the prototype must be an Object or exactly `null`.
    // `undefined` is NOT accepted — measured on node v26.7.0,
    // `Object.create(undefined)` is
    // `TypeError: Object prototype may only be an Object or null: undefined`,
    // where node-js quietly built a normal object.
    reject_bad_prototype(&proto)?;
    let obj = with_host(|h| h.new_object(IndexMap::new()));
    // `set_proto` records a null proto as an explicit null-prototype object.
    with_host(|h| h.set_proto(&obj, proto));
    // Optional second arg: a property-descriptor map.
    if let Some(descs) = args.get(1).filter(|d| !matches!(d, Value::Undef)) {
        let entries: Vec<(String, Value)> = with_host(|h| match h.get(descs) {
            Some(JsObj::Object(p)) => p.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
            _ => Vec::new(),
        });
        for (k, d) in entries {
            apply_descriptor(&obj, &k, &d)?;
        }
    }
    Ok(obj)
}

/// The enumerable method names of a builtin `<Ctor>.prototype` namespace that
/// supports being copied via `mixin`/`getOwnPropertyNames`. Currently only
/// `EventEmitter.prototype` (the one express mixes onto its app function).
/// The own property names of `<Ctor>.prototype`, and whether each is
/// enumerable, from the generated [`crate::arity::PROTO_MEMBERS`] table.
///
/// `Object.getOwnPropertyNames(Map.prototype)` answered `[]` for every
/// intrinsic — the members are reachable by NAME through the `@proto:` thunks
/// but were not enumerable, so feature detection that walks a prototype found
/// nothing there. The table is read from the reference engine rather than
/// derived from the arity table because the arity table holds functions only:
/// `Map.prototype.size`, `RegExp.prototype.source` and the twelve
/// `URL.prototype` components are accessors.
fn intrinsic_proto_members(ns: &str) -> Option<&'static [&'static str]> {
    let ctor = ns.strip_suffix(".prototype")?;
    crate::arity::PROTO_MEMBERS
        .binary_search_by(|(k, _)| (*k).cmp(ctor))
        .ok()
        .map(|i| crate::arity::PROTO_MEMBERS[i].1)
}

fn builtin_proto_method_names(ns: &str) -> Option<&'static [&'static str]> {
    match ns {
        "EventEmitter.prototype" => Some(crate::stdlib::events::METHODS),
        _ => None,
    }
}

/// The own SYMBOL-keyed property keys of `v` as symbol values. A Proxy's come
/// from its `ownKeys` trap (the symbol half of the same list the string keys are
/// filtered out of); every other receiver answers from its property map.
fn proxy_or_own_symbol_keys(v: &Value) -> Result<Vec<Value>, String> {
    if let Some(keys) = crate::proxy::own_keys(v)? {
        return Ok(keys
            .iter()
            .filter(|k| host::is_symbol_key(k))
            .map(|k| crate::proxy::key_value(k))
            .collect());
    }
    // An intrinsic prototype's symbol-keyed members come from the generated
    // table, which is the only record of them: they own no map entry, so
    // `Object.getOwnPropertySymbols(Array.prototype)` was `[]` where node
    // reports `Symbol.iterator` and `Symbol.unscopables`.
    if let Some(ns) = intrinsic_proto_of(v).map(|c| format!("{c}.prototype")) {
        if let Some(members) = intrinsic_proto_members(&ns) {
            return Ok(with_host(|h| {
                members
                    .iter()
                    .filter_map(|m| m.strip_prefix('+').unwrap_or(m).strip_prefix("@@"))
                    .map(|name| h.well_known_symbol(name))
                    .collect()
            }));
        }
    }
    Ok(with_host(|h| h.own_symbol_keys(v)))
}

/// `[[DefineOwnProperty]]` reachable from `crate::proxy`'s no-trap forward.
pub fn define_property_pub(obj: &Value, key: Value, desc: Value) -> Result<Value, String> {
    object_define_property(vec![obj.clone(), key, desc])
}

/// `[[GetOwnProperty]]` reachable from `crate::proxy`'s no-trap forward.
pub fn own_descriptor_pub(obj: &Value, key: Value) -> Result<Value, String> {
    object_get_own_descriptor(vec![obj.clone(), key])
}

fn object_define_property(args: Vec<Value>) -> Result<Value, String> {
    let obj = arg0(&args);
    // A Proxy defines through its `defineProperty` trap; the target it forwards
    // to is where the ordinary path below finally runs.
    if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
        let key = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
        let desc = args.get(2).cloned().unwrap_or(Value::Undef);
        if !with_host(|h| is_object_like(h, &desc)) {
            return Err(host::type_error(&format!(
                "Property description must be an object: {}",
                with_host(|h| h.str_of(&desc))
            )));
        }
        // `Object.defineProperty` THROWS on a refusing trap — in sloppy code
        // too. `Reflect.defineProperty` is the form that reports `false`.
        if !crate::proxy::define_property(&obj, &key, &desc)? {
            return Err(host::type_error(&format!(
                "'defineProperty' on proxy: trap returned falsish for property '{key}'"
            )));
        }
        return Ok(obj);
    }
    // 20.1.2.4 steps 1-3, both of which node-js skipped entirely: a non-object
    // target and a non-object descriptor each throw before anything is written.
    if !with_host(|h| is_object_like(h, &obj)) {
        return Err(host::type_error(
            "Object.defineProperty called on non-object",
        ));
    }
    let desc = args.get(2).cloned().unwrap_or(Value::Undef);
    if !with_host(|h| is_object_like(h, &desc)) {
        return Err(host::type_error(&format!(
            "Property description must be an object: {}",
            with_host(|h| h.str_of(&desc))
        )));
    }
    let key = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
    apply_descriptor(&obj, &key, &desc)?;
    Ok(obj)
}

/// Every `Reflect` method requires an OBJECT target and reports a `TypeError`
/// for anything else (28.1). A primitive was being accepted and silently
/// producing nothing.
/// `CreateListFromArrayLike` (7.3.18) — the argument list `Reflect.apply` and
/// `Reflect.construct` take.
///
/// An ARRAY-LIKE counts: `{length: 2, 0: 1, 1: 5}` is a two-element list. The
/// iterator was being used instead, so an array-like produced nothing and a
/// primitive produced nothing rather than the TypeError node raises.
/// Whether `p` is ALREADY `obj`'s prototype — the one case a non-extensible
/// object still accepts, because it changes nothing.
///
/// The observable prototype, not the stored link: an ordinary object has no
/// explicit link and inherits `Object.prototype`, so comparing the raw slot
/// reported "different" for `setPrototypeOf(frozen, Object.prototype)`.
/// Whether making `p` the prototype of `obj` would create a CYCLE — 10.1.2.1
/// step 8 walks up from `p` looking for `obj`.
///
/// Without the check `Object.setPrototypeOf(a, b)` followed by the reverse
/// built a ring. Nothing hung, because every chain walk in this host carries a
/// hop limit, but a lookup then silently gave up instead of finding a property
/// that really was there.
fn would_cycle(obj: &Value, p: &Value) -> bool {
    let mut cur = Some(p.clone());
    for _ in 0..1000 {
        let Some(c) = cur else { return false };
        if with_host(|h| h.strict_eq(&c, obj)) {
            return true;
        }
        // A PROXY's prototype is its handler's business; the spec skips the
        // walk entirely when one is in the chain.
        if with_host(|h| h.kind_of(&c)) == Some(ObjKind::Proxy) {
            return false;
        }
        cur = with_host(|h| h.proto_of(&c));
    }
    false
}

fn same_prototype(obj: &Value, p: &Value) -> bool {
    let cur = prototype_of(obj);
    with_host(|h| h.strict_eq(&cur, p) || (h.is_null(&cur) && h.is_null(p)))
}

fn create_list_from_array_like(v: &Value) -> Result<Vec<Value>, String> {
    if !with_host(|h| is_object_like(h, v)) {
        return Err(host::type_error(
            "CreateListFromArrayLike called on non-object",
        ));
    }
    let len = get_property(v, "length")?;
    let n = with_host(|h| h.to_number(&len));
    let n = if n.is_finite() && n > 0.0 {
        n as usize
    } else {
        0
    };
    (0..n).map(|i| get_property(v, &i.to_string())).collect()
}

fn reflect_require_object(v: &Value, method: &str) -> Result<(), String> {
    if with_host(|h| is_object_like(h, v)) {
        return Ok(());
    }
    Err(host::type_error(&format!(
        "Reflect.{method} called on non-object"
    )))
}

/// Whether `v` is an Object in the language sense — anything `typeof` calls
/// `"object"` (bar `null`) or `"function"`. Used by the argument checks that
/// distinguish "an object" from a primitive.
fn is_object_like(h: &host::JsHost, v: &Value) -> bool {
    matches!(v, Value::Obj(_)) && !h.is_null(v) && !host::is_primitive(h, v)
}

/// `RequireObjectCoercible(v)` — 7.2.1. The check in front of every `ToObject`,
/// which node-js was missing on the whole `Object.keys`/`values`/`entries`/
/// `getOwnPropertyNames`/`getOwnPropertySymbols`/`getOwnPropertyDescriptor`/
/// `assign` family: each returned an empty result for `null` where node v26.7.0
/// throws `TypeError: Cannot convert undefined or null to object`. A PRIMITIVE
/// is coercible and keeps working (`Object.keys(1)` is `[]`).
fn require_object_coercible(v: &Value) -> Result<(), String> {
    if with_host(|h| matches!(v, Value::Undef) || h.is_null(v)) {
        return Err(host::type_error(
            "Cannot convert undefined or null to object",
        ));
    }
    Ok(())
}

/// 10.1.2 / 20.1.2.2 step 1: reject a `[[Prototype]]` that is neither an Object
/// nor `null`, with V8's wording. Measured on node v26.7.0:
/// `Object.create("s")` is
/// `TypeError: Object prototype may only be an Object or null: s`.
fn reject_bad_prototype(proto: &Value) -> Result<(), String> {
    if with_host(|h| h.is_null(proto) || is_object_like(h, proto)) {
        return Ok(());
    }
    Err(host::type_error(&format!(
        "Object prototype may only be an Object or null: {}",
        with_host(|h| h.str_of(proto))
    )))
}

/// Apply a `{ value | get | set }` descriptor object to `obj[key]`.
///
/// Per ECMAScript `ToPropertyDescriptor`, an omitted `writable`/`enumerable`/
/// `configurable` field defaults to **false** — which is why a `defineProperty`
/// data property is invisible to `Object.keys` unless the caller opts in. That
/// asymmetry against plain assignment is the whole reason the attribute table
/// exists.
/// The requested fields of a property descriptor — 10.1.6.2
/// `ToPropertyDescriptor`. Each is `None` when the descriptor omits it, which
/// is the distinction the merge below turns on: an omitted field LEAVES an
/// existing attribute alone rather than resetting it.
struct Requested {
    value: Option<Value>,
    get: Option<Option<Value>>,
    set: Option<Option<Value>>,
    writable: Option<bool>,
    enumerable: Option<bool>,
    configurable: Option<bool>,
}

impl Requested {
    /// Reads through the prototype chain, as `ToPropertyDescriptor`'s
    /// `HasProperty`/`Get` pairs do — a descriptor built with
    /// `Object.create({ value: 1 })` is legal.
    fn read(desc: &Value) -> Self {
        let has = |k: &str| {
            with_host(|h| {
                host::lookup_chain(h, desc, k).is_some()
                    || host::lookup_accessor(h, desc, k).is_some()
            })
        };
        let val = |k: &str| get_property(desc, k).unwrap_or(Value::Undef);
        // Resolve the value BEFORE the borrow: `val` re-enters the host, and
        // doing it inside the `with_host` closure aborts on the double borrow.
        let flag = |k: &str| {
            has(k).then(|| {
                let v = val(k);
                with_host(|h| h.truthy(&v))
            })
        };
        Requested {
            value: has("value").then(|| val("value")),
            get: has("get").then(|| match val("get") {
                Value::Undef => None,
                g => Some(g),
            }),
            set: has("set").then(|| match val("set") {
                Value::Undef => None,
                st => Some(st),
            }),
            writable: flag("writable"),
            enumerable: flag("enumerable"),
            configurable: flag("configurable"),
        }
    }

    fn is_accessor(&self) -> bool {
        self.get.is_some() || self.set.is_some()
    }

    fn is_data(&self) -> bool {
        self.value.is_some() || self.writable.is_some()
    }
}

/// The own property already at `key`, if any, read back through
/// `Object.getOwnPropertyDescriptor` so every object kind (array indices, the
/// fn-prop side table, Buffer bytes) is covered by one code path.
struct Existing {
    accessor: bool,
    value: Value,
    get: Option<Value>,
    set: Option<Value>,
    writable: bool,
    enumerable: bool,
    configurable: bool,
}

fn existing_property(obj: &Value, key: &str) -> Option<Existing> {
    let k = with_host(|h| h.new_str(key.to_string()));
    let d = own_descriptor_pub(obj, k).ok()?;
    if matches!(d, Value::Undef) {
        return None;
    }
    let field = |n: &str| get_property(&d, n).unwrap_or(Value::Undef);
    let truthy = |n: &str| {
        let v = field(n);
        with_host(|h| h.truthy(&v))
    };
    let accessor = with_host(|h| host::lookup_chain(h, &d, "get").is_some());
    Some(Existing {
        accessor,
        value: field("value"),
        get: match field("get") {
            Value::Undef => None,
            g => Some(g),
        },
        set: match field("set") {
            Value::Undef => None,
            st => Some(st),
        },
        writable: truthy("writable"),
        enumerable: truthy("enumerable"),
        configurable: truthy("configurable"),
    })
}

/// SameValue (7.2.11) — `===` except that `NaN` equals itself and `+0` and
/// `-0` are distinct. 10.1.6.3 compares a redefined value against the current
/// one with this, not with strict equality.
pub(crate) fn same_value(a: &Value, b: &Value) -> bool {
    let num = |v: &Value| match v {
        Value::Int(n) => Some(*n as f64),
        Value::Float(f) => Some(*f),
        _ => None,
    };
    match (num(a), num(b)) {
        (Some(x), Some(y)) => {
            if x.is_nan() && y.is_nan() {
                true
            } else if x == 0.0 && y == 0.0 {
                x.is_sign_negative() == y.is_sign_negative()
            } else {
                x == y
            }
        }
        _ => with_host(|h| h.strict_eq(a, b)),
    }
}

/// 10.1.6.3 `ValidateAndApplyPropertyDescriptor`.
///
/// None of the validation existed: every `Object.defineProperty` was applied
/// unconditionally, so redefining a non-configurable property silently
/// succeeded where node throws. Worse in practice, an OMITTED field was read as
/// `false` rather than "leave alone", so the ordinary
/// `Object.defineProperty(o, 'k', { enumerable: false })` also stripped
/// `writable` and `configurable` from a property that had both.
///
/// Converting an accessor to a data property did not take effect at all: the
/// value was written but the accessor stayed in its side table, and accessors
/// win on read, so the getter kept answering.
fn apply_descriptor(obj: &Value, key: &str, desc: &Value) -> Result<(), String> {
    let req = Requested::read(desc);
    let cur = existing_property(obj, key);

    // An array's `length` is the exotic own property whose write resizes the
    // array (10.4.2.1); routing it through the ordinary path stored a shadowing
    // key and left the elements untouched.
    if key == "length" && with_host(|h| h.kind_of(obj)) == Some(ObjKind::Array) {
        if let Some(v) = req.value.clone() {
            return set_property_pub(obj, "length", v);
        }
    }

    // The other exotics whose own properties are SYNTHESIZED rather than stored
    // in a property map: a typed array's elements and a RegExp's `lastIndex`.
    // The ordinary path below writes a shadowing map entry the read never
    // consults, so `Object.defineProperty(u8, '0', {value: 9})` left `u8[0]`
    // unchanged.
    // A builtin namespace/prototype has no property map either, so a data
    // descriptor has to reach the same side table an assignment does.
    // `Object.defineProperty(Array.prototype, 'at', {value: impl})` — how a
    // careful polyfill installs itself, precisely to avoid the enumerable
    // property a bare assignment creates — wrote a map entry nothing read.
    if with_host(|h| h.kind_of(obj)) == Some(ObjKind::Builtin) {
        if let Some(v) = req.value.clone() {
            return set_property_pub(obj, key, v);
        }
    }
    let exotic_own = (crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray")
        && key.parse::<usize>().is_ok())
        || (key == "lastIndex" && with_host(|h| matches!(h.get(obj), Some(JsObj::RegExp(_)))));
    if exotic_own {
        if let Some(v) = req.value.clone() {
            return set_property_pub(obj, key, v);
        }
    }

    // 10.1.6.3 step 2: a NEW property cannot be added to a non-extensible
    // object. Only an existing property's attributes were being validated, so
    // `defineProperty(Object.freeze({}), 'z', …)` silently added one.
    if cur.is_none() && !with_host(|h| h.is_extensible(obj)) {
        return Err(host::type_error(&format!(
            "Cannot define property {key}, object is not extensible"
        )));
    }
    if let Some(c) = &cur {
        if !c.configurable {
            let rejected = req.configurable == Some(true)
                || req.enumerable.is_some_and(|e| e != c.enumerable)
                || (req.is_accessor() && !c.accessor)
                || (req.is_data() && c.accessor)
                || (c.accessor
                    && ((req.get.is_some() && req.get.clone().flatten() != c.get)
                        || (req.set.is_some() && req.set.clone().flatten() != c.set)))
                || (!c.accessor
                    && !c.writable
                    && (req.writable == Some(true)
                        || req.value.as_ref().is_some_and(|v| !same_value(v, &c.value))));
            if rejected {
                return Err(host::type_error(&format!(
                    "Cannot redefine property: {key}"
                )));
            }
        }
    }

    // An omitted field keeps what the property already had; a brand-new
    // property defaults every one of them to false.
    let attrs = host::PropAttrs {
        writable: req
            .writable
            .unwrap_or(cur.as_ref().is_some_and(|c| c.writable)),
        enumerable: req
            .enumerable
            .unwrap_or(cur.as_ref().is_some_and(|c| c.enumerable)),
        configurable: req
            .configurable
            .unwrap_or(cur.as_ref().is_some_and(|c| c.configurable)),
    };
    with_host(|h| h.set_prop_attrs(obj, key, attrs));

    if req.is_accessor() {
        let get = req
            .get
            .clone()
            .unwrap_or_else(|| cur.as_ref().and_then(|c| c.get.clone()));
        let set = req
            .set
            .clone()
            .unwrap_or_else(|| cur.as_ref().and_then(|c| c.set.clone()));
        // An ACCESSOR at an index past the end still extends the array
        // (10.4.2.1): `Object.defineProperty([1], '4', {get})` gives
        // `length === 5` with holes between. Only the DATA path grew it, so
        // the accessor landed in the side table while `length` stayed put —
        // and with it out of range, `Object.keys` and `JSON.stringify` never
        // saw the index at all.
        if let (Some(ObjKind::Array), Ok(i)) = (with_host(|h| h.kind_of(obj)), key.parse::<usize>())
        {
            with_host(|h| {
                let old_len = match h.get(obj) {
                    Some(JsObj::Array(items)) => items.len(),
                    _ => 0,
                };
                if i >= old_len {
                    if let Some(JsObj::Array(items)) = h.get_mut(obj) {
                        items.resize(i + 1, Value::Undef);
                    }
                    h.mark_hole_range(obj, old_len..i + 1);
                }
            });
        }
        with_host(|h| h.set_accessor(obj, key, get, set));
        return Ok(());
    }

    if let Some(c) = &cur {
        if c.accessor {
            if !req.is_data() {
                // A generic descriptor — flags only — leaves an accessor an
                // accessor. They were already applied above.
                return Ok(());
            }
            let v = req.value.clone().unwrap_or(Value::Undef);
            with_host(|h| h.accessor_to_data(obj, key, v));
            return Ok(());
        }
    }

    let Some(v) = req.value else {
        // Nothing to write: a flags-only redefinition of a data property.
        return Ok(());
    };
    write_data_slot(obj, key, v);
    Ok(())
}

/// Store `v` as an own data property, in whichever slot the object kind keeps
/// its own properties.
fn write_data_slot(obj: &Value, key: &str, v: Value) {
    // A function/class receiver stores its own props in the fn-prop side table
    // (express `mixin(app, proto)` defines methods onto the `app` *function*).
    if matches!(
        with_host(|h| h.get(obj).cloned()),
        Some(JsObj::Func(_)) | Some(JsObj::Class(_))
    ) || uses_side_table(obj)
    {
        with_host(|h| h.set_fn_prop(obj, key, v));
        return;
    }
    if let (Some(ObjKind::Array), Ok(i)) = (with_host(|h| h.kind_of(obj)), key.parse::<usize>()) {
        // An array's index keys ARE its elements, and defining one past the end
        // grows the array with holes in between (10.4.2.1). This whole branch
        // used to be missing: `Object.defineProperty(arr, 1, {value})` wrote
        // into the ordinary property map an array does not have, so it was a
        // silent no-op.
        with_host(|h| {
            let old = match h.get(obj) {
                Some(JsObj::Array(items)) => items.len(),
                _ => 0,
            };
            if let Some(JsObj::Array(items)) = h.get_mut(obj) {
                if i >= old {
                    items.resize(i + 1, Value::Undef);
                }
                items[i] = v;
            }
            if i > old {
                h.mark_hole_range(obj, old..i);
            }
            h.clear_hole(obj, i);
        });
        return;
    }
    with_host(|h| {
        if let Some(JsObj::Object(p)) = h.get_mut(obj) {
            p.insert(key.to_string(), v);
            host::canonicalize_own_keys(p);
        }
    });
}

/// `Object.defineProperties(obj, descriptorMap)`.
fn object_define_properties(args: Vec<Value>) -> Result<Value, String> {
    let obj = arg0(&args);
    let descs = args.get(1).cloned().unwrap_or(Value::Undef);
    let entries: Vec<(String, Value)> = with_host(|h| match h.get(&descs) {
        Some(JsObj::Object(p)) => p.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
        _ => Vec::new(),
    });
    for (k, d) in entries {
        apply_descriptor(&obj, &k, &d)?;
    }
    Ok(obj)
}

/// The descriptor of an own property a function, a typed array or a RegExp
/// SYNTHESIZES rather than keeping in a property map.
///
/// These read back through the ordinary path but owned no descriptor and did
/// not appear under `hasOwnProperty` or `getOwnPropertyNames`, so the five
/// views of "does this property exist" disagreed — a read said yes while
/// `Object.getOwnPropertyDescriptor(f, 'name')` said no such property, which is
/// what a shim checks before patching.
fn synthesized_own_descriptor(obj: &Value, key: &str) -> Option<(Value, host::PropAttrs)> {
    let ro_configurable = host::PropAttrs {
        writable: false,
        enumerable: false,
        configurable: true,
    };
    // A callable's `length`/`name` are read-only but configurable; its
    // `prototype` is writable and NOT configurable, and a class's is neither.
    // An arrow, a method and a bound function own no `prototype` at all.
    if with_host(|h| host::is_callable(h, obj)) && !matches!(key, "length" | "name" | "prototype") {
        return None;
    }
    if with_host(|h| host::is_callable(h, obj)) {
        if key == "prototype" {
            let p = get_property(obj, "prototype").ok()?;
            if matches!(p, Value::Undef) {
                return None;
            }
            return Some((
                p,
                host::PropAttrs {
                    writable: with_host(|h| h.kind_of(obj)) != Some(ObjKind::Class),
                    enumerable: false,
                    configurable: false,
                },
            ));
        }
        return Some((get_property(obj, key).ok()?, ro_configurable));
    }
    // A typed array's elements are own, enumerable, writable, configurable
    // properties; an index past the end owns nothing.
    if crate::stdlib::native_tag(obj).as_deref() == Some("TypedArray") {
        let v = crate::stdlib::typedarray::elem_get(obj, key)?;
        return Some((
            v,
            host::PropAttrs {
                writable: true,
                enumerable: true,
                configurable: true,
            },
        ));
    }
    // A RegExp's `lastIndex` is its own, writable, non-configurable cursor.
    if with_host(|h| matches!(h.get(obj), Some(JsObj::RegExp(_)))) && key == "lastIndex" {
        return Some((
            get_property(obj, "lastIndex").ok()?,
            host::PropAttrs {
                writable: true,
                enumerable: false,
                configurable: false,
            },
        ));
    }
    None
}

fn object_get_own_descriptor(args: Vec<Value>) -> Result<Value, String> {
    let obj = arg0(&args);
    require_object_coercible(&obj)?;
    let key = host::to_property_key(&args.get(1).cloned().unwrap_or(Value::Undef))?;
    // A string primitive's boxed own properties: each code-unit index is an
    // enumerable, non-writable, non-configurable data property, and `length` is
    // the same minus enumerable.
    if let Some(units) = string_primitive_units(&obj) {
        let entry = match key.parse::<usize>() {
            Ok(i) => units
                .get(i)
                .map(|c| (with_host(|h| h.new_str(c.clone())), true)),
            Err(_) if key == "length" => Some((Value::Float(units.len() as f64), false)),
            Err(_) => None,
        };
        return Ok(match entry {
            Some((value, enumerable)) => with_host(|h| {
                let mut m: IndexMap<String, Value> = IndexMap::new();
                m.insert("value".into(), value);
                m.insert("writable".into(), Value::Bool(false));
                m.insert("enumerable".into(), Value::Bool(enumerable));
                m.insert("configurable".into(), Value::Bool(false));
                h.new_object(m)
            }),
            None => Value::Undef,
        });
    }
    if with_host(|h| h.kind_of(&obj)) == Some(ObjKind::Proxy) {
        return Ok(crate::proxy::get_own_descriptor(&obj, &key)?.unwrap_or(Value::Undef));
    }
    // A method read off an enumerable builtin prototype (`EventEmitter.prototype`)
    // yields a `{ value: <method thunk> }` data descriptor so `mixin` can copy it.
    if let Some(JsObj::Builtin(ns)) = with_host(|h| h.get(&obj).cloned()) {
        if let Some(names) = builtin_proto_method_names(&ns) {
            if names.contains(&key.as_str()) {
                return Ok(with_host(|h| {
                    let thunk = h.alloc(JsObj::Builtin(format!(
                        "@proto:{}:{key}",
                        ns.trim_end_matches(".prototype")
                    )));
                    let mut m: IndexMap<String, Value> = IndexMap::new();
                    m.insert("value".into(), thunk);
                    m.insert("writable".into(), Value::Bool(true));
                    m.insert("enumerable".into(), Value::Bool(true));
                    m.insert("configurable".into(), Value::Bool(true));
                    h.new_object(m)
                }));
            }
        }
    }
    // A global the object does not own outright is still an own property of the
    // global object — the same lazy binding the bare identifier resolves to.
    // Every one of them reported `undefined`, so a feature probe written as
    // `getOwnPropertyDescriptor(globalThis, 'structuredClone')` concluded the
    // global was absent. The immutable trio (11.1.1 / 19.1.1-3) is frozen; the
    // rest are ordinary writable, non-enumerable, configurable bindings.
    if with_host(|h| h.is_global_object(&obj)) {
        let owned = with_host(|h| match h.get(&obj) {
            Some(JsObj::Object(p)) => p.contains_key(&key),
            _ => false,
        });
        if !owned && !CJS_WRAPPER_LOCALS.contains(&key.as_str()) {
            // A global a SCRIPT created — `x = 1` with no declaration — is an
            // ordinary enumerable property, unlike the builtins.
            let script_made = with_host(|h| h.read_global(&key).is_some());
            if let Some(v) = global_object_binding(&key) {
                let frozen = matches!(key.as_str(), "undefined" | "NaN" | "Infinity");
                return Ok(with_host(|h| {
                    let mut m: IndexMap<String, Value> = IndexMap::new();
                    m.insert("value".into(), v);
                    m.insert("writable".into(), Value::Bool(!frozen));
                    m.insert(
                        "enumerable".into(),
                        Value::Bool(script_made || ENUMERABLE_GLOBALS.contains(&key.as_str())),
                    );
                    m.insert("configurable".into(), Value::Bool(!frozen));
                    h.new_object(m)
                }));
            }
        }
    }
    // Any other member of a builtin namespace (`Math.PI`, `Math.floor`,
    // `Array.prototype.slice`, a builtin function's own `name`/`length`). Every
    // one of these reads back a value, but none owned a DESCRIPTOR:
    // `Object.getOwnPropertyDescriptor(Math, 'PI')` was `undefined`, which reads
    // as "no such property" to the shim/polyfill family that probes a namespace
    // before patching it.
    // An ACCESSOR member describes itself with a `get`, never a `value` — and
    // it must do so without READING the property, since running the getter
    // against the prototype is exactly what throws. Both prototype
    // representations are covered, so `Symbol.prototype.description` and
    // `Map.prototype.size` answer alike; both were `undefined`, which reads as
    // "no such property" to anything that probes before patching.
    if let Some(ctor) = intrinsic_proto_of(&obj) {
        if is_proto_accessor(&ctor, &key) {
            let getter = proto_getter(&ctor, &key);
            // The poison pair is the only ECMAScript accessor here with a
            // SETTER, but a WebIDL class has plenty: `URL.prototype.href`,
            // `hostname` and the rest are all writable, and reporting them as
            // read-only made `Object.getOwnPropertyDescriptor(URL.prototype,
            // 'href').set` read `undefined` for a setter that runs.
            let writable = (ctor == "Function" && matches!(key.as_str(), "arguments" | "caller"))
                || crate::stdlib::instance_accessors(&ctor)
                    .0
                    .iter()
                    .any(|(k, settable)| *k == key && *settable);
            let setter = writable
                .then(|| with_host(|h| h.alloc(JsObj::Builtin(format!("@protoset:{ctor}:{key}")))));
            return Ok(with_host(|h| {
                let mut m: IndexMap<String, Value> = IndexMap::new();
                m.insert("get".into(), getter);
                // `undefined`, not null: a read-only accessor has no setter at
                // all, and `JSON.stringify` of the descriptor must drop the key
                // rather than report `"set": null`.
                m.insert("set".into(), setter.unwrap_or(Value::Undef));
                m.insert("enumerable".into(), Value::Bool(is_webidl_proto(&ctor)));
                m.insert("configurable".into(), Value::Bool(true));
                h.new_object(m)
            }));
        }
    }
    if let Some(ns) = with_host(|h| match h.get(&obj) {
        Some(JsObj::Builtin(ns)) => Some(ns.clone()),
        _ => None,
    }) {
        let value = namespace_property(&ns, &key);
        if !matches!(value, Value::Undef) {
            return Ok(builtin_member_descriptor(&ns, &key, value));
        }
    }
    if let Some((value, attrs)) = synthesized_own_descriptor(&obj, &key) {
        return Ok(with_host(|h| {
            let mut m: IndexMap<String, Value> = IndexMap::new();
            m.insert("value".into(), value);
            m.insert("writable".into(), Value::Bool(attrs.writable));
            m.insert("enumerable".into(), Value::Bool(attrs.enumerable));
            m.insert("configurable".into(), Value::Bool(attrs.configurable));
            h.new_object(m)
        }));
    }
    // Accessor descriptor?
    if let Some((get, set)) = with_host(|h| h.own_accessor(&obj, &key)) {
        return Ok(with_host(|h| {
            let a = h.prop_attrs(&obj, &key);
            let mut m: IndexMap<String, Value> = IndexMap::new();
            m.insert("get".into(), get.unwrap_or(Value::Undef));
            m.insert("set".into(), set.unwrap_or(Value::Undef));
            m.insert("enumerable".into(), Value::Bool(a.enumerable));
            m.insert("configurable".into(), Value::Bool(a.configurable));
            h.new_object(m)
        }));
    }
    let val = with_host(|h| match h.get(&obj) {
        // A Buffer's own properties are exactly its byte indices, read out of the
        // hidden `@@bytes` slot; `length`/`byteLength` are internal bookkeeping
        // that V8 keeps on the prototype, so they own no descriptor.
        Some(JsObj::Object(p))
            if p.get("@@native").map(|t| h.str_of(t)).as_deref() == Some("Buffer") =>
        {
            match (
                p.get("@@bytes").and_then(|b| h.get(b)),
                key.parse::<usize>(),
            ) {
                (Some(JsObj::Array(items)), Ok(i)) => items.get(i).cloned(),
                _ => None,
            }
        }
        Some(JsObj::Object(p)) => p.get(&key).cloned(),
        // An array's index keys read the elements; `length` is the exotic own
        // property; anything else is an ordinary own key in the side table.
        Some(JsObj::Array(items)) => match key.parse::<usize>() {
            // An ELIDED index owns no property at all, so it has no descriptor.
            Ok(i) if h.is_hole(&obj, i) => None,
            Ok(i) => items.get(i).cloned(),
            Err(_) if key == "length" => Some(Value::Float(items.len() as f64)),
            Err(_) => h.fn_prop(&obj, &key),
        },
        // A function/class own prop lives in the fn-prop side table.
        Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => h.fn_prop(&obj, &key),
        _ => None,
    });
    match val {
        Some(v) => Ok(with_host(|h| {
            let a = h.prop_attrs(&obj, &key);
            let mut m: IndexMap<String, Value> = IndexMap::new();
            m.insert("value".into(), v);
            m.insert("writable".into(), Value::Bool(a.writable));
            m.insert("enumerable".into(), Value::Bool(a.enumerable));
            m.insert("configurable".into(), Value::Bool(a.configurable));
            h.new_object(m)
        })),
        None => Ok(Value::Undef),
    }
}

/// `Object.getOwnPropertyDescriptors(obj)` — the descriptor of every own string
/// key, keyed by name. `Object.create(proto, getOwnPropertyDescriptors(src))` is
/// the standard "clone with accessors intact" idiom, so this must agree
/// key-for-key with `getOwnPropertyNames`.
fn object_get_own_descriptors(args: Vec<Value>) -> Result<Value, String> {
    let obj = arg0(&args);
    let names = object_keys(vec![obj.clone()], 3)?;
    let keys: Vec<String> = with_host(|h| match h.get(&names) {
        Some(JsObj::Array(items)) => items.iter().map(|k| h.str_of(k)).collect(),
        _ => Vec::new(),
    });
    let mut out: IndexMap<String, Value> = IndexMap::new();
    for k in keys {
        let ks = with_host(|h| h.new_str(k.clone()));
        let d = object_get_own_descriptor(vec![obj.clone(), ks])?;
        if !matches!(d, Value::Undef) {
            out.insert(k, d);
        }
    }
    Ok(with_host(|h| h.new_object(out)))
}

/// `key in obj` respecting the prototype chain. Reports a `Result` because a
/// Proxy's `has` trap is user code and may throw.
pub fn has_property(obj: &Value, key: &str) -> Result<bool, String> {
    if let Some(b) = crate::proxy::has(obj, key)? {
        return Ok(b);
    }
    Ok(has_property_ordinary(obj, key))
}

/// `[[HasProperty]]` for every non-Proxy receiver.
fn has_property_ordinary(obj: &Value, key: &str) -> bool {
    // `key in globalThis`: membership matches what the READ answers, which for
    // the global object includes every lazily-bound builtin and every global a
    // script created. `'Math' in globalThis` and `'x' in globalThis` after
    // `x = 1` both answered FALSE while `globalThis.Math` and `globalThis.x`
    // read back fine.
    if with_host(|h| h.is_global_object(obj))
        && !CJS_WRAPPER_LOCALS.contains(&key)
        && global_object_binding(key).is_some()
    {
        return true;
    }
    // `key in <builtin namespace/prototype>`: membership matches what a property
    // read would yield. `String.prototype.indexOf` (and the rest of the builtin
    // prototype methods) resolve as callable thunks via `namespace_property`, so
    // `'indexOf' in String.prototype` must report true (get-intrinsic probes this
    // with the `in` operator before reading the intrinsic).
    if let Some(JsObj::Builtin(ns)) = with_host(|h| h.get(obj).cloned()) {
        return !matches!(namespace_property(&ns, key), Value::Undef);
    }
    // An integer index of a typed array / Buffer is an own property, and lives
    // in the hidden element array rather than the property map — the same
    // question `hasOwnProperty` answers, through the same helper. Only a hit
    // short-circuits: a non-index key like `'length'` must still fall through
    // to the ordinary chain lookup below.
    if crate::stdlib::typedarray::has_index(obj, key) == Some(true) {
        return true;
    }
    if with_host(|h| host::lookup_chain(h, obj, key)).is_some() {
        return true;
    }
    if with_host(|h| host::lookup_accessor(h, obj, key)).is_some() {
        return true;
    }
    // A member patched onto the receiver's intrinsic prototype. The READ
    // resolves it, so without this `Array.prototype.at = f` made `[].at` a
    // function while `'at' in []` stayed false.
    if !key.starts_with('#') && inherited_builtin_static(obj, key).is_some() {
        return true;
    }
    if with_host(|h| match h.get(obj) {
        Some(JsObj::Object(p)) => p.contains_key(key),
        Some(JsObj::Array(items)) => {
            key == "length"
                || key
                    .parse::<usize>()
                    .map(|i| i < items.len() && !h.is_hole(obj, i))
                    .unwrap_or(false)
                // A non-index own property (`arr.foo`, `arr[sym]`) lives in the
                // side table, and `in` must see it.
                || h.fn_prop(obj, key).is_some()
        }
        Some(JsObj::Func(_)) | Some(JsObj::Class(_)) => h.fn_prop(obj, key).is_some(),
        // A RegExp's `lastIndex` is an OWN property in node. Here it lives in
        // the `RegExpObj` struct rather than a property map, so nothing above
        // can see it.
        Some(JsObj::RegExp(_)) => key == "lastIndex" || h.fn_prop(obj, key).is_some(),
        _ => false,
    }) {
        return true;
    }
    // An INHERITED builtin prototype method. These are not objects on the
    // prototype chain — they are synthesized by the read path from the
    // intrinsic table — so neither `lookup_chain` nor the property map above
    // can see them, and `'toString' in {}`, `'push' in []` and `'then' in
    // Promise.resolve()` all answered false. That last one is the standard
    // thenable test, so the `in` operator disagreed with what a read gives for
    // every builtin method of every builtin kind.
    inherited_builtin_method(obj, key)
}

/// Whether a READ of `key` on `obj` would resolve to an inherited builtin
/// prototype method. Asked by `in` and `hasOwnProperty`'s negative case; it
/// performs no read, so a getter cannot fire.
/// A property a script MONKEY-PATCHED onto the intrinsic prototype `obj`
/// inherits from (`Array.prototype.at = impl`, `Object.prototype.foo = 1`), or
/// `None`.
///
/// The intrinsic prototypes are namespace handles rather than real objects on
/// the chain, so an assignment onto one lands in `builtin_statics` and no
/// ordinary chain walk can see it. This is the read side: the receiver's own
/// constructor's prototype first, then `Object.prototype`, mirroring
/// `inherited_method_owner`'s two-step.
pub(crate) fn inherited_builtin_static(obj: &Value, key: &str) -> Option<Value> {
    if with_host(|h| h.has_null_proto(obj)) {
        return None;
    }
    let ctor = match wrapped_primitive(obj).as_ref().and_then(wrapper_ctor_of) {
        Some(c) => Some(c),
        None if is_arguments(obj) => Some("Object"),
        None => with_host(|h| default_ctor_name(h, obj)),
    };
    // Only the side table is consulted, never the real prototype OBJECT's map:
    // `String.prototype` and friends are materialized with their intrinsic
    // members present, so reading their maps here would re-route every ordinary
    // `"a".toString()` through this path — which recursed until the stack blew.
    // `set_property` mirrors a write onto a real intrinsic prototype INTO this
    // table precisely so the read side can stay this narrow.
    let on = |c: &str| with_host(|h| h.builtin_static(&format!("{c}.prototype"), key));
    let found = ctor.and_then(on).or_else(|| on("Object"))?;
    // Restoring a saved intrinsic (`const orig = Array.prototype.join; …;
    // Array.prototype.join = orig`) stores the SYNTHESIZED thunk for this very
    // name back into the table. Dispatching to it would re-enter this lookup
    // and recurse until the stack blew, so a thunk that is already this key's
    // own intrinsic reports nothing and the ordinary builtin path answers.
    let self_thunk = with_host(
        |h| matches!(h.get(&found), Some(JsObj::Builtin(s)) if s.starts_with("@proto:") && s.ends_with(&format!(":{key}"))),
    );
    (!self_thunk).then_some(found)
}

/// Whether `recv` carries `key` as an OWN property — the guard on
/// [`inherited_builtin_static`], since an own property shadows anything
/// patched onto a prototype.
fn has_own_for_shadow(recv: &Value, key: &str) -> bool {
    with_host(|h| {
        if h.fn_prop(recv, key).is_some() || h.own_accessor(recv, key).is_some() {
            return true;
        }
        match h.get(recv) {
            Some(JsObj::Object(p)) => p.contains_key(key),
            // An ELIDED index owns nothing — the whole point of a hole is that
            // the lookup continues up the chain — so it must not count as a
            // shadow here or an inherited value at that index stays invisible.
            Some(JsObj::Array(items)) => {
                key == "length" || {
                    key.parse::<usize>()
                        .is_ok_and(|i| i < items.len() && !h.is_hole(recv, i))
                }
            }
            _ => false,
        }
    })
}

fn inherited_builtin_method(obj: &Value, key: &str) -> bool {
    if with_host(|h| h.has_null_proto(obj)) {
        return false;
    }
    if let Some(tag) = crate::stdlib::native_tag(obj) {
        if crate::stdlib::instance_has_method(&tag, key) {
            return true;
        }
    }
    inherited_method_owner(obj, key).is_some()
}

/// Whether `recv`'s intrinsic prototype is still on its chain — that is,
/// whether `Array.prototype`'s methods are still reachable from an array.
///
/// A builtin's methods are synthesized from the receiver's KIND rather than
/// found on a chain, so replacing the prototype could not take them away:
/// `Object.setPrototypeOf(a, {})` left `a.join` a function where node reports
/// `undefined`, and `Object.setPrototypeOf(a, null)` did too. The exotic
/// storage is unaffected either way — `Array.isArray`, `a.length` and `a[0]`
/// all still answer, as they do in node.
///
/// The overwhelmingly common case is the DEFAULT link, which is recorded as no
/// link at all, so this answers true after one map probe and allocates nothing.
pub(crate) fn own_intrinsic_reachable_pub(recv: &Value) -> bool {
    own_intrinsic_reachable(recv)
}

fn own_intrinsic_reachable(recv: &Value) -> bool {
    // A BOXED primitive needs no special case here: its methods resolve through
    // `inherited_method_owner`, which applies the wrapper rule itself.
    with_host(|h| default_ctor_name(h, recv)).map_or(true, |c| intrinsic_reachable(recv, c))
}

/// Whether the intrinsic prototype for `ctor` is still on `recv`'s chain.
fn intrinsic_reachable(recv: &Value, ctor: &str) -> bool {
    let own = Some(ctor);
    let mut cur = recv.clone();
    for _ in 0..100 {
        let explicit = with_host(|h| h.proto_of(&cur));
        let Some(p) = explicit else {
            // No explicit link: the implicit prototype is this object's own
            // kind's, which is what `recv` is asking about only while `cur` is
            // still `recv` itself.
            if with_host(|h| h.has_null_proto(&cur)) {
                return false;
            }
            let implicit = with_host(|h| default_ctor_name(h, &cur));
            // Every implicit prototype chain ends at `Object.prototype`, so a
            // question about `Object` is answered yes by any of them.
            return implicit == own || ctor == "Object";
        };
        if with_host(|h| h.is_null(&p)) {
            return false;
        }
        let hit = with_host(|h| {
            own.is_some_and(|c| {
                matches!(h.get(&p), Some(JsObj::Builtin(ns)) if *ns == format!("{c}.prototype"))
                    || h.intrinsic_proto_ctor(&p) == Some(c)
                    || (c == "Object" && h.object_proto() == p)
            })
        });
        if hit {
            return true;
        }
        // A CLASS prototype object is not linked to the builtin its class
        // extends — the `extends` relationship is recorded on the class value —
        // so the walk has to cross over there or `class D extends Array {}` ends
        // it, and every inherited method of every subclass instance vanishes.
        if let Some(builtin) = with_host(|h| {
            h.class_owning_proto(&p)
                .and_then(|c| h.class_builtin_ancestor(&c))
                .map(|b| h.callable_name(&b))
        }) {
            if own == Some(builtin.as_str()) || ctor == "Object" {
                return true;
            }
        }
        cur = p;
    }
    false
}

/// The intrinsic prototypes actually ON `recv`'s explicit chain, nearest first
/// — the complement of [`intrinsic_reachable`], which asks about one known
/// constructor.
///
/// `Object.create(Array.prototype)` is an ordinary object whose chain reaches
/// `Array.prototype`, and node resolves the whole of `Array.prototype` through
/// it: `o.push(1)` works, because those methods are generic over their receiver
/// (which is also why `Array.prototype.push.call({length: 0}, 1)` already
/// worked here). Deciding the owner from the receiver's KIND alone made every
/// one of them `undefined` — the same "methods come from the kind, not the
/// chain" mistake as the detachment case, in the opposite direction.
pub(crate) fn chain_intrinsic_ctors_pub(recv: &Value) -> Vec<&'static str> {
    chain_intrinsic_ctors(recv)
}

fn chain_intrinsic_ctors(recv: &Value) -> Vec<&'static str> {
    with_host(|h| chain_intrinsic_ctors_h(h, recv))
}

/// [`chain_intrinsic_ctors`] against an already-held host borrow, for the
/// callers that are inside one — `can_write_prop` takes `&JsHost`, so going
/// back through `with_host` there aborts the process on a double borrow.
pub(crate) fn chain_intrinsic_ctors_h(h: &host::JsHost, recv: &Value) -> Vec<&'static str> {
    let mut out: Vec<&'static str> = Vec::new();
    let mut cur = recv.clone();
    for _ in 0..100 {
        let Some(p) = h.proto_of(&cur) else {
            break;
        };
        if h.is_null(&p) {
            break;
        }
        let name = match h.get(&p) {
            Some(JsObj::Builtin(ns)) => ns.strip_suffix(".prototype").map(str::to_string),
            _ => h.intrinsic_proto_ctor(&p).map(str::to_string),
        };
        if let Some(n) = name {
            if let Some(c) = crate::arity::PROTO_MEMBERS
                .iter()
                .map(|(k, _)| *k)
                .find(|k| *k == n)
            {
                if !out.contains(&c) {
                    out.push(c);
                }
            }
        }
        cur = p;
    }
    out
}

/// The constructor whose prototype defines `key` for `obj` — its own if that
/// prototype has it, otherwise `Object` — or `None` when neither does.
///
/// Used both by `in` and by the READ, so the two cannot disagree about which
/// prototype a name comes from. `new Map().toString` is `Map.prototype`'s and
/// `new Map().hasOwnProperty` is `Object.prototype`'s.
pub(crate) fn inherited_method_owner_pub(obj: &Value, key: &str) -> Option<&'static str> {
    inherited_method_owner(obj, key)
}

fn inherited_method_owner(obj: &Value, key: &str) -> Option<&'static str> {
    if with_host(|h| h.has_null_proto(obj)) {
        return None;
    }
    // The generated prototype-member table, which unlike the arity table knows
    // about the ACCESSORS — `size` on a Map, `source` on a RegExp, `description`
    // on a Symbol are members but not functions — and about `constructor`.
    // A BOXED primitive reports its wrapper's constructor, not `Object` —
    // `'description' in Object(Symbol())` is true. The box is an ordinary
    // object carrying the primitive in a slot, so the ctor comes from what it
    // holds rather than from the box itself.
    let ctor = match wrapped_primitive(obj).as_ref().and_then(wrapper_ctor_of) {
        Some(c) => Some(c),
        // An `arguments` object is ARRAY-BACKED here so that indices, `length`,
        // spread and `for-of` work, but node's is an exotic that inherits from
        // `Object.prototype` — `typeof arguments.map` is `undefined`. Reporting
        // its backing kind would hand it the whole `Array.prototype`.
        None if is_arguments(obj) => Some("Object"),
        None => with_host(|h| default_ctor_name(h, obj)),
    };
    let on_proto = |c: &str| {
        crate::arity::PROTO_MEMBERS
            .binary_search_by(|(k, _)| (*k).cmp(c))
            .ok()
            .is_some_and(|i| {
                crate::arity::PROTO_MEMBERS[i]
                    .1
                    .iter()
                    .any(|m| m.strip_prefix('+').unwrap_or(m) == key)
            })
    };
    // `PROTO_MEMBERS` is generated from the prototypes' STRING keys, so a
    // well-known symbol member is absent from it. For an object whose CHAIN
    // reaches an intrinsic prototype the intrinsic table has to be consulted as
    // well, or `[...Object.create(Array.prototype)]` finds no `Symbol.iterator`
    // at all. It is deliberately NOT consulted for the receiver's own kind:
    // there a thunk would be minted for every `@@` member the table names,
    // including ones whose dispatch has no implementation for that receiver,
    // and `[...buffer]` then failed with `@@iterator is not a function`.
    //
    // It is narrowed further to an ORDINARY object: a natively-tagged receiver
    // (a typed array, a Buffer) is linked to a real intrinsic prototype too,
    // and minting a thunk there produced `@@iterator is not a function` for
    // `[...new Uint8Array(ab)]` — those kinds reach their iterator by their own
    // fast path, which the table entry would shadow.
    let plain = with_host(|h| h.kind_of(obj)) == Some(ObjKind::Object)
        && crate::stdlib::native_tag(obj).is_none();
    let on_proto_or_symbol =
        |c: &str| on_proto(c) || (plain && builtin_meta(&format!("@proto:{c}:{key}")).is_some());
    // Each candidate is only an answer while ITS prototype is still on the
    // receiver's chain. The two are asked separately: replacing an array's
    // prototype with a plain object takes `Array.prototype`'s methods away and
    // leaves `Object.prototype`'s, since the replacement inherits from it.
    if let Some(c) = ctor.filter(|c| on_proto(c) && intrinsic_reachable(obj, c)) {
        return Some(c);
    }
    // An intrinsic prototype the receiver's chain passes THROUGH, which its own
    // kind does not account for.
    if let Some(c) = chain_intrinsic_ctors(obj)
        .into_iter()
        .find(|c| on_proto_or_symbol(c))
    {
        return Some(c);
    }
    // Everything else inherits `Object.prototype`'s.
    if on_proto("Object") && intrinsic_reachable(obj, "Object") {
        return Some("Object");
    }
    None
}

/// `structuredClone` — a deep copy of plain data (objects/arrays/primitives).
/// `structuredClone` — the HTML structured-clone algorithm's shape: a deep copy
/// that preserves the *reference graph*. Two properties pointing at the same
/// object clone to two properties pointing at the same clone, and a cycle clones
/// to a cycle instead of recursing forever. `seen` maps each source heap index
/// to its clone, which is what buys both.
/// The rendering node puts in a `DataCloneError` for a value the structured
/// clone algorithm refuses, or `None` when the value IS cloneable.
///
/// Refusing at all is the point: these used to be copied through by reference,
/// so `structuredClone({f: () => 1})` handed back an object sharing the
/// original's function and `structuredClone(new WeakMap())` returned the very
/// same WeakMap. Node throws on every one of them.
fn clone_refusal(v: &Value) -> Option<String> {
    let kind = with_host(|h| h.kind_of(v))?;
    let render = |ctor: &str| Some(format!("#<{ctor}>"));
    match kind {
        // A function renders as its SOURCE TEXT here, which each FuncDef
        // keeps as a span into its script (`JsHost::func_source`).
        ObjKind::Func | ObjKind::Class | ObjKind::BoundFunc | ObjKind::BoundMethod => {
            Some(with_host(|h| h.str_of(v)))
        }
        ObjKind::Builtin if with_host(|h| host::is_callable(h, v)) => {
            Some(with_host(|h| h.str_of(v)))
        }
        ObjKind::Symbol => Some(with_host(|h| h.str_of(v))),
        ObjKind::Promise => render("Promise"),
        ObjKind::Generator => Some("[object Generator]".to_string()),
        // A proxy is refused by its TARGET's shape: a callable one renders like
        // the function it wraps, everything else as a plain object.
        ObjKind::Proxy => Some(if with_host(|h| host::is_callable(h, v)) {
            with_host(|h| h.str_of(v))
        } else {
            "#<Object>".to_string()
        }),
        ObjKind::Map if with_host(|h| matches!(h.get(v), Some(JsObj::Map { weak: true, .. }))) => {
            render("WeakMap")
        }
        ObjKind::Set if with_host(|h| matches!(h.get(v), Some(JsObj::Set { weak: true, .. }))) => {
            render("WeakSet")
        }
        _ => match crate::stdlib::native_tag(v).as_deref() {
            Some(t @ ("WeakRef" | "FinalizationRegistry")) => render(t),
            _ => None,
        },
    }
}

/// `structuredClone(value[, { transfer }])`.
///
/// Everything in `transfer` must be an `ArrayBuffer`, and each one is DETACHED
/// after the clone — its bytes belong to the copy. The option used to be
/// ignored entirely, so the source buffer stayed usable where node leaves it
/// with zero length.
fn structured_clone(args: Vec<Value>) -> Result<Value, String> {
    let list: Vec<Value> = match args.get(1).filter(|v| !matches!(v, Value::Undef)) {
        Some(opts) => {
            let t = get_property(opts, "transfer")?;
            if matches!(t, Value::Undef) {
                Vec::new()
            } else {
                host::iter_all(&t)?
            }
        }
        None => Vec::new(),
    };
    for item in &list {
        if crate::stdlib::native_tag(item).as_deref() != Some("ArrayBuffer") {
            return Err(host::dom_error(
                "DataCloneError",
                "Found invalid value in transferList.",
            ));
        }
    }
    let out = deep_clone(&arg0(&args))?;
    for item in &list {
        crate::stdlib::typedarray::detach_buffer(item);
    }
    Ok(out)
}

pub(crate) fn deep_clone(v: &Value) -> Result<Value, String> {
    deep_clone_seen(v, &mut std::collections::HashMap::new())
}

fn deep_clone_seen(
    v: &Value,
    seen: &mut std::collections::HashMap<u32, Value>,
) -> Result<Value, String> {
    let idx = match v {
        Value::Obj(i) => *i,
        _ => return Ok(v.clone()),
    };
    if let Some(done) = seen.get(&idx) {
        return Ok(done.clone());
    }
    if crate::stdlib::typedarray::is_detached(v) {
        return Err(host::dom_error(
            "DataCloneError",
            "An ArrayBuffer is detached and could not be cloned.",
        ));
    }
    if let Some(render) = clone_refusal(v) {
        return Err(host::dom_error(
            "DataCloneError",
            &format!("{render} could not be cloned."),
        ));
    }
    // A REGEXP is cloned, not shared: it carries a mutable `lastIndex`, so
    // handing back the same object let a write through the clone move the
    // original's match cursor.
    if let Some((src, flags)) = with_host(|h| match h.get(v) {
        Some(JsObj::RegExp(r)) => Some((r.source.clone(), r.flags.clone())),
        _ => None,
    }) {
        let args = with_host(|h| vec![h.new_str(src), h.new_str(flags)]);
        let out = regexp_ctor(&args)?;
        seen.insert(idx, out.clone());
        return Ok(out);
    }
    Ok(match with_host(|h| h.get(v).cloned()) {
        Some(JsObj::Array(items)) => {
            // Register the (empty) clone BEFORE recursing so a self-reference
            // resolves to it.
            let out = with_host(|h| h.new_array(Vec::new()));
            seen.insert(idx, out.clone());
            let mut cloned: Vec<Value> = Vec::with_capacity(items.len());
            for x in &items {
                cloned.push(deep_clone_seen(x, seen)?);
            }
            with_host(|h| {
                if let Some(JsObj::Array(a)) = h.get_mut(&out) {
                    *a = cloned;
                }
                // A sparse source clones to an equally sparse array: the clone
                // walks own properties, so a hole is nothing to copy.
                h.copy_holes(v, &out, Some);
            });
            out
        }
        Some(JsObj::Object(_)) => {
            let out = with_host(|h| h.new_object(IndexMap::new()));
            seen.insert(idx, out.clone());
            // Own ENUMERABLE string keys, read THROUGH any accessor: the clone
            // walked the property map, where an accessor stores nothing, so
            // `structuredClone({get p(){return 1}})` silently lost `p`. A symbol
            // key and a non-enumerable one are dropped, as node drops them.
            let is_error = with_host(|h| h.error_to_string(v)).is_some();
            let proto = clone_proto(v);
            let keeps_proto = !matches!(proto, CloneProto::Plain);
            // An ERROR clones its name, message and stack and NOTHING else —
            // node drops any other own property, even an enumerable one.
            let keys: Vec<String> = if is_error {
                // An ERROR clones its name, message and stack and NOTHING else —
                // node drops any other own property, even an enumerable one.
                ["name", "message", "stack"]
                    .iter()
                    .filter(|k| has_property(v, k).unwrap_or(false))
                    .map(|k| (*k).to_string())
                    .collect()
            } else if keeps_proto {
                // A preserved exotic keeps EVERY own property, including the
                // non-enumerable ones and the internal slots — a Date's time
                // value, an ArrayBuffer's `byteLength` and byte store, a typed
                // array's view. The enumerable-only walk dropped all of those,
                // so a cloned Date read `Invalid Date` and a cloned
                // ArrayBuffer had no `byteLength`.
                with_host(|h| match h.get(v) {
                    Some(JsObj::Object(p)) => p.keys().cloned().collect(),
                    _ => Vec::new(),
                })
            } else {
                with_host(|h| h.own_enum_key_names(v))
            };
            let mut cloned: IndexMap<String, Value> = IndexMap::new();
            for k in keys {
                // An internal slot is read straight out of the map: it is not a
                // property, so a `[[Get]]` would not find it.
                let val = if k.starts_with("@@") {
                    match with_host(|h| match h.get(v) {
                        Some(JsObj::Object(p)) => p.get(&k).cloned(),
                        _ => None,
                    }) {
                        Some(val) => val,
                        None => continue,
                    }
                } else {
                    get_property(v, &k)?
                };
                cloned.insert(k, deep_clone_seen(&val, seen)?);
            }
            // The prototype survives only for the exotics the algorithm knows —
            // a Date, an Error, a typed array, a boxed primitive. A USER class
            // instance becomes a plain object, which is what node produces;
            // keeping every prototype made `structuredClone(new K())
            // instanceof K` true.
            with_host(|h| {
                if let Some(JsObj::Object(p)) = h.get_mut(&out) {
                    *p = cloned;
                }
                match &proto {
                    CloneProto::Same => {
                        if let Some(p) = h.proto_of(v) {
                            h.set_proto(&out, p);
                        }
                    }
                    CloneProto::Ctor(c) => {
                        h.ensure_error_protos();
                        let p = h.error_proto(c).or_else(|| h.ensure_ctor_proto(c));
                        if let Some(p) = p {
                            h.set_proto(&out, p);
                        }
                        // A Buffer clones to a plain `Uint8Array`, so the native
                        // tag has to change with the prototype — left alone,
                        // `Buffer.isBuffer` still answered true for the clone.
                        // A Buffer clones to a plain `Uint8Array`, so the native
                        // tag has to change with the prototype — left alone,
                        // `Buffer.isBuffer` answered true for the clone and the
                        // brand stayed `[object Object]`. A typed array is
                        // tagged `TypedArray` and names its element type in
                        // `@@kind`; `@@native = "Uint8Array"` matches no arm.
                        if c == "Uint8Array" {
                            let tag = h.new_str("TypedArray");
                            let kind = h.new_str("Uint8Array");
                            if let Some(JsObj::Object(p)) = h.get_mut(&out) {
                                p.insert("@@native".into(), tag);
                                p.insert("@@kind".into(), kind);
                            }
                        }
                    }
                    CloneProto::Plain => {}
                }
                h.copy_prop_attrs(v, &out);
            });
            out
        }
        // Map/Set are structured types: clone the entries, keep the kind.
        Some(JsObj::Map { entries, weak }) => {
            let out = with_host(|h| {
                h.alloc(JsObj::Map {
                    entries: IndexMap::new(),
                    weak,
                })
            });
            seen.insert(idx, out.clone());
            let pairs: Vec<(Value, Value)> = entries.values().cloned().collect();
            for (k, val) in pairs {
                let ck = deep_clone_seen(&k, seen)?;
                let cv = deep_clone_seen(&val, seen)?;
                let _ = map_method(&out, "set", vec![ck, cv]);
            }
            out
        }
        Some(JsObj::Set { entries, weak }) => {
            let out = with_host(|h| {
                h.alloc(JsObj::Set {
                    entries: IndexMap::new(),
                    weak,
                })
            });
            seen.insert(idx, out.clone());
            let vals: Vec<Value> = entries.values().cloned().collect();
            for x in vals {
                let cx = deep_clone_seen(&x, seen)?;
                let _ = set_method(&out, "add", vec![cx]);
            }
            out
        }
        // A string, a BigInt and a boxed primitive are immutable enough to
        // share; anything left is a value type.
        _ => v.clone(),
    })
}

/// Whether a cloned object keeps the source's prototype.
///
/// The structured clone algorithm reproduces the exotics it knows and turns
/// everything else into a plain object — so a `Date` clones to a `Date` and a
/// user class instance clones to an `Object`.
fn clone_proto(v: &Value) -> CloneProto {
    // An ERROR clones to the BUILT-IN class its `name` selects, so a subclass
    // flattens: `structuredClone(new (class E extends Error{})('m'))` reports
    // `Error`, not `E`.
    if with_host(|h| h.error_to_string(v)).is_some() {
        let name = get_property(v, "name")
            .map(|n| with_host(|h| h.str_of(&n)))
            .unwrap_or_else(|_| "Error".into());
        let class = if host::ERROR_NAMES.contains(&name.as_str()) {
            name
        } else {
            "Error".to_string()
        };
        return CloneProto::Ctor(class);
    }
    match crate::stdlib::native_tag(v).as_deref() {
        // A Buffer is not reproduced as a Buffer: node hands back a plain
        // `Uint8Array` over the same bytes.
        Some("Buffer") => CloneProto::Ctor("Uint8Array".into()),
        Some(_) => CloneProto::Same,
        // A boxed primitive keeps its wrapper; anything else — a user class
        // instance included — becomes a plain object.
        None if wrapped_primitive(v).is_some() => CloneProto::Same,
        None => CloneProto::Plain,
    }
}

/// Which prototype a clone gets: the source's, a named builtin's, or none.
enum CloneProto {
    Same,
    Ctor(String),
    Plain,
}

// ══ Promises, timers, microtasks (event-loop-driven) ═════════════════════════

/// A short `Name: message` string for an error value (used when an await
/// rejection unwinds as a thrown error).
pub fn error_string(h: &host::JsHost, v: &Value) -> String {
    if let Some(JsObj::Object(props)) = h.get(v) {
        let name = props
            .get("name")
            .map(|x| h.str_of(x))
            .or_else(|| host::lookup_chain(h, v, "name").map(|x| h.str_of(&x)))
            .unwrap_or_else(|| "Error".into());
        if let Some(m) = props.get("message") {
            return format!("{name}: {}", h.str_of(m));
        }
        return name;
    }
    h.str_of(v)
}

/// 27.2.5.3 `thenFinally`/`catchFinally`: `PromiseResolve(result).then(() =>
/// value)`, or `() => { throw reason }` on the reject path.
///
/// Returning the carried value directly — what this used to do — skipped both
/// halves. A promise returned by the callback was never awaited, so the
/// ordinary async-cleanup shape
///
/// ```text
/// work().finally(() => closeConnection()).then(next)
/// ```
///
/// ran `next` before the connection had closed. And the chain settled three
/// microtask ticks early, which is observable in ordering against any other
/// chain, not just against a timer.
///
/// A rejection from the callback's own promise wins over the carried value, so
/// no reject handler is attached here: it propagates on its own.
fn finally_chain(result: Value, carried: Value, rethrow: bool) -> Value {
    // PromiseResolve (27.2.4.7) returns an argument that is already a promise
    // UNCHANGED. Wrapping it anyway costs the extra tick that resolving with a
    // thenable takes to adopt it, which showed up as a callback returning a
    // rejected promise settling one tick late against every other chain.
    let p = match with_host(|h| h.promise_id(&result)) {
        Some(_) => result,
        None => {
            let fresh = with_host(|h| h.new_promise());
            if let Some(pid) = with_host(|h| h.promise_id(&fresh)) {
                host::resolve_promise_val(pid, result);
            }
            fresh
        }
    };
    let cell = with_host(|h| h.new_array(vec![carried]));
    let idx = match cell {
        Value::Obj(i) => i,
        _ => 0,
    };
    let tag = if rethrow { "finrethrow" } else { "finret" };
    let thunk = make_builtin(format!("@@{tag}:{idx}"));
    host::promise_then(&p, thunk, Value::Undef)
}

fn make_builtin(name: String) -> Value {
    with_host(|h| h.alloc(JsObj::Builtin(name)))
}

/// `[[GetPrototypeOf]]` (10.1.1) — the answer `Object.getPrototypeOf`,
/// `Reflect.getPrototypeOf` and a `__proto__` READ all have to agree on.
///
/// `__proto__` used to answer from `JsHost::proto_of` alone, which records only
/// an EXPLICIT link, so an object on the default prototype reported `null`:
/// `({}).__proto__ === Object.prototype` was false while
/// `Object.getPrototypeOf({}) === Object.prototype` was true. One function, so
/// the three cannot drift apart again.
pub fn prototype_of(v: &Value) -> Value {
    // Constructor-side inheritance: `Buffer extends Uint8Array`, so
    // `Object.getPrototypeOf(Buffer)` is the `Uint8Array` constructor itself,
    // not `Function.prototype`. This is the class-side half of the subclass
    // link — the instance-side half is `Buffer.prototype`'s `[[Prototype]]`.
    if matches!(with_host(|h| h.get(v).cloned()), Some(JsObj::Builtin(ref n)) if n == "Buffer") {
        return with_host(|h| h.alloc(JsObj::Builtin("Uint8Array".into())));
    }
    // Constructor-side inheritance for a `class B extends A` (ClassDefinition
    // 15.7.14 step 6.d: the constructor's `[[Prototype]]` is the parent
    // CONSTRUCTOR, not `Function.prototype`). Statics already resolved through
    // `ClassVal.parent`, but the link itself was invisible, so
    // `Object.getPrototypeOf(B) === A` read false and any library walking the
    // constructor chain — rather than calling a static — saw a base class.
    // A base class keeps the default answer below (`Function.prototype`).
    if let Some(JsObj::Class(c)) = with_host(|h| h.get(v).cloned()) {
        if let Some(parent) = c.parent {
            return parent;
        }
    }
    // `Object.create(null)` and friends really do have a null prototype.
    if with_host(|h| h.has_null_proto(v)) {
        return with_host(|h| h.null());
    }
    // `Object.prototype` is the CHAIN ROOT, so its own prototype is `null`. It
    // reported itself, because the fallback below answers by constructor name
    // and a plain object's is `Object` — an infinite chain to anything walking
    // it.
    if with_host(|h| h.strict_eq(v, &h.object_proto())) {
        return with_host(|h| h.null());
    }
    // Every OTHER builtin prototype namespace (`Array.prototype`,
    // `Function.prototype`, …) inherits from `Object.prototype`; the fallback
    // would send it back to a namespace handle for its own constructor.
    if matches!(
        with_host(|h| h.get(v).cloned()),
        Some(JsObj::Builtin(ref n)) if n.ends_with(".prototype")
    ) {
        return with_host(|h| h.object_proto());
    }
    if let Some(p) = with_host(|h| h.proto_of(v)) {
        return p;
    }
    // A builtin exotic with no explicit `[[Prototype]]` link reports its
    // constructor's prototype namespace (`Object.getPrototypeOf([]) ===
    // Array.prototype`), which `strict_eq` compares by name. A plain object
    // reports the one real `Object.prototype` object.
    with_host(|h| {
        h.ensure_native_protos();
        match default_ctor_name(h, v) {
            Some("Object") => h.object_proto(),
            // `String`/`Number`/`Boolean` own REAL prototype objects, so a
            // primitive must report that object and not a fresh namespace
            // thunk — otherwise `Object.getPrototypeOf(1) === Number.prototype`
            // compares a thunk against the real object and reads false.
            Some(c) => h
                .native_proto(c)
                .unwrap_or_else(|| h.alloc(JsObj::Builtin(format!("{c}.prototype")))),
            None => h.null(),
        }
    })
}

/// `new Promise((resolve, reject) => …)` — run the executor synchronously with
/// internal resolve/reject functions.
/// A fresh promise built through the SPECIES constructor, when a `Promise`
/// static was reached through a subclass.
///
/// `class P extends Promise {}` makes `P.resolve(1)` a `P`, because every
/// combinator builds its result with `this` (27.2.4.x). They all allocated a
/// plain promise, so nothing a subclass produced was an instance of it. The
/// executor is a no-op: the result is settled through its promise id, which is
/// what the ordinary path does too.
fn promise_species_create() -> Result<Option<Value>, String> {
    let Some(ctor) = host::current_static_this() else {
        return Ok(None);
    };
    if !matches!(
        with_host(|h| h.kind_of(&ctor)),
        Some(ObjKind::Class) | Some(ObjKind::Func)
    ) {
        return Ok(None);
    }
    let species = match get_property(&ctor, "@@species") {
        Ok(Value::Undef) => ctor,
        Ok(s) if with_host(|h| h.is_null(&s)) => return Ok(None),
        Ok(s) => s,
        Err(_) => ctor,
    };
    if !matches!(
        with_host(|h| h.kind_of(&species)),
        Some(ObjKind::Class) | Some(ObjKind::Func)
    ) {
        return Ok(None);
    }
    let noop = make_builtin("@@pnoop".to_string());
    let p = host::construct(&species, vec![noop])?;
    // Only usable if the subclass really produced a promise; a constructor that
    // returned something else has no id to settle.
    Ok(with_host(|h| h.promise_id(&p)).map(|_| p))
}

/// The species constructor of a promise RECEIVER — what `then`/`catch`/`finally`
/// build their result with (`SpeciesConstructor(p, %Promise%)`, 27.2.5.4 step 3).
///
/// Distinct from `promise_species_create`, which answers for a STATIC reached
/// through a subclass. Here the subclass comes from the receiver itself, so
/// `P.resolve(1).then(f)` is also a `P`.
pub fn promise_species_from(recv: &Value) -> Result<Option<Value>, String> {
    // A chain lookup: a Promise receiver resolves through the stdlib funnel,
    // which has no `constructor` entry of its own.
    let ctor = with_host(|h| host::lookup_chain(h, recv, "constructor")).unwrap_or(Value::Undef);
    if !matches!(
        with_host(|h| h.kind_of(&ctor)),
        Some(ObjKind::Class) | Some(ObjKind::Func)
    ) {
        return Ok(None);
    }
    let species = match get_property(&ctor, "@@species") {
        Ok(Value::Undef) => ctor,
        Ok(s) if with_host(|h| h.is_null(&s)) => return Ok(None),
        Ok(s) => s,
        Err(_) => ctor,
    };
    if !matches!(
        with_host(|h| h.kind_of(&species)),
        Some(ObjKind::Class) | Some(ObjKind::Func)
    ) {
        return Ok(None);
    }
    let noop = make_builtin("@@pnoop".to_string());
    let p = host::construct(&species, vec![noop])?;
    Ok(with_host(|h| h.promise_id(&p)).map(|_| p))
}

fn new_promise(executor: Value) -> Result<Value, String> {
    let p = with_host(|h| h.new_promise());
    let id = with_host(|h| h.promise_id(&p).unwrap());
    let res = make_builtin(format!("@@presolve:{id}"));
    let rej = make_builtin(format!("@@preject:{id}"));
    if let Err(e) = host::invoke(&executor, vec![res, rej], None) {
        // A throw in the executor rejects the promise.
        let ev = host::take_exc_or_error(&e);
        host::reject_promise_val(id, ev);
    }
    Ok(p)
}

/// `Promise.resolve(v)` for stdlib callers that need to hand back an
/// already-settled promise.
pub fn promise_resolve_pub(v: Value) -> Result<Value, String> {
    promise_resolve(v)
}

fn promise_resolve(v: Value) -> Result<Value, String> {
    if let Some(p) = promise_species_create()? {
        let id = with_host(|h| h.promise_id(&p).unwrap());
        host::resolve_promise_val(id, v);
        return Ok(p);
    }
    Ok(host::promise_of(&v))
}
fn promise_reject(v: Value) -> Result<Value, String> {
    let p = match promise_species_create()? {
        Some(p) => p,
        None => with_host(|h| h.new_promise()),
    };
    let id = with_host(|h| h.promise_id(&p).unwrap());
    host::reject_promise_val(id, v);
    Ok(p)
}

/// `Promise.withResolvers()` — a fresh pending promise paired with its own
/// resolve/reject continuations (the same `@@presolve`/`@@preject` thunks the
/// executor receives), returned as a plain `{ promise, resolve, reject }` object.
/// A fresh pending promise paired with the thunk that resolves it, for stdlib
/// callers that hand the resolver to an event listener.
pub fn pending_promise_with_resolver() -> (Value, Value) {
    let p = with_host(|h| h.new_promise());
    let id = with_host(|h| h.promise_id(&p).unwrap());
    let resolve = make_builtin(format!("@@presolve:{id}"));
    (p, resolve)
}

/// `RegExp.escape(s)` (22.2.4.2) — a string that matches `s` literally.
///
/// The rule is not "backslash the syntax characters": it also escapes a LEADING
/// ASCII alphanumeric, so the result can be concatenated after a `\` or a `{`
/// without the two running together, and it escapes the punctuation that is
/// meaningful inside a character class or a group name.
fn regexp_escape(args: Vec<Value>) -> Result<Value, String> {
    let v = arg0(&args);
    if !matches!(v, Value::Str(_)) && !with_host(|h| matches!(h.get(&v), Some(JsObj::Str(_)))) {
        return Err(host::type_error("input argument must be a string"));
    }
    let s = with_host(|h| h.str_of(&v));
    // Punctuation that is escaped by CODE POINT rather than with a backslash.
    // Measured against node over the whole ASCII range, not taken from a list:
    // `-` and `=` are here, `$` and `*` are syntax characters and are not.
    const OTHER_PUNCTUATORS: &str = " !\"#%&',-:;<=>@`~";
    const SYNTAX: &str = "^$\\.*+?()[]{}|/";
    let mut out = String::with_capacity(s.len());
    for (i, c) in s.chars().enumerate() {
        // A leading ASCII alphanumeric, and only a leading one.
        if i == 0 && c.is_ascii_alphanumeric() {
            out.push_str(&format!("\\x{:02x}", c as u32));
            continue;
        }
        if SYNTAX.contains(c) {
            out.push('\\');
            out.push(c);
            continue;
        }
        match c {
            '\t' => out.push_str("\\t"),
            '\n' => out.push_str("\\n"),
            '\u{b}' => out.push_str("\\v"),
            '\u{c}' => out.push_str("\\f"),
            '\r' => out.push_str("\\r"),
            _ if OTHER_PUNCTUATORS.contains(c) || is_regex_escape_space(c) => {
                let n = c as u32;
                if n <= 0xff {
                    out.push_str(&format!("\\x{n:02x}"));
                } else {
                    out.push_str(&format!("\\u{n:04x}"));
                }
            }
            _ => out.push(c),
        }
    }
    Ok(with_host(|h| h.new_str(out)))
}

/// The WhiteSpace and LineTerminator code points `RegExp.escape` spells out.
/// Deliberately NOT `char::is_whitespace`: U+180E and U+200B are whitespace to
/// Unicode but not to ECMAScript, and node leaves both alone.
fn is_regex_escape_space(c: char) -> bool {
    matches!(
        c,
        '\u{a0}' | '\u{1680}' | '\u{2000}'
            ..='\u{200a}'
                | '\u{2028}'
                | '\u{2029}'
                | '\u{202f}'
                | '\u{205f}'
                | '\u{3000}'
                | '\u{feff}'
    )
}

/// `Error.isError(v)` (20.5.2.1) — a brand check for `[[ErrorData]]`, so an
/// object that merely INHERITS from `Error.prototype` is not one.
fn error_is_error(args: Vec<Value>) -> Result<Value, String> {
    let v = arg0(&args);
    Ok(Value::Bool(with_host(|h| has_error_data(h, &v))))
}

/// Whether `v` carries `[[ErrorData]]` — the slot `Error.isError` (20.5.2.1)
/// and `Object.prototype.toString`'s step 9 both test.
///
/// The brand is the OWN `stack` an error is built with (a `DOMException`
/// carries `@@domName` instead); a plain `Object.create(Error.prototype)` has
/// neither, which is why inheriting from an error prototype does not make a
/// value an error. Shared so the two cannot disagree — branding by a chain
/// lookup for `name`/`message` made `Object.create(Error.prototype)` report
/// `[object Error]` where node says `[object Object]`, while `Error.isError`
/// on the same value already said false.
pub(crate) fn has_error_data(h: &host::JsHost, v: &Value) -> bool {
    match h.get(v) {
        Some(JsObj::Object(p)) => {
            p.contains_key("stack") || p.contains_key("@@stackRaw") || p.contains_key("@@domName")
        }
        _ => false,
    }
}

/// `Promise.try(fn, ...args)` (27.2.4.6) — call `fn` and settle the promise with
/// what it does, so a SYNCHRONOUS throw becomes a rejection instead of
/// propagating. `Promise.resolve().then(fn)` is the shape it replaces, and it
/// costs a tick that this does not.
fn promise_try(args: Vec<Value>) -> Result<Value, String> {
    let f = arg0(&args);
    // A non-callable argument REJECTS, it does not throw: `Promise.try(5)`
    // returns a rejected promise, so the surrounding `try` never sees it.
    if !with_host(|h| host::is_callable(h, &f)) {
        // Node names the TYPE alongside the value — `number 5 is not a
        // function` — which the ordinary call-site message does not. A plain
        // object and a symbol name only the type; `null` names both.
        let shown = with_host(|h| {
            let kind = h.type_of(&f);
            match kind {
                "undefined" => "undefined".to_string(),
                "symbol" | "bigint" => kind.to_string(),
                "object" if h.is_null(&f) => "object null".to_string(),
                "object" => "object".to_string(),
                "string" => format!("string \"{}\"", h.str_of(&f)),
                _ => format!("{kind} {}", h.str_of(&f)),
            }
        });
        let p = with_host(|h| h.new_promise());
        let id = with_host(|h| h.promise_id(&p).unwrap());
        let reject = make_builtin(format!("@@preject:{id}"));
        let err =
            with_host(|h| synth_error(h, &host::type_error(&format!("{shown} is not a function"))));
        host::invoke(&reject, vec![err], None)?;
        return Ok(p);
    }
    let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
    let p = with_host(|h| h.new_promise());
    let id = with_host(|h| h.promise_id(&p).unwrap());
    let resolve = make_builtin(format!("@@presolve:{id}"));
    let reject = make_builtin(format!("@@preject:{id}"));
    let promise = p;
    match host::invoke(&f, rest, None) {
        Ok(v) => {
            host::invoke(&resolve, vec![v], None)?;
        }
        Err(e) => {
            // The thrown VALUE, not a re-synthesis of its rendering: a callback
            // that throws a `TypeError` must reject with that object, and
            // rebuilding it from the message string flattened it to a plain
            // `Error` whose message was the rendered `Uncaught TypeError: t`.
            let err =
                with_host(|h| h.exc.clone()).unwrap_or_else(|| with_host(|h| synth_error(h, &e)));
            with_host(|h| {
                h.error = None;
                h.exc = None;
            });
            host::invoke(&reject, vec![err], None)?;
        }
    }
    Ok(promise)
}

fn promise_with_resolvers() -> Result<Value, String> {
    let p = with_host(|h| h.new_promise());
    let id = with_host(|h| h.promise_id(&p).unwrap());
    let resolve = make_builtin(format!("@@presolve:{id}"));
    let reject = make_builtin(format!("@@preject:{id}"));
    let mut props: IndexMap<String, Value> = IndexMap::new();
    props.insert("promise".into(), p);
    props.insert("resolve".into(), resolve);
    props.insert("reject".into(), reject);
    Ok(with_host(|h| h.new_object(props)))
}

/// A promise already rejected with `e` — what every combinator hands back when
/// the ITERABLE misbehaves.
///
/// 27.2.4.1 step 4 catches an abrupt completion from the iteration and rejects
/// rather than letting it propagate, so `Promise.all(badIterable)` returns a
/// rejected promise. Throwing synchronously meant a `.catch()` never attached
/// and the caller saw the error at the call site instead.
fn rejected_promise(e: String) -> Value {
    let p = with_host(|h| h.new_promise());
    let id = with_host(|h| h.promise_id(&p).unwrap());
    let reject = make_builtin(format!("@@preject:{id}"));
    let err = with_host(|h| h.exc.clone()).unwrap_or_else(|| with_host(|h| synth_error(h, &e)));
    with_host(|h| {
        h.error = None;
        h.exc = None;
    });
    let _ = host::invoke(&reject, vec![err], None);
    p
}

#[derive(Clone, Copy)]
enum AllMode {
    All,
    AllSettled,
}

/// `Promise.all` / `Promise.allSettled`.
fn promise_all(args: Vec<Value>, mode: AllMode) -> Result<Value, String> {
    let items = match host::iter_all(&arg0(&args)) {
        Ok(v) => v,
        Err(e) => return Ok(rejected_promise(e)),
    };
    // 27.2.4.1 step 3: the combinator builds its result with `this`, so on a
    // subclass the promise it hands back is an instance of that subclass.
    let result = match promise_species_create()? {
        Some(p) => p,
        None => with_host(|h| h.new_promise()),
    };
    let rid = with_host(|h| h.promise_id(&result).unwrap());
    let n = items.len();
    if n == 0 {
        let empty = with_host(|h| h.new_array(Vec::new()));
        host::resolve_promise_val(rid, empty);
        return Ok(result);
    }
    // Shared mutable accumulator via Rc<RefCell<…>>.
    let slots = std::rc::Rc::new(std::cell::RefCell::new(vec![Value::Undef; n]));
    let remaining = std::rc::Rc::new(std::cell::RefCell::new(n));
    for (i, it) in items.into_iter().enumerate() {
        let ap = host::promise_of(&it);
        let aid = with_host(|h| h.promise_id(&ap).unwrap());
        let slots = slots.clone();
        let remaining = remaining.clone();
        host::subscribe_native(
            aid,
            Box::new(move |state, val| {
                let settled = match mode {
                    AllMode::All => {
                        if state == host::PromiseState::Rejected {
                            host::reject_promise_val(rid, val);
                            return Ok(());
                        }
                        val
                    }
                    AllMode::AllSettled => with_host(|h| {
                        let mut m: IndexMap<String, Value> = IndexMap::new();
                        if state == host::PromiseState::Rejected {
                            m.insert("status".into(), h.new_str("rejected"));
                            m.insert("reason".into(), val);
                        } else {
                            m.insert("status".into(), h.new_str("fulfilled"));
                            m.insert("value".into(), val);
                        }
                        h.new_object(m)
                    }),
                };
                slots.borrow_mut()[i] = settled;
                let mut r = remaining.borrow_mut();
                *r -= 1;
                if *r == 0 {
                    let arr = with_host(|h| h.new_array(slots.borrow().clone()));
                    host::resolve_promise_val(rid, arr);
                }
                Ok(())
            }),
        );
    }
    Ok(result)
}

/// `Promise.race` (first to settle wins) / `Promise.any` (first to fulfill wins).
fn promise_race(args: Vec<Value>, any: bool) -> Result<Value, String> {
    let items = match host::iter_all(&arg0(&args)) {
        Ok(v) => v,
        Err(e) => return Ok(rejected_promise(e)),
    };
    // Built with `this`, as every combinator is (27.2.4.5 / 27.2.4.3).
    let result = match promise_species_create()? {
        Some(p) => p,
        None => with_host(|h| h.new_promise()),
    };
    let rid = with_host(|h| h.promise_id(&result).unwrap());
    let n = items.len();
    let errors = std::rc::Rc::new(std::cell::RefCell::new(vec![Value::Undef; n]));
    let remaining = std::rc::Rc::new(std::cell::RefCell::new(n));
    for (i, it) in items.into_iter().enumerate() {
        let ap = host::promise_of(&it);
        let aid = with_host(|h| h.promise_id(&ap).unwrap());
        let errors = errors.clone();
        let remaining = remaining.clone();
        host::subscribe_native(
            aid,
            Box::new(move |state, val| {
                if any {
                    if state == host::PromiseState::Fulfilled {
                        host::resolve_promise_val(rid, val);
                    } else {
                        errors.borrow_mut()[i] = val;
                        let mut r = remaining.borrow_mut();
                        *r -= 1;
                        if *r == 0 {
                            // All rejected → AggregateError carrying every reason.
                            let reasons = with_host(|h| h.new_array(errors.borrow().clone()));
                            let msg = with_host(|h| h.new_str("All promises were rejected"));
                            let agg = make_error_inner("AggregateError", &[reasons, msg]);
                            host::reject_promise_val(rid, agg);
                        }
                    }
                } else if state == host::PromiseState::Rejected {
                    host::reject_promise_val(rid, val);
                } else {
                    host::resolve_promise_val(rid, val);
                }
                Ok(())
            }),
        );
    }
    Ok(result)
}

/// `.then` / `.catch` / `.finally` on a promise.
fn promise_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "then" => Ok(host::promise_then(
            recv,
            args.first().cloned().unwrap_or(Value::Undef),
            args.get(1).cloned().unwrap_or(Value::Undef),
        )),
        "catch" => Ok(host::promise_then(
            recv,
            Value::Undef,
            args.first().cloned().unwrap_or(Value::Undef),
        )),
        "finally" => {
            let cb = arg0(&args);
            // 27.2.5.3 step 3: a non-callable `onFinally` is handed to `then`
            // as BOTH handlers, and `then` ignores a non-callable one — so the
            // value or reason simply passes through. Building the thunks
            // regardless meant `p.finally(null)` tried to call `null`.
            if !with_host(|h| host::is_callable(h, &cb)) {
                return Ok(host::promise_then(recv, cb.clone(), cb));
            }
            let i = match cb {
                Value::Obj(i) => i,
                _ => 0,
            };
            let pass = make_builtin(format!("@@finpass:{i}"));
            let throw = make_builtin(format!("@@finthrow:{i}"));
            Ok(host::promise_then(recv, pass, throw))
        }
        _ => Err(host::type_error(&format!(
            "promise.{name} is not a function"
        ))),
    }
}

fn enqueue_microtask(next_tick: bool, cb: Value, args: Vec<Value>) {
    with_host(|h| {
        if next_tick {
            h.queue_nexttick(cb, args);
        } else {
            h.queue_micro(cb, args);
        }
    });
}

/// `setTimeout`/`setInterval`/`setImmediate` — register a macrotask and return
/// the handle object Node returns (`Timeout` for the first two, `Immediate` for
/// the third), carrying `ref`/`unref`/`hasRef`/`refresh`.
///
/// `setInterval` schedules a *repeating* timer: the loop re-arms it each time it
/// fires, so it runs until cleared and — being referenced — holds the process
/// open exactly as in Node.
fn schedule_timer(name: &str, args: Vec<Value>) -> Value {
    let cb = arg0(&args);
    let delay = if name == "setImmediate" {
        -1.0 // before any 0ms timeout
    } else {
        args.get(1)
            .map(|d| with_host(|h| h.to_number(d)))
            .unwrap_or(0.0)
            .max(0.0)
    };
    let extra = if name == "setImmediate" {
        args.get(1..).map(|s| s.to_vec()).unwrap_or_default()
    } else {
        args.get(2..).map(|s| s.to_vec()).unwrap_or_default()
    };
    // Node clamps a sub-1ms interval to 1ms, so `setInterval(fn, 0)` yields a
    // ~1000Hz timer rather than a busy loop that starves the rest of the queue.
    let interval = (name == "setInterval").then(|| delay.max(1.0));
    let id = with_host(|h| h.add_timer(delay, cb, extra, interval));
    let tag = if name == "setImmediate" {
        "Immediate"
    } else {
        "Timeout"
    };
    crate::stdlib::timers::new_handle(id, tag)
}

/// `clearTimeout`/`clearInterval`/`clearImmediate` — cancel by handle object or
/// by the bare id it coerces to (code that stored `+timer` still works).
fn clear_timer(v: &Value) {
    let id =
        crate::stdlib::timers::handle_id(v).unwrap_or_else(|| with_host(|h| h.to_number(v)) as u64);
    with_host(|h| h.cancel_timer(id));
}