v8x 149.4.0-rc.1

Engine agnostic JavaScript
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
//! Family "misc" (QuickJS backend): SnapshotCreator / StartupData / CppHeap /
//! cppgc / WeakCallbackInfo / Proxy / JSON / Wasm* / Task / IdleTask / Global.
//!
//! QuickJS has no equivalent for V8 snapshots, cppgc (Oilpan), the WebAssembly
//! C++ internals or the C++ task abstractions, so most of these are safe inert
//! defaults (see the `TODO(qjs)` markers). The pieces QuickJS *can* back are
//! implemented for real:
//!   * `v8__Global__New` / `v8__Global__Reset` — `JS_DupValue` / `JS_FreeValue`
//!     against a stable context, with a process-wide protect refcount so the
//!     value outlives handle scopes and survives GC.
//!   * `v8__JSON__Parse` — `JS_ParseJSON`.
//!   * `v8__SnapshotCreator__GetIsolate` / `v8__WeakCallbackInfo__GetIsolate`
//!     surface the current isolate.
//!
//! Mirrors the C-ABI shape of the JSC backend (`src/misc.rs`) but routes
//! every JSValue through the QuickJS refcount helpers in `core`.
#![allow(non_snake_case, unused)]

use crate::binding::RustObj;
use crate::quickjs::core::{
  PersistentCell, PersistentHandle, adjust_external_memory, ctx_of,
  current_ctx, current_iso, intern, intern_dup, iso_state, jsval_of,
  release_external_string_memory,
};
use crate::quickjs::quickjs_sys::*;
use crate::{
  Context, Data, FunctionTemplate, Object, RealIsolate, String as V8String,
  Value,
};

use std::collections::{HashMap, HashSet};
use std::ffi::CStr;
use std::os::raw::{c_char, c_int, c_void};
use std::ptr;
use std::sync::Arc;
use std::sync::atomic::Ordering;

struct WeakCallbackInfoShim {
  isolate: *mut RealIsolate,
  parameter: *const c_void,
  second_pass: Option<crate::quickjs::core::WeakCallback>,
}

struct ProxyRevokeEntry {
  proxy: JSValue,
  revoke: JSValue,
  revoked: bool,
}

thread_local! {
  static PROXY_REVOKES: std::cell::RefCell<Vec<ProxyRevokeEntry>> =
    const { std::cell::RefCell::new(Vec::new()) };
}

#[repr(C)]
struct JSPropertyEnum {
  is_enumerable: bool,
  atom: JSAtom,
}

#[repr(C)]
struct JSPropertyDescriptorQjs {
  flags: c_int,
  value: JSValue,
  getter: JSValue,
  setter: JSValue,
}

const JS_GPN_STRING_MASK: c_int = 1 << 0;
const JS_GPN_SYMBOL_MASK: c_int = 1 << 1;
const JS_GPN_ENUM_ONLY: c_int = 1 << 4;
const JS_PROP_GETSET_QJS: c_int = 1 << 4;
const JS_PROP_CONFIGURABLE_QJS: c_int = 1 << 0;
const JS_PROP_WRITABLE_QJS: c_int = 1 << 1;
const JS_PROP_HAS_CONFIGURABLE_QJS: c_int = 1 << 8;
const JS_PROP_HAS_WRITABLE_QJS: c_int = 1 << 9;
const JS_PROP_HAS_ENUMERABLE_QJS: c_int = 1 << 10;
const JS_PROP_HAS_VALUE_QJS: c_int = 1 << 13;
const HEAP_SNAPSHOT_MAX_DEPTH: usize = 5;
const HEAP_SNAPSHOT_ARRAY_SAMPLE: u32 = 64;

unsafe extern "C" {
  fn v82jsc_clear_error_backtrace(ctx: *mut JSContext, error: JSValue);
  fn JS_GetOwnPropertyNames(
    ctx: *mut JSContext,
    ptab: *mut *mut JSPropertyEnum,
    plen: *mut u32,
    obj: JSValue,
    flags: c_int,
  ) -> c_int;
  fn JS_GetProperty(
    ctx: *mut JSContext,
    this_obj: JSValue,
    prop: JSAtom,
  ) -> JSValue;
  fn JS_GetOwnProperty(
    ctx: *mut JSContext,
    desc: *mut JSPropertyDescriptorQjs,
    obj: JSValue,
    prop: JSAtom,
  ) -> c_int;
  fn JS_DefinePropertyValueStr(
    ctx: *mut JSContext,
    this_obj: JSValue,
    prop: *const c_char,
    val: JSValue,
    flags: c_int,
  ) -> c_int;
  fn rusty_v8_RustObj_trace(obj: *const RustObj, visitor: *mut c_void);
  fn rusty_v8_RustObj_get_name(obj: *const RustObj) -> *const c_char;
  fn rusty_v8_RustObj_drop(obj: *mut RustObj);
}

fn same_value_identity(a: JSValue, b: JSValue) -> bool {
  if a.tag != b.tag {
    return false;
  }
  match a.tag {
    JS_TAG_OBJECT
    | JS_TAG_STRING
    | JS_TAG_STRING_ROPE
    | JS_TAG_SYMBOL
    | JS_TAG_BIG_INT
    | JS_TAG_MODULE
    | JS_TAG_FUNCTION_BYTECODE => unsafe { a.u.ptr == b.u.ptr },
    JS_TAG_FLOAT64 => unsafe { a.u.float64.to_bits() == b.u.float64.to_bits() },
    _ => unsafe { a.u.int32 == b.u.int32 },
  }
}

fn register_proxy_revoke(ctx: *mut JSContext, proxy: JSValue, revoke: JSValue) {
  PROXY_REVOKES.with(|entries| {
    entries.borrow_mut().push(ProxyRevokeEntry {
      proxy: unsafe { JS_DupValue(ctx, proxy) },
      revoke,
      revoked: false,
    });
  });
}

fn proxy_revoked_from_table(proxy: JSValue) -> Option<bool> {
  PROXY_REVOKES.with(|entries| {
    entries
      .borrow()
      .iter()
      .find(|entry| same_value_identity(entry.proxy, proxy))
      .map(|entry| entry.revoked)
  })
}

fn proxy_revoke_function(
  ctx: *mut JSContext,
  proxy: JSValue,
) -> Option<JSValue> {
  PROXY_REVOKES.with(|entries| {
    let mut entries = entries.borrow_mut();
    let entry = entries
      .iter_mut()
      .find(|entry| same_value_identity(entry.proxy, proxy))?;
    entry.revoked = true;
    Some(unsafe { JS_DupValue(ctx, entry.revoke) })
  })
}

fn is_strongly_reachable_from_handles(
  isolate: *mut RealIsolate,
  weak_handle: *const Data,
) -> bool {
  if isolate.is_null() || weak_handle.is_null() {
    return false;
  }
  let weak_slot = weak_handle as *const JSValue;
  let weak_value = unsafe { *weak_slot };
  let st = iso_state(isolate);
  st.handles.iter().any(|&slot| {
    !slot.is_null() && same_value_identity(unsafe { *slot }, weak_value)
  }) || st.persistent_handles.iter().any(|handle| {
    let slot = handle.slot;
    !handle.is_weak
      && !slot.is_null()
      && !std::ptr::addr_eq(slot, weak_slot)
      && same_value_identity(unsafe { *slot }, weak_value)
  })
}

fn collect_weak_handles(isolate: *mut RealIsolate) {
  if isolate.is_null() {
    return;
  }

  let weak_handles = {
    let st = iso_state(isolate);
    std::mem::take(&mut st.weak_handles)
  };

  let mut survivors = Vec::new();
  for weak in weak_handles {
    let is_live = if jsv_is_undefined(&weak.weak_ref) {
      is_strongly_reachable_from_handles(isolate, weak.handle)
    } else {
      unsafe { v82jsc_weak_ref_is_live(weak.weak_ref) }
    };
    if is_live {
      if !jsv_is_undefined(&weak.weak_ref) {
        let cell = weak.handle as *mut PersistentCell;
        let target = unsafe { v82jsc_weak_ref_target(weak.weak_ref) };
        if target.tag != JS_TAG_EXCEPTION {
          unsafe { (*cell).value = target };
        }
      }
      survivors.push(weak);
      continue;
    }

    unsafe { JS_FreeValue(weak.context, weak.weak_ref) };
    let mut info = WeakCallbackInfoShim {
      isolate,
      parameter: weak.parameter,
      second_pass: None,
    };
    unsafe { (weak.callback)(&info as *const _ as *const c_void) };
    if let Some(second_pass) = info.second_pass {
      unsafe { second_pass(&info as *const _ as *const c_void) };
    }
  }

  if !survivors.is_empty() {
    iso_state(isolate).weak_handles.extend(survivors);
  }
}

fn release_weak_handle_targets(isolate: *mut RealIsolate) {
  if isolate.is_null() {
    return;
  }
  for weak in &iso_state(isolate).weak_handles {
    if jsv_is_undefined(&weak.weak_ref) || weak.handle.is_null() {
      continue;
    }
    let cell = weak.handle as *mut PersistentCell;
    unsafe {
      JS_FreeValue((*cell).context, (*cell).value);
      (*cell).value = jsv_undefined();
    }
  }
}

fn run_gc_callbacks(
  isolate: *mut RealIsolate,
  callbacks: &[crate::quickjs::core::GcCallbackEntry],
) {
  let raw = crate::isolate::UnsafeRawIsolatePtr::from_real_ptr(isolate);
  for entry in callbacks {
    unsafe {
      (entry.callback)(
        raw,
        entry.gc_type_filter,
        crate::gc::GCCallbackFlags(0),
        entry.data,
      );
    }
  }
}

unsafe extern "C" {

  fn JS_ParseJSON(
    ctx: *mut JSContext,
    buf: *const c_char,
    buf_len: usize,
    filename: *const c_char,
  ) -> JSValue;
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__initialize_process(_platform: *mut c_void) {}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__shutdown_process() {}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__heap__enable_detached_garbage_collections_for_testing(
  _heap: *mut c_void,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__heap__collect_garbage_for_testing(
  _heap: *mut c_void,
  _stack_state: u8,
) {
  cppgc_collect_garbage();
}

#[derive(Clone, Copy)]
struct CppGcObject {
  ptr: usize,
  size: usize,
  align: usize,
  wrapper_key: Option<usize>,
  weak_wrapper: JSValue,
}

thread_local! {
  static CPPGC_OBJECTS: std::cell::RefCell<Vec<CppGcObject>> =
    const { std::cell::RefCell::new(Vec::new()) };
  static CPPGC_MEMBERS: std::cell::RefCell<HashMap<usize, usize>> =
    std::cell::RefCell::new(HashMap::new());
  static CPPGC_WEAK_MEMBERS: std::cell::RefCell<HashMap<usize, usize>> =
    std::cell::RefCell::new(HashMap::new());
  static CPPGC_TRACE_MARKS: std::cell::Cell<*mut HashSet<usize>> =
    const { std::cell::Cell::new(ptr::null_mut()) };
}

fn cppgc_member_construct(
  members: &std::cell::RefCell<HashMap<usize, usize>>,
  member: *mut c_void,
  obj: *mut c_void,
) {
  if member.is_null() {
    return;
  }
  unsafe { ptr::write_unaligned(member as *mut u32, 0) };
  let key = member as usize;
  if obj.is_null() {
    members.borrow_mut().remove(&key);
  } else {
    members.borrow_mut().insert(key, obj as usize);
  }
}

fn cppgc_member_get(
  members: &std::cell::RefCell<HashMap<usize, usize>>,
  member: *const c_void,
) -> *mut c_void {
  if member.is_null() {
    return ptr::null_mut();
  }
  members
    .borrow()
    .get(&(member as usize))
    .copied()
    .map(|ptr| ptr as *mut c_void)
    .unwrap_or(ptr::null_mut())
}

fn cppgc_mark_object(obj: *mut RustObj) {
  if obj.is_null() {
    return;
  }
  let ptr = obj as usize;
  CPPGC_TRACE_MARKS.with(|marks| {
    let marks_ptr = marks.get();
    if marks_ptr.is_null() {
      return;
    }
    let should_trace = unsafe {
      let marks = &mut *marks_ptr;
      marks.insert(ptr)
    };
    if should_trace {
      let mut visitor = 0usize;
      unsafe {
        rusty_v8_RustObj_trace(
          obj as *const RustObj,
          &mut visitor as *mut _ as *mut c_void,
        );
      }
    }
  });
}

fn cppgc_mark_wrapper_key(wrapper_key: usize) -> bool {
  let objects = CPPGC_OBJECTS.with(|objects| {
    objects
      .borrow()
      .iter()
      .filter(|object| object.wrapper_key == Some(wrapper_key))
      .map(|object| object.ptr)
      .collect::<Vec<_>>()
  });
  let found = !objects.is_empty();
  for object in objects {
    cppgc_mark_object(object as *mut RustObj);
  }
  found
}

unsafe fn new_native_weak_ref(ctx: *mut JSContext, target: JSValue) -> JSValue {
  let weak = unsafe { v82jsc_new_weak_ref(ctx, target) };
  if weak.tag == JS_TAG_EXCEPTION {
    let exception = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exception) };
    return jsv_undefined();
  }
  weak
}

unsafe fn cppgc_weak_wrapper_is_live(weak: JSValue) -> bool {
  if jsv_is_undefined(&weak) {
    // WeakRef is a standard QuickJS intrinsic. Be conservative if creating it
    // failed so a live native object can never become a dangling wrapper.
    return true;
  }
  unsafe { v82jsc_weak_ref_is_live(weak) }
}

fn cppgc_value_has_wrapper_marker(ctx: *mut JSContext, value: JSValue) -> bool {
  if ctx.is_null() || !jsv_is_object(&value) {
    return false;
  }
  let marker =
    unsafe { JS_GetPropertyStr(ctx, value, c"__qjs_cppgc_wrapped".as_ptr()) };
  if marker.tag == JS_TAG_EXCEPTION {
    return false;
  }
  let marked = unsafe { JS_ToBool(ctx, marker) != 0 };
  unsafe { JS_FreeValue(ctx, marker) };
  marked
}

fn cppgc_mark_js_value(ctx: *mut JSContext, value: JSValue) -> bool {
  if !jsv_is_object(&value) {
    return false;
  }
  if !cppgc_value_has_wrapper_marker(ctx, value) {
    return false;
  }
  let key = unsafe { value.u.ptr } as usize;
  if key != 0 {
    return cppgc_mark_wrapper_key(key);
  }
  false
}

unsafe fn cppgc_mark_js_graph(
  ctx: *mut JSContext,
  value: JSValue,
  depth: usize,
  seen_objects: &mut HashSet<usize>,
) {
  if ctx.is_null() || depth > HEAP_SNAPSHOT_MAX_DEPTH || !jsv_is_object(&value)
  {
    return;
  }
  let key = unsafe { value.u.ptr } as usize;
  if key == 0 || !seen_objects.insert(key) {
    return;
  }

  cppgc_mark_js_value(ctx, value);

  let mut ptab: *mut JSPropertyEnum = ptr::null_mut();
  let mut plen = 0u32;
  let flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY;
  let rc =
    unsafe { JS_GetOwnPropertyNames(ctx, &mut ptab, &mut plen, value, flags) };
  if rc != 0 || ptab.is_null() {
    return;
  }
  for index in 0..plen as usize {
    let atom = unsafe { (*ptab.add(index)).atom };
    let property = unsafe { JS_GetProperty(ctx, value, atom) };
    unsafe {
      cppgc_mark_js_graph(ctx, property, depth + 1, seen_objects);
      JS_FreeValue(ctx, property);
      JS_FreeAtom(ctx, atom);
    }
  }
  unsafe { js_free(ctx, ptab as *mut c_void) };
}

unsafe fn cppgc_mark_global_properties(ctx: *mut JSContext, global: JSValue) {
  let mut ptab: *mut JSPropertyEnum = ptr::null_mut();
  let mut plen = 0u32;
  let flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY;
  let rc =
    unsafe { JS_GetOwnPropertyNames(ctx, &mut ptab, &mut plen, global, flags) };
  if rc != 0 || ptab.is_null() {
    return;
  }
  for index in 0..plen as usize {
    let atom = unsafe { (*ptab.add(index)).atom };
    let property = unsafe { JS_GetProperty(ctx, global, atom) };
    cppgc_mark_js_value(ctx, property);
    unsafe {
      JS_FreeValue(ctx, property);
      JS_FreeAtom(ctx, atom);
    }
  }
  unsafe { js_free(ctx, ptab as *mut c_void) };
}

fn cppgc_mark_traced_reference(ref_: *const c_void) {
  if ref_.is_null() {
    return;
  }
  let slot = unsafe { (ref_ as *const usize).read_unaligned() };
  if slot == 0 {
    return;
  }
  let value = unsafe { *(slot as *const JSValue) };
  let ctx = stable_ctx();
  if ctx.is_null() {
    return;
  }
  let mut seen_objects = HashSet::new();
  unsafe { cppgc_mark_js_graph(ctx, value, 0, &mut seen_objects) };
}

fn cppgc_collect_garbage() {
  let ctx = stable_ctx();
  let mut marks = HashSet::new();
  CPPGC_TRACE_MARKS.with(|trace_marks| {
    let previous = trace_marks.replace(&mut marks);
    if !ctx.is_null() {
      let roots = CPPGC_OBJECTS.with(|objects| {
        objects
          .borrow()
          .iter()
          .filter(|object| {
            object.wrapper_key.is_some()
              && unsafe { cppgc_weak_wrapper_is_live(object.weak_wrapper) }
          })
          .map(|object| object.ptr)
          .collect::<Vec<_>>()
      });
      for root in roots {
        cppgc_mark_object(root as *mut RustObj);
      }
    }
    trace_marks.set(previous);
  });

  let mut dropped = Vec::new();
  CPPGC_OBJECTS.with(|objects| {
    let mut objects = objects.borrow_mut();
    let mut index = 0;
    while index < objects.len() {
      if marks.contains(&objects[index].ptr) {
        index += 1;
      } else {
        dropped.push(objects.remove(index));
      }
    }
  });

  for object in dropped {
    unsafe {
      if !ctx.is_null() {
        JS_FreeValue(ctx, object.weak_wrapper);
      }
      rusty_v8_RustObj_drop(object.ptr as *mut RustObj);
      if let Ok(layout) =
        std::alloc::Layout::from_size_align(object.size, object.align)
      {
        std::alloc::dealloc(object.ptr as *mut u8, layout);
      }
    }
  }
}

pub(crate) fn cppgc_register_wrapper(wrapper: JSValue, value: *const RustObj) {
  if value.is_null() || !jsv_is_object(&wrapper) {
    return;
  }
  let ctx = stable_ctx();
  if !ctx.is_null() {
    let marker = unsafe { JS_NewBool(ctx, 1) };
    let flags = JS_PROP_CONFIGURABLE_QJS
      | JS_PROP_WRITABLE_QJS
      | JS_PROP_HAS_CONFIGURABLE_QJS
      | JS_PROP_HAS_WRITABLE_QJS
      | JS_PROP_HAS_ENUMERABLE_QJS
      | JS_PROP_HAS_VALUE_QJS;
    unsafe {
      JS_DefinePropertyValueStr(
        ctx,
        wrapper,
        c"__qjs_cppgc_wrapped".as_ptr(),
        marker,
        flags,
      );
    }
  }
  let wrapper_key = unsafe { wrapper.u.ptr } as usize;
  let weak_wrapper = if ctx.is_null() {
    jsv_undefined()
  } else {
    unsafe { new_native_weak_ref(ctx, wrapper) }
  };
  CPPGC_OBJECTS.with(|objects| {
    if let Some(object) = objects
      .borrow_mut()
      .iter_mut()
      .find(|object| object.ptr == value as usize)
    {
      if !ctx.is_null() {
        unsafe { JS_FreeValue(ctx, object.weak_wrapper) };
      }
      object.wrapper_key = Some(wrapper_key);
      object.weak_wrapper = weak_wrapper;
    } else if !ctx.is_null() {
      unsafe { JS_FreeValue(ctx, weak_wrapper) };
    }
  });
}

pub(crate) fn cppgc_wrapper_matches(
  value: *mut RustObj,
  wrapper: JSValue,
) -> bool {
  if value.is_null() || !jsv_is_object(&wrapper) {
    return false;
  }
  let wrapper_key = unsafe { wrapper.u.ptr } as usize;
  CPPGC_OBJECTS.with(|objects| {
    objects.borrow().iter().any(|object| {
      object.ptr == value as usize
        && object.wrapper_key == Some(wrapper_key)
        && unsafe { cppgc_weak_wrapper_is_live(object.weak_wrapper) }
    })
  })
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Member__CONSTRUCT(
  member: *mut c_void,
  obj: *mut c_void,
) {
  CPPGC_MEMBERS.with(|members| cppgc_member_construct(members, member, obj));
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Member__DESTRUCT(member: *mut c_void) {
  if !member.is_null() {
    unsafe { ptr::write_unaligned(member as *mut u32, 0) };
    CPPGC_MEMBERS.with(|members| {
      members.borrow_mut().remove(&(member as usize));
    });
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Member__Get(member: *const c_void) -> *mut c_void {
  CPPGC_MEMBERS.with(|members| cppgc_member_get(members, member))
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Member__Assign(member: *mut c_void, obj: *mut c_void) {
  CPPGC_MEMBERS.with(|members| cppgc_member_construct(members, member, obj));
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakMember__CONSTRUCT(
  member: *mut c_void,
  obj: *mut c_void,
) {
  CPPGC_WEAK_MEMBERS
    .with(|members| cppgc_member_construct(members, member, obj));
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakMember__DESTRUCT(member: *mut c_void) {
  if !member.is_null() {
    unsafe { ptr::write_unaligned(member as *mut u32, 0) };
    CPPGC_WEAK_MEMBERS.with(|members| {
      members.borrow_mut().remove(&(member as usize));
    });
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakMember__Get(member: *const c_void) -> *mut c_void {
  CPPGC_WEAK_MEMBERS.with(|members| cppgc_member_get(members, member))
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakMember__Assign(
  member: *mut c_void,
  obj: *mut c_void,
) {
  CPPGC_WEAK_MEMBERS
    .with(|members| cppgc_member_construct(members, member, obj));
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Visitor__Trace__Member(
  _visitor: *mut c_void,
  member: *const c_void,
) {
  let obj = CPPGC_MEMBERS.with(|members| cppgc_member_get(members, member));
  cppgc_mark_object(obj as *mut RustObj);
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Visitor__Trace__WeakMember(
  _visitor: *mut c_void,
  _member: *const c_void,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__RequestGarbageCollectionForTesting(
  isolate: *mut RealIsolate,
  _type: usize,
) {
  // Best-effort: run the engine GC. Our cppgc shim doesn't reclaim native
  // wrappers, so the cppgc-specific collection assertions still won't hold,
  // but this satisfies the many `test_api` tests that just need a GC to run.
  if isolate.is_null() {
    return;
  }
  let st = iso_state(isolate);
  let prologue_callbacks = st.gc_prologue_callbacks.clone();
  run_gc_callbacks(isolate, &prologue_callbacks);
  release_weak_handle_targets(isolate);
  // Two passes: freeing a cppgc-wrapped object can release references held by
  // its native member (e.g. a wrapper wrapping another wrapper), and those only
  // become collectable after the first sweep + cppgc drop round.
  for _ in 0..2 {
    if !st.rt.is_null() {
      unsafe { JS_RunGC(st.rt) };
    }
    cppgc_collect_garbage();
  }
  release_external_string_memory(st);
  let epilogue_callbacks = st.gc_epilogue_callbacks.clone();
  run_gc_callbacks(isolate, &epilogue_callbacks);
  collect_weak_handles(isolate);
}

thread_local! {
    static DUMMY_CPP_HEAP: std::cell::Cell<*mut c_void> =
        const { std::cell::Cell::new(ptr::null_mut()) };
}

fn current_cpp_heap() -> *mut c_void {
  DUMMY_CPP_HEAP.with(|c| {
    let mut h = c.get();
    if h.is_null() {
      h = Box::into_raw(Box::new(0u64)) as *mut c_void;
      c.set(h);
    }
    h
  })
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__CppHeap__Create(
  _platform: *mut c_void,
  _marking_support: u8,
  _sweeping_support: u8,
) -> *mut c_void {
  current_cpp_heap()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__CppHeap__Terminate(_heap: *mut c_void) {}

#[unsafe(no_mangle)]
pub extern "C" fn v8__CppHeap__DELETE(_heap: *mut c_void) {}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__GetCppHeap(
  _isolate: *mut RealIsolate,
) -> *mut c_void {
  current_cpp_heap()
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__make_garbage_collectable(
  _heap: *mut c_void,
  additional_bytes: usize,
  align: usize,
) -> *mut c_void {
  const RUST_OBJ_SIZE: usize = 8;
  let size = RUST_OBJ_SIZE + additional_bytes;
  let align = align.max(8);
  let Ok(layout) = std::alloc::Layout::from_size_align(size, align) else {
    return ptr::null_mut();
  };
  let ptr = unsafe { std::alloc::alloc_zeroed(layout) as *mut c_void };
  if !ptr.is_null() {
    CPPGC_OBJECTS.with(|objects| {
      objects.borrow_mut().push(CppGcObject {
        ptr: ptr as usize,
        size,
        align,
        wrapper_key: None,
        weak_wrapper: jsv_undefined(),
      });
    });
  }
  ptr
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Persistent__CONSTRUCT(
  obj: *mut c_void,
) -> *mut c_void {
  Box::into_raw(Box::new(obj)) as *mut c_void
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Persistent__DESTRUCT(this: *mut c_void) {
  if !this.is_null() {
    unsafe { drop(Box::from_raw(this as *mut *mut c_void)) };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Persistent__Assign(
  this: *mut c_void,
  obj: *mut c_void,
) {
  if !this.is_null() {
    unsafe { *(this as *mut *mut c_void) = obj };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Persistent__Get(this: *const c_void) -> *mut c_void {
  if this.is_null() {
    return ptr::null_mut();
  }
  unsafe { *(this as *const *mut c_void) }
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakPersistent__CONSTRUCT(
  obj: *mut c_void,
) -> *mut c_void {
  cppgc__Persistent__CONSTRUCT(obj)
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakPersistent__DESTRUCT(this: *mut c_void) {
  cppgc__Persistent__DESTRUCT(this)
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakPersistent__Assign(
  this: *mut c_void,
  obj: *mut c_void,
) {
  cppgc__Persistent__Assign(this, obj)
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__WeakPersistent__Get(
  this: *const c_void,
) -> *mut c_void {
  cppgc__Persistent__Get(this)
}

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

  #[test]
  fn persistent_uses_an_independent_pointer_slot() {
    let mut first = 1u8;
    let mut second = 2u8;
    let first = (&mut first as *mut u8).cast::<c_void>();
    let second = (&mut second as *mut u8).cast::<c_void>();

    let persistent = cppgc__Persistent__CONSTRUCT(first);
    assert!(!persistent.is_null());
    assert_ne!(persistent, first);
    assert_eq!(cppgc__Persistent__Get(persistent), first);

    cppgc__Persistent__Assign(persistent, second);
    assert_eq!(cppgc__Persistent__Get(persistent), second);
    cppgc__Persistent__DESTRUCT(persistent);

    let weak = cppgc__WeakPersistent__CONSTRUCT(first);
    assert_eq!(cppgc__WeakPersistent__Get(weak), first);
    cppgc__WeakPersistent__Assign(weak, second);
    assert_eq!(cppgc__WeakPersistent__Get(weak), second);
    cppgc__WeakPersistent__DESTRUCT(weak);
  }

  #[test]
  #[cfg(feature = "link_quickjs")]
  fn collected_wrapper_does_not_match_stale_native_record() {
    unsafe {
      let rt = JS_NewRuntime();
      assert!(!rt.is_null());
      let ctx = JS_NewContext(rt);
      assert!(!ctx.is_null());

      let wrapper = JS_NewObject(ctx);
      let weak_wrapper = new_native_weak_ref(ctx, wrapper);
      assert!(!jsv_is_undefined(&weak_wrapper));
      let native = 8usize as *mut RustObj;
      CPPGC_OBJECTS.with(|objects| {
        objects.borrow_mut().push(CppGcObject {
          ptr: native as usize,
          size: 0,
          align: 8,
          wrapper_key: Some(wrapper.u.ptr as usize),
          weak_wrapper,
        });
      });

      assert!(cppgc_wrapper_matches(native, wrapper));
      JS_FreeValue(ctx, wrapper);
      JS_RunGC(rt);
      assert!(!cppgc_wrapper_matches(native, wrapper));

      CPPGC_OBJECTS.with(|objects| {
        objects
          .borrow_mut()
          .retain(|object| object.ptr != native as usize);
      });
      JS_FreeValue(ctx, weak_wrapper);
      JS_FreeContext(ctx);
      JS_FreeRuntime(rt);
    }
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn cppgc__Visitor__Trace__TracedReference(
  _visitor: *mut c_void,
  ref_: *const c_void,
) {
  cppgc_mark_traced_reference(ref_);
}

fn stable_ctx() -> *mut JSContext {
  let ctx = current_ctx();
  if !ctx.is_null() {
    return ctx;
  }
  let iso = current_iso();
  if iso.is_null() {
    return ptr::null_mut();
  }
  let st = iso_state(iso);
  st.contexts.last().copied().unwrap_or(st.ctx)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Global__New(
  _isolate: *mut RealIsolate,
  data: *const Data,
) -> *const Data {
  if data.is_null() {
    return ptr::null();
  }

  if super::core::is_non_value_handle(data) {
    return data;
  }
  let ctx = stable_ctx();
  if ctx.is_null() {
    return ptr::null();
  }

  let v = jsval_of(data);
  let cell = Box::into_raw(Box::new(PersistentCell {
    value: unsafe { JS_DupValue(ctx, v) },
    context: ctx,
    isolate: _isolate,
  }));
  let slot = unsafe { &mut (*cell).value } as *mut JSValue;
  if !_isolate.is_null() {
    let st = iso_state(_isolate);
    st.persistent_handles.push(PersistentHandle {
      slot,
      is_weak: false,
    });
    st.global_handles.fetch_add(1, Ordering::SeqCst);
  }
  slot as *const Data
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Global__NewWeak(
  isolate: *mut RealIsolate,
  data: *const Data,
  parameter: *const c_void,
  callback: unsafe extern "C" fn(*const c_void),
) -> *const Data {
  let handle = v8__Global__New(isolate, data);
  let mut weak_ref = jsv_undefined();
  let mut context = ptr::null_mut();
  if !handle.is_null() && !isolate.is_null() {
    let st = iso_state(isolate);
    if let Some(persistent) =
      st.persistent_handles.iter_mut().find(|persistent| {
        std::ptr::addr_eq(persistent.slot, handle as *const JSValue)
      })
    {
      persistent.is_weak = true;
      let cell = handle as *const PersistentCell;
      context = unsafe { (*cell).context };
      weak_ref = unsafe { new_native_weak_ref(context, (*cell).value) };
    }
    st.weak_handles.push(crate::quickjs::core::WeakHandle {
      handle,
      parameter,
      callback,
      weak_ref,
      context,
    });
  }
  handle
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Global__Reset(data: *const Data) {
  if data.is_null() {
    return;
  }

  if super::core::is_non_value_handle(data) {
    return;
  }

  let cell = data as *mut PersistentCell;
  let iso = unsafe { (*cell).isolate };
  if !iso.is_null() {
    let st = iso_state(iso);
    if let Some(index) =
      st.weak_handles.iter().position(|weak| weak.handle == data)
    {
      let weak = st.weak_handles.remove(index);
      unsafe { JS_FreeValue(weak.context, weak.weak_ref) };
    }
    st.persistent_handles
      .retain(|handle| !std::ptr::addr_eq(handle.slot, data as *const JSValue));
    if st.global_handles.load(Ordering::SeqCst) > 0 {
      st.global_handles.fetch_sub(1, Ordering::SeqCst);
    }
  }

  unsafe {
    let ctx = (*cell).context;
    let v = (*cell).value;
    if !ctx.is_null() {
      JS_FreeValue(ctx, v);
    }
    drop(Box::from_raw(cell));
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__TracedReference__CONSTRUCT(this: *mut usize) {
  if !this.is_null() {
    unsafe { this.write_unaligned(0) };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__TracedReference__DESTRUCT(this: *mut usize) {
  if this.is_null() {
    return;
  }
  unsafe {
    let cell = this.read_unaligned() as *mut JSValue;
    if !cell.is_null() {
      let v = *cell;
      let ctx = stable_ctx();
      if !ctx.is_null() {
        JS_FreeValue(ctx, v);
      }
      drop(Box::from_raw(cell));
      this.write_unaligned(0);
    }
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__TracedReference__Reset(
  this: *mut usize,
  _isolate: *mut RealIsolate,
  data: *const Data,
) {
  if this.is_null() {
    return;
  }
  let ctx = stable_ctx();
  unsafe {
    let old = this.read_unaligned() as *mut JSValue;
    if !old.is_null() {
      if !ctx.is_null() {
        JS_FreeValue(ctx, *old);
      }
      drop(Box::from_raw(old));
      this.write_unaligned(0);
    }
    if data.is_null() || ctx.is_null() {
      return;
    }

    if super::core::is_non_value_handle(data) {
      return;
    }
    let dup = JS_DupValue(ctx, jsval_of(data));
    if std::env::var_os("QJS_DEBUG_TR").is_some() {
      eprintln!(
        "[QJS TracedRef::Reset] store tag={} ptr={:?}",
        dup.tag, dup.u.ptr
      );
    }
    let cell = Box::into_raw(Box::new(dup));
    this.write_unaligned(cell as usize);
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__TracedReference__Get(
  this: *const usize,
  _isolate: *mut RealIsolate,
) -> *const Data {
  if this.is_null() {
    return ptr::null();
  }
  let slot = unsafe { this.read_unaligned() };
  if slot == 0 {
    if std::env::var_os("QJS_DEBUG_TR").is_some() {
      eprintln!("[QJS TracedRef::Get] EMPTY");
    }
    return ptr::null();
  }
  if std::env::var_os("QJS_DEBUG_TR").is_some() {
    let v = unsafe { *(slot as *const JSValue) };
    eprintln!("[QJS TracedRef::Get] tag={} ptr={:?}", v.tag, unsafe {
      v.u.ptr
    });
  }

  slot as *const Data
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__JSON__Parse(
  context: *const Context,
  json_string: *const V8String,
) -> *const Value {
  if context.is_null() || json_string.is_null() {
    return ptr::null();
  }
  let ctx = ctx_of(context);
  unsafe {
    let mut len: usize = 0;
    let cstr = JS_ToCStringLen(ctx, &mut len, jsval_of(json_string));
    if cstr.is_null() {
      return ptr::null();
    }
    let fname = c"<json>";
    let parsed = JS_ParseJSON(ctx, cstr, len, fname.as_ptr());
    let input = std::slice::from_raw_parts(cstr as *const u8, len);
    let invalid_leading_token = input
      .iter()
      .copied()
      .find(|byte| !byte.is_ascii_whitespace())
      .filter(|byte| {
        !matches!(
          byte,
          b'{' | b'[' | b'"' | b't' | b'f' | b'n' | b'-' | b'0'..=b'9'
        )
      });
    let input_preview = invalid_leading_token.map(|token| {
      let preview_len = input.len().min(10);
      let preview = std::string::String::from_utf8_lossy(&input[..preview_len]);
      let suffix = if input.len() > preview_len { "..." } else { "" };
      format!(
        "Unexpected token '{}', {:?}{} is not valid JSON",
        char::from(token).escape_default(),
        preview,
        suffix,
      )
    });
    JS_FreeCString(ctx, cstr);
    if parsed.tag == JS_TAG_EXCEPTION {
      let exception = JS_GetException(ctx);
      if let Some(message) = input_preview
        && let Ok(message) = std::ffi::CString::new(message)
      {
        JS_SetPropertyStr(
          ctx,
          exception,
          c"message".as_ptr(),
          JS_NewString(ctx, message.as_ptr()),
        );
      }
      v82jsc_clear_error_backtrace(ctx, exception);
      JS_Throw(ctx, exception);
      return ptr::null();
    }

    intern::<Value>(parsed)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Proxy__GetHandler(this: *const c_void) -> *const Value {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  let v = unsafe { JS_GetProxyHandler(ctx, jsval_of(this as *const Value)) };
  if v.tag == JS_TAG_EXCEPTION {
    let exc = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exc) };
    return ptr::null();
  }
  intern::<Value>(v)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Proxy__GetTarget(this: *const c_void) -> *const Value {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  let v = unsafe { JS_GetProxyTarget(ctx, jsval_of(this as *const Value)) };
  if v.tag == JS_TAG_EXCEPTION {
    let exc = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exc) };
    return ptr::null();
  }
  intern::<Value>(v)
}

#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct RawStartupDataAbi {
  data: *const c_char,
  raw_size: std::os::raw::c_int,
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__CONSTRUCT(
  buf: *mut c_void,
  params: *const c_void,
) {
  // Snapshots are unsupported on quickjs (no heap serializer); the creator is
  // just a plain isolate. CreateBlob returns an empty blob and the embedder
  // falls back to New-init.
  let iso = crate::quickjs::core::v8__Isolate__New(params);
  if !iso.is_null() {
    crate::quickjs::core::iso_state(iso).is_snapshot_creator = true;
  }
  crate::quickjs::core::v8__Isolate__Enter(iso);
  if !buf.is_null() {
    unsafe { *(buf as *mut *mut RealIsolate) = iso };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__DESTRUCT(this: *mut c_void) {
  if this.is_null() {
    return;
  }
  let slot = this as *mut *mut RealIsolate;
  let iso = unsafe { *slot };
  if iso.is_null() {
    return;
  }
  if crate::quickjs::core::v8__Isolate__GetCurrent() == iso {
    crate::quickjs::core::v8__Isolate__Exit(iso);
  }
  crate::quickjs::core::v8__Isolate__Dispose(iso);
  unsafe { *slot = ptr::null_mut() };
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__GetIsolate(
  this: *const c_void,
) -> *mut c_void {
  if !this.is_null() {
    let iso = unsafe { *(this as *const *mut RealIsolate) };
    if !iso.is_null() {
      return iso as *mut c_void;
    }
  }
  current_iso() as *mut c_void
}

fn creator_iso(this: *const c_void) -> *mut RealIsolate {
  if !this.is_null() {
    let iso = unsafe { *(this as *const *mut RealIsolate) };
    if !iso.is_null() {
      return iso;
    }
  }
  current_iso()
}

fn omit_unchanged_context_global(
  st: &crate::quickjs::core::IsoState,
  context: usize,
  capture: &mut super::snapshot::ContextSnapshot,
) {
  let Some(baseline) = st.snap_context_baselines.get(&context) else {
    return;
  };
  let Some(current) = capture.global_object.as_deref() else {
    return;
  };
  let Some(baseline) = baseline.global_object.as_deref() else {
    return;
  };
  if current == baseline {
    capture.global_object = None;
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__CreateBlob(
  this: *mut c_void,
  _function_code_handling: u32,
) -> RawStartupDataAbi {
  let iso = creator_iso(this);
  if iso.is_null() {
    return RawStartupDataAbi {
      data: ptr::null(),
      raw_size: 0,
    };
  }
  let st = crate::quickjs::core::iso_state(iso);
  let default_context =
    st.snap_default_context_capture.as_ref().map(|capture| {
      Arc::new(finalize_context_snapshot(
        st,
        st.snap_default_context,
        capture,
      ))
    });
  let contexts = st
    .snap_context_captures
    .iter()
    .enumerate()
    .map(|(index, capture)| {
      Arc::new(finalize_context_snapshot(
        st,
        st.snap_contexts.get(index).copied(),
        capture,
      ))
    })
    .collect();
  let blob = super::snapshot::SnapshotBlob {
    default_context,
    contexts,
    isolate_data: st
      .snap_isolate_data
      .iter()
      .cloned()
      .map(Into::into)
      .collect(),
  };
  let (data, raw_size) =
    super::snapshot::leak_blob(super::snapshot::encode_blob(&blob));
  RawStartupDataAbi {
    data: data as *const c_char,
    raw_size,
  }
}

fn finalize_context_snapshot(
  st: &crate::quickjs::core::IsoState,
  context: Option<usize>,
  capture: &super::snapshot::ContextSnapshot,
) -> super::snapshot::ContextSnapshot {
  let Some(context) = context else {
    return capture.clone();
  };
  let context_data = st
    .snap_context_data
    .get(&context)
    .cloned()
    .unwrap_or_default();
  let context_values = st
    .snap_context_data_values
    .get(&context)
    .cloned()
    .unwrap_or_default();
  if context_values.iter().any(Option::is_some) {
    super::snapshot::capture_context_with_data_roots(
      context as *mut JSContext,
      &st.external_references,
      &context_data,
      &context_values,
    )
  } else {
    // Re-capture at blob time: V8 serializes contexts in CreateBlob, so
    // mutations made after SetDefaultContext/AddContext (e.g. globals added
    // once the context is set) must be part of the snapshot. The capture taken
    // when the context was registered only serves as a fallback below.
    let mut fresh = super::snapshot::capture_context(
      context as *mut JSContext,
      &st.external_references,
      &[],
    );
    omit_unchanged_context_global(st, context, &mut fresh);
    fresh.context_data = context_data.into_iter().map(Into::into).collect();
    fresh.context_data_refs = vec![false; fresh.context_data.len()];
    fresh
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__SetDefaultContext(
  this: *mut c_void,
  context: *const Context,
) {
  let iso = creator_iso(this);
  if iso.is_null() {
    return;
  }
  let qctx = ctx_of(context);
  let external_references = crate::quickjs::core::iso_state(iso)
    .external_references
    .clone();
  let mut capture =
    super::snapshot::capture_context(qctx, &external_references, &[]);
  let st = crate::quickjs::core::iso_state(iso);
  omit_unchanged_context_global(st, qctx as usize, &mut capture);
  st.snap_default_context = Some(qctx as usize);
  st.snap_default_context_capture = Some(capture);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__AddContext(
  this: *mut c_void,
  context: *const Context,
) -> usize {
  let iso = creator_iso(this);
  if iso.is_null() {
    return 0;
  }
  let qctx = ctx_of(context);
  let external_references = crate::quickjs::core::iso_state(iso)
    .external_references
    .clone();
  let mut capture =
    super::snapshot::capture_context(qctx, &external_references, &[]);
  let st = crate::quickjs::core::iso_state(iso);
  omit_unchanged_context_global(st, qctx as usize, &mut capture);
  let n = st.snap_contexts.len();
  st.snap_contexts.push(qctx as usize);
  st.snap_context_captures.push(capture);
  st.iso_added_contexts += 1;
  n
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__AddData_to_isolate(
  this: *mut c_void,
  data: *const Data,
) -> usize {
  let iso = creator_iso(this);
  if iso.is_null() || data.is_null() {
    return 0;
  }
  let ctx = current_ctx();
  let external_refs = crate::quickjs::core::iso_state(iso)
    .external_references
    .clone();
  let bytes = if super::function::template_kind(data as *const c_void)
    == Some(super::function::TemplKind::Func)
  {
    super::snapshot::serialize_function_template(
      ctx,
      data as *const FunctionTemplate,
      &external_refs,
    )
  } else {
    super::snapshot::serialize_value_with_refs(
      ctx,
      jsval_of(data),
      &external_refs,
    )
  }
  .unwrap_or_default();
  let st = crate::quickjs::core::iso_state(iso);
  let n = st.snap_isolate_data.len();
  st.snap_isolate_data.push(bytes);
  st.iso_data_count += 1;
  n
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__SnapshotCreator__AddData_to_context(
  this: *mut c_void,
  context: *const Context,
  data: *const Data,
) -> usize {
  let iso = creator_iso(this);
  if iso.is_null() || data.is_null() {
    return 0;
  }
  let ctx = ctx_of(context);
  let external_refs = crate::quickjs::core::iso_state(iso)
    .external_references
    .clone();
  let is_function_template =
    super::function::template_kind(data as *const c_void)
      == Some(super::function::TemplKind::Func);
  let function_template_proto = if is_function_template {
    super::function::snapshot_function_template_info(
      data as *const FunctionTemplate,
    )
    .and_then(|info| info.cached_proto)
  } else {
    None
  };
  let val = (!is_function_template).then(|| jsval_of(data));
  let bytes = if is_function_template {
    super::snapshot::serialize_function_template(
      ctx,
      data as *const FunctionTemplate,
      &external_refs,
    )
  } else {
    super::snapshot::serialize_value_with_refs(
      ctx,
      val.unwrap(),
      &external_refs,
    )
  };
  let graph_value = if let Some(proto) = function_template_proto {
    Some(unsafe { JS_DupValue(ctx, proto) })
  } else {
    val.and_then(|value| {
      super::snapshot::duplicate_graph_serializable_value(
        ctx,
        value,
        &external_refs,
      )
    })
  };
  if std::env::var_os("QJS_DEBUG_SNAPSHOT").is_some() {
    let Some(val) = val else {
      eprintln!(
        "[qjs snapshot] AddData_to_context FunctionTemplate ser={}",
        bytes.is_some(),
      );
      return store_context_snapshot_data(
        iso,
        ctx,
        bytes.unwrap_or_default(),
        graph_value,
      );
    };
    let preview = unsafe {
      let mut l = 0usize;
      let s = JS_ToCStringLen(ctx, &mut l, val);
      let out = if s.is_null() {
        "<unstringifiable>".to_string()
      } else {
        let b = std::slice::from_raw_parts(s as *const u8, l.min(80));
        let c = String::from_utf8_lossy(b).into_owned();
        JS_FreeCString(ctx, s);
        c
      };
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      out
    };
    eprintln!(
      "[qjs snapshot] AddData_to_context tag={} ser={} preview={preview}",
      val.tag,
      bytes.is_some(),
    );
  }
  let bytes = bytes.unwrap_or_default();
  store_context_snapshot_data(iso, ctx, bytes, graph_value)
}

fn store_context_snapshot_data(
  iso: *mut RealIsolate,
  ctx: *mut JSContext,
  bytes: Vec<u8>,
  graph_value: Option<JSValue>,
) -> usize {
  let st = crate::quickjs::core::iso_state(iso);
  let n = st.ctx_data_counts.entry(ctx as usize).or_insert(0);
  let idx = *n;
  *n += 1;
  st.snap_context_data
    .entry(ctx as usize)
    .or_default()
    .push(bytes);
  st.snap_context_data_values
    .entry(ctx as usize)
    .or_default()
    .push(graph_value);
  idx
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__StartupData__CanBeRehashed(_this: *const c_void) -> bool {
  false
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__StartupData__IsValid(_this: *const c_void) -> bool {
  // No snapshot support on quickjs: never a valid startup blob.
  false
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__StartupData__data__DELETE(this: *const c_char) {
  super::snapshot::free_blob(this as *const u8);
}

// ICU common-data loader (vendored rusty_v8 `icu::set_common_data_77`). QuickJS
// brings its own ICU/Intl, so we never actually *load* V8's blob — but we do
// validate its header exactly like ICU's `udata_setCommonData`: a real ICU data
// file (icudtl.dat) begins with `headerSize:u16` followed by the format magic
// bytes 0xDA 0x27. The test harness ships a blob with a valid header, so setup's
// `set_common_data_77(<icudtl.dat>)` returns Ok; a garbage blob — e.g. the
// `[1, 2, 3, 0, …]` from `icu_set_common_data_fail` — has the wrong magic and
// must return `U_INVALID_FORMAT_ERROR`. No length crosses this C ABI, so we read
// only the 4 header bytes every real caller is guaranteed to provide.
#[unsafe(no_mangle)]
pub extern "C" fn udata_setCommonData_77(
  data: *const u8,
  error_code: *mut i32,
) {
  // ICU's UErrorCode for a bad/unrecognized data header.
  const U_INVALID_FORMAT_ERROR: i32 = 3;
  let valid = !data.is_null()
    && unsafe {
      // ICU DataHeader: bytes [2] and [3] are the magic 0xDA 0x27.
      *data.add(2) == 0xDA && *data.add(3) == 0x27
    };
  if !error_code.is_null() {
    unsafe {
      *error_code = if valid { 0 } else { U_INVALID_FORMAT_ERROR };
    }
  }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn v8__Task__Run(task: *mut c_void) {
  unsafe { super::init::run_foreground_task(task) };
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn v8__Task__DELETE(task: *mut c_void) {
  unsafe { super::init::delete_foreground_task(task) };
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__IdleTask__Run(
  _task: *mut c_void,
  _deadline_in_seconds: f64,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__IdleTask__DELETE(_task: *mut c_void) {}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WeakCallbackInfo__GetIsolate(
  this: *const c_void,
) -> *mut c_void {
  if this.is_null() {
    return current_iso() as *mut c_void;
  }
  unsafe { (*(this as *const WeakCallbackInfoShim)).isolate as *mut c_void }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WeakCallbackInfo__GetParameter(
  this: *const c_void,
) -> *mut c_void {
  if this.is_null() {
    return ptr::null_mut();
  }
  unsafe { (*(this as *const WeakCallbackInfoShim)).parameter as *mut c_void }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WeakCallbackInfo__SetSecondPassCallback(
  this: *const c_void,
  callback: unsafe extern "C" fn(*const c_void),
) {
  if this.is_null() {
    return;
  }
  unsafe {
    (*(this as *mut WeakCallbackInfoShim)).second_pass = Some(callback);
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmStreaming__Unpack(
  _isolate: *mut c_void,
  value: *const Value,
  that: *mut c_void,
) {
  super::wasm::streaming_unpack(value, that);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmStreaming__shared_ptr_DESTRUCT(this: *mut c_void) {
  super::wasm::streaming_shared_ptr_destruct(this);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmStreaming__OnBytesReceived(
  this: *mut c_void,
  data: *const u8,
  len: usize,
) {
  super::wasm::streaming_on_bytes_received(this, data, len);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmStreaming__Finish(
  this: *mut c_void,
  callback: Option<unsafe extern "C" fn(*mut c_void)>,
) {
  super::wasm::streaming_finish(this, callback);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmStreaming__Abort(
  this: *mut c_void,
  exception: *const Value,
) {
  super::wasm::streaming_abort(this, exception);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmStreaming__SetUrl(
  this: *mut c_void,
  url: *const c_char,
  len: usize,
) {
  super::wasm::streaming_set_url(this, url, len);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleObject__FromCompiledModule(
  isolate: *mut c_void,
  compiled_module: *const c_void,
) -> *const c_void {
  super::wasm::module_object_from_compiled_module(isolate, compiled_module)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleObject__GetCompiledModule(
  this: *const c_void,
) -> *mut c_void {
  super::wasm::module_object_get_compiled_module(this)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleObject__Compile(
  isolate: *mut RealIsolate,
  wire_bytes_data: *const u8,
  length: usize,
) -> *const Object {
  if isolate.is_null() || wire_bytes_data.is_null() {
    return ptr::null();
  }
  let st = iso_state(isolate);
  let ctx = st.contexts.last().copied().unwrap_or(st.ctx);
  if ctx.is_null() {
    return ptr::null();
  }
  let bytes = unsafe { std::slice::from_raw_parts(wire_bytes_data, length) };
  let v = unsafe { super::wasm::compile_module_object(ctx, bytes) };
  if v.tag == JS_TAG_EXCEPTION {
    let exc = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exc) };
    return ptr::null();
  }
  intern::<Object>(v)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__CompiledWasmModule__DELETE(this: *mut c_void) {
  super::wasm::compiled_module_delete(this);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleCompilation__NEW() -> *mut c_void {
  super::wasm::module_compilation_new()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleCompilation__DELETE(this: *mut c_void) {
  super::wasm::module_compilation_delete(this);
}

unsafe extern "C" {
  fn JS_JSONStringify(
    ctx: *mut JSContext,
    obj: JSValue,
    replacer: JSValue,
    space0: JSValue,
  ) -> JSValue;
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__JSON__Stringify(
  context: *const Context,
  json_object: *const Value,
) -> *const V8String {
  let ctx = ctx_of(context);
  if ctx.is_null() || json_object.is_null() {
    return ptr::null();
  }
  unsafe {
    let s = JS_JSONStringify(
      ctx,
      jsval_of(json_object),
      jsv_undefined(),
      jsv_undefined(),
    );
    if s.tag == JS_TAG_EXCEPTION {
      // Leave the exception PENDING (v8's JSON::Stringify returns Empty and
      // keeps it set) so the caller's TryCatch can read it — e.g. console's
      // `%j` distinguishes circular-reference TypeErrors from real ones.
      // Clearing it here made TryCatch::Exception() return undefined.
      return ptr::null();
    }
    intern::<V8String>(s)
  }
}

unsafe fn call_unary_closure(
  ctx: *mut JSContext,
  src: &[u8],
  obj: JSValue,
) -> JSValue {
  unsafe {
    let f = JS_Eval(
      ctx,
      src.as_ptr() as *const c_char,
      src.len() - 1,
      c"<map-set>".as_ptr(),
      JS_EVAL_TYPE_GLOBAL,
    );
    if f.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return jsv_exception();
    }
    let mut args = [JS_DupValue(ctx, obj)];
    let r = JS_Call(ctx, f, jsv_undefined(), 1, args.as_mut_ptr());
    JS_FreeValue(ctx, f);
    JS_FreeValue(ctx, args[0]);
    r
  }
}

fn map_set_size(v: *const Object) -> usize {
  let ctx = current_ctx();
  if ctx.is_null() || v.is_null() {
    return 0;
  }
  unsafe {
    let sz = JS_GetPropertyStr(ctx, jsval_of(v), c"size".as_ptr());
    if sz.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return 0;
    }
    let mut n: i64 = 0;
    let rc = JS_ToInt64(ctx, &mut n, sz);
    JS_FreeValue(ctx, sz);
    if rc < 0 {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return 0;
    }
    n.max(0) as usize
  }
}

fn mb(b: bool) -> crate::support::MaybeBool {
  if b {
    crate::support::MaybeBool::JustTrue
  } else {
    crate::support::MaybeBool::JustFalse
  }
}

// Invoke `this.<method>(args...)` and return the raw result JSValue (the caller
// must `JS_FreeValue` it) or `jsv_exception()` when the method is missing or
// threw (the pending exception is cleared). Used to back the Map/Set C-ABI on
// top of QuickJS's native Map/Set prototype methods.
unsafe fn call_collection_method(
  ctx: *mut JSContext,
  this: JSValue,
  method: *const c_char,
  args: &mut [JSValue],
) -> JSValue {
  unsafe {
    let f = JS_GetPropertyStr(ctx, this, method);
    if !JS_IsFunction(ctx, f) {
      JS_FreeValue(ctx, f);
      return jsv_exception();
    }
    let r = JS_Call(
      ctx,
      f,
      this,
      args.len() as std::os::raw::c_int,
      args.as_mut_ptr(),
    );
    JS_FreeValue(ctx, f);
    if r.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
    }
    r
  }
}

// `new <ctor_name>()` against the isolate's active context (Map / Set).
fn new_builtin(isolate: *mut RealIsolate, ctor_name: *const c_char) -> JSValue {
  if isolate.is_null() {
    return jsv_exception();
  }
  let st = iso_state(isolate);
  let ctx = st.contexts.last().copied().unwrap_or(st.ctx);
  if ctx.is_null() {
    return jsv_exception();
  }
  unsafe {
    let global = JS_GetGlobalObject(ctx);
    let ctor = JS_GetPropertyStr(ctx, global, ctor_name);
    JS_FreeValue(ctx, global);
    if !JS_IsConstructor(ctx, ctor) {
      JS_FreeValue(ctx, ctor);
      return jsv_exception();
    }
    let v = JS_CallConstructor(ctx, ctor, 0, ptr::null_mut());
    JS_FreeValue(ctx, ctor);
    if v.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return jsv_exception();
    }
    v
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__Size(map: *const crate::Map) -> usize {
  map_set_size(map as *const Object)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__Size(set: *const crate::Set) -> usize {
  map_set_size(set as *const Object)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__As__Array(
  this: *const crate::Map,
) -> *const crate::Array {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }

  const SRC: &[u8] =
        b"(function(m){var r=[];m.forEach(function(v,k){r.push(k);r.push(v);});return r;})\0";
  let arr = unsafe { call_unary_closure(ctx, SRC, jsval_of(this)) };
  if arr.tag == JS_TAG_EXCEPTION {
    let exc = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exc) };
    return ptr::null();
  }
  intern::<crate::Array>(arr)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__As__Array(
  this: *const crate::Set,
) -> *const crate::Array {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  const SRC: &[u8] =
    b"(function(s){var r=[];s.forEach(function(v){r.push(v);});return r;})\0";
  let arr = unsafe { call_unary_closure(ctx, SRC, jsval_of(this)) };
  if arr.tag == JS_TAG_EXCEPTION {
    let exc = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exc) };
    return ptr::null();
  }
  intern::<crate::Array>(arr)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__New(isolate: *mut RealIsolate) -> *const crate::Set {
  if isolate.is_null() {
    return ptr::null();
  }
  let st = iso_state(isolate);
  let ctx = st.contexts.last().copied().unwrap_or(st.ctx);
  if ctx.is_null() {
    return ptr::null();
  }
  unsafe {
    let global = JS_GetGlobalObject(ctx);
    let ctor = JS_GetPropertyStr(ctx, global, c"Set".as_ptr());
    JS_FreeValue(ctx, global);
    if !JS_IsConstructor(ctx, ctor) {
      JS_FreeValue(ctx, ctor);
      return ptr::null();
    }
    let v = JS_CallConstructor(ctx, ctor, 0, ptr::null_mut());
    JS_FreeValue(ctx, ctor);
    if v.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return ptr::null();
    }
    intern::<crate::Set>(v)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__Add(
  this: *const crate::Set,
  context: *const Context,
  key: *const Value,
) -> *const crate::Set {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  unsafe {
    let add = JS_GetPropertyStr(ctx, jsval_of(this), c"add".as_ptr());
    if !JS_IsFunction(ctx, add) {
      JS_FreeValue(ctx, add);
      return ptr::null();
    }
    let mut args = [JS_DupValue(ctx, jsval_of(key))];
    let r = JS_Call(ctx, add, jsval_of(this), 1, args.as_mut_ptr());
    JS_FreeValue(ctx, add);
    JS_FreeValue(ctx, args[0]);
    if r.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return ptr::null();
    }
    JS_FreeValue(ctx, r);

    intern::<crate::Set>(JS_DupValue(ctx, jsval_of(this)))
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Date__New(
  context: *const Context,
  value: f64,
) -> *const crate::Date {
  let ctx = ctx_of(context);
  if ctx.is_null() {
    return ptr::null();
  }
  unsafe {
    let global = JS_GetGlobalObject(ctx);
    let ctor = JS_GetPropertyStr(ctx, global, c"Date".as_ptr());
    JS_FreeValue(ctx, global);
    if !JS_IsConstructor(ctx, ctor) {
      JS_FreeValue(ctx, ctor);
      return ptr::null();
    }
    let mut args = [JS_NewFloat64(ctx, value)];
    let v = JS_CallConstructor(ctx, ctor, 1, args.as_mut_ptr());
    JS_FreeValue(ctx, ctor);
    if v.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return ptr::null();
    }
    intern::<crate::Date>(v)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Date__ValueOf(this: *const crate::Date) -> f64 {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return 0.0;
  }
  unsafe {
    let vo = JS_GetPropertyStr(ctx, jsval_of(this), c"valueOf".as_ptr());
    if !JS_IsFunction(ctx, vo) {
      JS_FreeValue(ctx, vo);
      return 0.0;
    }
    let r = JS_Call(ctx, vo, jsval_of(this), 0, ptr::null_mut());
    JS_FreeValue(ctx, vo);
    if r.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return 0.0;
    }
    let mut n: f64 = 0.0;
    JS_ToFloat64(ctx, &mut n, r);
    JS_FreeValue(ctx, r);
    n
  }
}

thread_local! {
    static EMBEDDER_DATA: std::cell::RefCell<HashMap<usize, Vec<JSValue>>> =
        std::cell::RefCell::new(HashMap::new());
    static SECURITY_TOKEN: std::cell::RefCell<HashMap<usize, JSValue>> =
        std::cell::RefCell::new(HashMap::new());
}

unsafe extern "C" {
  fn JS_IsStrictEqual(ctx: *mut JSContext, op1: JSValue, op2: JSValue) -> bool;
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Context__SetEmbedderData(
  this: *const Context,
  index: std::os::raw::c_int,
  value: *const Value,
) {
  let ctx = ctx_of(this);
  if ctx.is_null() || index < 0 {
    return;
  }
  let owned = unsafe { JS_DupValue(ctx, jsval_of(value)) };
  EMBEDDER_DATA.with(|m| {
    let mut map = m.borrow_mut();
    let slots = map.entry(ctx as usize).or_default();
    let idx = index as usize;
    while slots.len() <= idx {
      slots.push(jsv_undefined());
    }
    let old = slots[idx];
    if old.tag < 0 {
      unsafe { JS_FreeValue(ctx, old) };
    }
    slots[idx] = owned;
  });
}

/// Snapshot support: borrow every embedder-data value slot of `ctx`.
/// `None` marks unset (undefined) slots.
pub(crate) fn embedder_data_snapshot(
  ctx: *mut JSContext,
) -> Vec<Option<JSValue>> {
  EMBEDDER_DATA.with(|m| {
    m.borrow()
      .get(&(ctx as usize))
      .map(|slots| {
        slots
          .iter()
          .map(|v| if jsv_is_undefined(v) { None } else { Some(*v) })
          .collect()
      })
      .unwrap_or_default()
  })
}

/// Snapshot support: install a replayed value into an embedder-data slot.
/// Dups `value` (caller keeps its refcount).
pub(crate) fn set_embedder_data_raw(
  ctx: *mut JSContext,
  index: usize,
  value: JSValue,
) {
  let owned = unsafe { JS_DupValue(ctx, value) };
  EMBEDDER_DATA.with(|m| {
    let mut map = m.borrow_mut();
    let slots = map.entry(ctx as usize).or_default();
    while slots.len() <= index {
      slots.push(jsv_undefined());
    }
    let old = slots[index];
    if old.tag < 0 {
      unsafe { JS_FreeValue(ctx, old) };
    }
    slots[index] = owned;
  });
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Context__GetEmbedderData(
  this: *const Context,
  index: std::os::raw::c_int,
) -> *const Value {
  let ctx = ctx_of(this);
  if ctx.is_null() || index < 0 {
    return ptr::null();
  }
  let found = EMBEDDER_DATA.with(|m| {
    m.borrow()
      .get(&(ctx as usize))
      .and_then(|slots| slots.get(index as usize).copied())
  });
  let h = match found {
    Some(v) => intern_dup::<Value>(ctx, v),
    None => intern::<Value>(jsv_undefined()),
  };
  h
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Context__SetSecurityToken(
  this: *const Context,
  value: *const Value,
) {
  let ctx = ctx_of(this);
  if ctx.is_null() {
    return;
  }
  let owned = unsafe { JS_DupValue(ctx, jsval_of(value)) };
  SECURITY_TOKEN.with(|m| {
    if let Some(old) = m.borrow_mut().insert(ctx as usize, owned) {
      if old.tag < 0 {
        unsafe { JS_FreeValue(ctx, old) };
      }
    }
  });
}

fn context_security_token(ctx: *mut JSContext) -> JSValue {
  if ctx.is_null() {
    return jsv_undefined();
  }
  let found = SECURITY_TOKEN.with(|m| m.borrow().get(&(ctx as usize)).copied());
  match found {
    Some(v) => unsafe { JS_DupValue(ctx, v) },
    None => unsafe { JS_GetGlobalObject(ctx) },
  }
}

pub(crate) fn contexts_share_security_token(
  accessing_ctx: *mut JSContext,
  target_ctx: *mut JSContext,
) -> bool {
  if accessing_ctx.is_null() || target_ctx.is_null() {
    return false;
  }
  if accessing_ctx == target_ctx {
    return true;
  }

  let accessing = context_security_token(accessing_ctx);
  let target = context_security_token(target_ctx);
  let matches = unsafe { JS_IsStrictEqual(accessing_ctx, accessing, target) };
  unsafe {
    JS_FreeValue(accessing_ctx, accessing);
    JS_FreeValue(accessing_ctx, target);
  }
  matches
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Context__GetSecurityToken(
  this: *const Context,
) -> *const Value {
  let ctx = ctx_of(this);
  if ctx.is_null() {
    return ptr::null();
  }
  intern::<Value>(context_security_token(ctx))
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Context__UseDefaultSecurityToken(this: *const Context) {
  let ctx = ctx_of(this);
  if ctx.is_null() {
    return;
  }
  SECURITY_TOKEN.with(|m| {
    if let Some(old) = m.borrow_mut().remove(&(ctx as usize)) {
      if old.tag < 0 {
        unsafe { JS_FreeValue(ctx, old) };
      }
    }
  });
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Eternal__CONSTRUCT(this: *mut *const Data) {
  if !this.is_null() {
    unsafe { this.write_unaligned(ptr::null()) };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Eternal__DESTRUCT(this: *mut *const Data) {
  v8__Eternal__Clear(this as *mut c_void);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Eternal__Get(
  this: *const *const Data,
  _isolate: *mut RealIsolate,
) -> *const Data {
  if this.is_null() {
    return ptr::null();
  }
  let stored = unsafe { this.read_unaligned() };
  if stored.is_null() {
    return ptr::null();
  }

  let ctx = current_ctx();
  if ctx.is_null() {
    return stored;
  }
  intern_dup::<Data>(ctx, jsval_of(stored))
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Eternal__Set(
  this: *mut *const Data,
  _isolate: *mut RealIsolate,
  data: *mut Data,
) {
  if this.is_null() {
    return;
  }
  let ctx = current_ctx();
  if ctx.is_null() || data.is_null() {
    unsafe { this.write_unaligned(ptr::null()) };
    return;
  }

  let owned = unsafe { JS_DupValue(ctx, jsval_of(data)) };
  let boxed = Box::into_raw(Box::new(owned));
  unsafe { this.write_unaligned(boxed as *const Data) };
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__AddGCPrologueCallback(
  isolate: *mut RealIsolate,
  callback: crate::isolate::GcCallbackWithData,
  data: *mut c_void,
  gc_type_filter: crate::gc::GCType,
) {
  if !isolate.is_null() {
    iso_state(isolate).gc_prologue_callbacks.push(
      crate::quickjs::core::GcCallbackEntry {
        callback,
        data,
        gc_type_filter,
      },
    );
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__AddGCEpilogueCallback(
  isolate: *mut RealIsolate,
  callback: crate::isolate::GcCallbackWithData,
  data: *mut c_void,
  gc_type_filter: crate::gc::GCType,
) {
  if !isolate.is_null() {
    iso_state(isolate).gc_epilogue_callbacks.push(
      crate::quickjs::core::GcCallbackEntry {
        callback,
        data,
        gc_type_filter,
      },
    );
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__AddNearHeapLimitCallback(
  isolate: *mut RealIsolate,
  callback: crate::isolate::NearHeapLimitCallback,
  data: *mut c_void,
) {
  crate::quickjs::isolate::set_near_heap_limit_callback(
    isolate, callback, data,
  );
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__AdjustAmountOfExternalAllocatedMemory(
  isolate: *mut RealIsolate,
  change_in_bytes: i64,
) -> i64 {
  let isolate = if isolate.is_null() {
    current_iso()
  } else {
    isolate
  };
  if isolate.is_null() {
    return change_in_bytes;
  }
  adjust_external_memory(iso_state(isolate), change_in_bytes)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__LowMemoryNotification(
  isolate: *mut RealIsolate,
) {
  if isolate.is_null() {
    return;
  }
  let rt = iso_state(isolate).rt;
  if !rt.is_null() {
    unsafe { JS_RunGC(rt) };
  }
  super::arraybuffer::release_pending_allocator_buffers(isolate);
  let st = iso_state(isolate);
  release_external_string_memory(st);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__NumberOfHeapSpaces(
  _isolate: *mut RealIsolate,
) -> usize {
  0
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__GetHeapSpaceStatistics(
  _isolate: *mut RealIsolate,
  space_statistics: *mut crate::binding::v8__HeapSpaceStatistics,
  _index: usize,
) -> bool {
  if !space_statistics.is_null() {
    unsafe {
      ptr::write_bytes(
        space_statistics as *mut u8,
        0,
        std::mem::size_of::<crate::binding::v8__HeapSpaceStatistics>(),
      );
    }
  }
  false
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__GetHeapCodeAndMetadataStatistics(
  isolate: *mut RealIsolate,
  code_statistics: *mut crate::binding::v8__HeapCodeStatistics,
) -> bool {
  if isolate.is_null() {
    return false;
  }
  if !code_statistics.is_null() {
    let bytecode_size = iso_state(isolate)
      .bytecode_and_metadata_size
      .load(Ordering::SeqCst);
    unsafe {
      ptr::write_bytes(
        code_statistics as *mut u8,
        0,
        std::mem::size_of::<crate::binding::v8__HeapCodeStatistics>(),
      );
      (*code_statistics).bytecode_and_metadata_size_ = bytecode_size;
    }
  }
  true
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__DateTimeConfigurationChangeNotification(
  _isolate: *mut RealIsolate,
  _time_zone_detection: crate::isolate::TimeZoneDetection,
) {
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Isolate__SetAllowWasmCodeGenerationCallback(
  _isolate: *mut RealIsolate,
  _callback: crate::isolate::AllowWasmCodeGenerationCallback,
) {
}

unsafe fn qjs_value_to_string(
  ctx: *mut JSContext,
  v: JSValue,
) -> Option<String> {
  let mut len = 0usize;
  let cstr = unsafe { JS_ToCStringLen(ctx, &mut len, v) };
  if cstr.is_null() {
    return None;
  }
  let text = unsafe {
    let bytes = std::slice::from_raw_parts(cstr as *const u8, len);
    String::from_utf8_lossy(bytes).into_owned()
  };
  unsafe { JS_FreeCString(ctx, cstr) };
  Some(text)
}

unsafe fn qjs_atom_to_string(
  ctx: *mut JSContext,
  atom: JSAtom,
) -> Option<String> {
  let value = unsafe { JS_AtomToString(ctx, atom) };
  if value.tag == JS_TAG_EXCEPTION {
    return None;
  }
  let text = unsafe { qjs_value_to_string(ctx, value) };
  unsafe { JS_FreeValue(ctx, value) };
  text
}

fn push_snapshot_name(
  names: &mut Vec<String>,
  seen_names: &mut HashSet<String>,
  name: String,
) {
  if name.is_empty() || name == "undefined" || name == "null" {
    return;
  }
  if seen_names.insert(name.clone()) {
    names.push(name);
  }
}

unsafe fn snapshot_data_property(
  ctx: *mut JSContext,
  value: JSValue,
  atom: JSAtom,
) -> Option<JSValue> {
  let mut current = unsafe { JS_DupValue(ctx, value) };
  loop {
    if !jsv_is_object(&current) || unsafe { JS_IsProxy(current) } {
      unsafe { JS_FreeValue(ctx, current) };
      return None;
    }
    let mut desc = JSPropertyDescriptorQjs {
      flags: 0,
      value: jsv_undefined(),
      getter: jsv_undefined(),
      setter: jsv_undefined(),
    };
    let result = unsafe { JS_GetOwnProperty(ctx, &mut desc, current, atom) };
    if result < 0 {
      unsafe {
        JS_FreeValue(ctx, current);
        crate::quickjs::exception::clear_pending(ctx);
      }
      return None;
    }
    if result > 0 {
      unsafe {
        JS_FreeValue(ctx, current);
        JS_FreeValue(ctx, desc.getter);
        JS_FreeValue(ctx, desc.setter);
      }
      if desc.flags & JS_PROP_GETSET_QJS != 0 {
        unsafe { JS_FreeValue(ctx, desc.value) };
        return None;
      }
      return Some(desc.value);
    }
    unsafe {
      JS_FreeValue(ctx, desc.value);
      JS_FreeValue(ctx, desc.getter);
      JS_FreeValue(ctx, desc.setter);
    }
    let prototype = unsafe { JS_GetPrototype(ctx, current) };
    unsafe { JS_FreeValue(ctx, current) };
    if jsv_is_exception(&prototype) {
      unsafe { crate::quickjs::exception::clear_pending(ctx) };
      return None;
    }
    if jsv_is_null(&prototype) {
      unsafe { JS_FreeValue(ctx, prototype) };
      return None;
    }
    current = prototype;
  }
}

unsafe fn snapshot_constructor_name(
  ctx: *mut JSContext,
  value: JSValue,
  constructor_atom: JSAtom,
  name_atom: JSAtom,
) -> Option<String> {
  let constructor =
    unsafe { snapshot_data_property(ctx, value, constructor_atom) }?;
  let name = unsafe { snapshot_data_property(ctx, constructor, name_atom) };
  unsafe { JS_FreeValue(ctx, constructor) };
  let name = name?;
  let text = unsafe { qjs_value_to_string(ctx, name) };
  unsafe { JS_FreeValue(ctx, name) };
  if text.is_none() {
    unsafe { crate::quickjs::exception::clear_pending(ctx) };
  }
  text.filter(|name| !name.is_empty())
}

unsafe fn quickjs_heap_object_names(ctx: *mut JSContext) -> Vec<String> {
  let constructor_atom = unsafe { JS_NewAtom(ctx, c"constructor".as_ptr()) };
  let name_atom = unsafe { JS_NewAtom(ctx, c"name".as_ptr()) };
  let mut count = 0usize;
  let objects = unsafe { v82jsc_heap_objects(ctx, &mut count) };
  let mut names = Vec::with_capacity(count);
  if !objects.is_null() {
    for value in unsafe { std::slice::from_raw_parts(objects, count) } {
      if let Some(name) = unsafe {
        snapshot_constructor_name(ctx, *value, constructor_atom, name_atom)
      } {
        names.push(name);
      }
    }
    unsafe { v82jsc_free_heap_objects(ctx, objects, count) };
  }
  unsafe {
    JS_FreeAtom(ctx, constructor_atom);
    JS_FreeAtom(ctx, name_atom);
  }
  names
}

unsafe fn collect_constructor_name(
  ctx: *mut JSContext,
  value: JSValue,
  names: &mut Vec<String>,
  seen_names: &mut HashSet<String>,
) {
  if !jsv_is_object(&value) {
    return;
  }
  let ctor = unsafe { JS_GetPropertyStr(ctx, value, c"constructor".as_ptr()) };
  if ctor.tag == JS_TAG_EXCEPTION {
    return;
  }
  let name = unsafe { JS_GetPropertyStr(ctx, ctor, c"name".as_ptr()) };
  if name.tag != JS_TAG_EXCEPTION {
    if let Some(text) = unsafe { qjs_value_to_string(ctx, name) } {
      push_snapshot_name(names, seen_names, text);
    }
  }
  unsafe {
    JS_FreeValue(ctx, name);
    JS_FreeValue(ctx, ctor);
  }
}

fn collect_cppgc_snapshot_names(
  names: &mut Vec<String>,
  seen_names: &mut HashSet<String>,
) {
  let objects = CPPGC_OBJECTS.with(|objects| {
    objects
      .borrow()
      .iter()
      .map(|object| object.ptr)
      .collect::<Vec<_>>()
  });
  for object in objects {
    let name = unsafe { rusty_v8_RustObj_get_name(object as *const RustObj) };
    if name.is_null() {
      continue;
    }
    if let Ok(name) = unsafe { CStr::from_ptr(name) }.to_str() {
      push_snapshot_name(names, seen_names, name.to_owned());
    }
  }
}

unsafe fn collect_heap_snapshot_names(
  ctx: *mut JSContext,
  value: JSValue,
  depth: usize,
  seen_objects: &mut HashSet<usize>,
  seen_names: &mut HashSet<String>,
  names: &mut Vec<String>,
) {
  if depth > HEAP_SNAPSHOT_MAX_DEPTH || !jsv_is_object(&value) {
    return;
  }

  let ptr = unsafe { value.u.ptr } as usize;
  if ptr == 0 || !seen_objects.insert(ptr) {
    return;
  }

  unsafe { collect_constructor_name(ctx, value, names, seen_names) };

  if unsafe { JS_IsArray(value) } {
    let len_value =
      unsafe { JS_GetPropertyStr(ctx, value, c"length".as_ptr()) };
    let mut len = 0i32;
    unsafe {
      JS_ToInt32(ctx, &mut len, len_value);
      JS_FreeValue(ctx, len_value);
    }
    for index in 0..(len.max(0) as u32).min(HEAP_SNAPSHOT_ARRAY_SAMPLE) {
      let element = unsafe { JS_GetPropertyUint32(ctx, value, index) };
      unsafe {
        collect_heap_snapshot_names(
          ctx,
          element,
          depth + 1,
          seen_objects,
          seen_names,
          names,
        );
        JS_FreeValue(ctx, element);
      }
    }
  }

  let mut ptab: *mut JSPropertyEnum = ptr::null_mut();
  let mut plen = 0u32;
  let flags = JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK | JS_GPN_ENUM_ONLY;
  let rc =
    unsafe { JS_GetOwnPropertyNames(ctx, &mut ptab, &mut plen, value, flags) };
  if rc != 0 || ptab.is_null() {
    return;
  }

  for index in 0..plen as usize {
    let atom = unsafe { (*ptab.add(index)).atom };
    if let Some(name) = unsafe { qjs_atom_to_string(ctx, atom) } {
      push_snapshot_name(names, seen_names, name);
    }
    let property = unsafe { JS_GetProperty(ctx, value, atom) };
    unsafe {
      collect_heap_snapshot_names(
        ctx,
        property,
        depth + 1,
        seen_objects,
        seen_names,
        names,
      );
      JS_FreeValue(ctx, property);
      JS_FreeAtom(ctx, atom);
    }
  }
  unsafe { js_free(ctx, ptab as *mut c_void) };
}

fn push_json_string(out: &mut String, value: &str) {
  out.push('"');
  for ch in value.chars() {
    match ch {
      '"' => out.push_str("\\\""),
      '\\' => out.push_str("\\\\"),
      '\n' => out.push_str("\\n"),
      '\r' => out.push_str("\\r"),
      '\t' => out.push_str("\\t"),
      ch if ch.is_control() => {
        use std::fmt::Write;
        let _ = write!(out, "\\u{:04x}", ch as u32);
      }
      ch => out.push(ch),
    }
  }
  out.push('"');
}

fn quickjs_heap_snapshot_json(isolate: *mut RealIsolate) -> Vec<u8> {
  if isolate.is_null() {
    return br#"{"snapshot":{"meta":{}},"nodes":[],"strings":[]}"#.to_vec();
  }
  let ctx = {
    let current = current_ctx();
    if !current.is_null() {
      current
    } else {
      let st = iso_state(isolate);
      st.contexts.last().copied().unwrap_or(st.ctx)
    }
  };
  if ctx.is_null() {
    return br#"{"snapshot":{"meta":{}},"nodes":[],"strings":[]}"#.to_vec();
  }

  let mut object_names = unsafe { quickjs_heap_object_names(ctx) };
  let mut cppgc_names = Vec::new();
  let mut seen_cppgc_names = HashSet::new();
  collect_cppgc_snapshot_names(&mut cppgc_names, &mut seen_cppgc_names);
  object_names.extend(cppgc_names);

  let mut strings = vec![String::new()];
  let mut string_indices = HashMap::new();
  string_indices.insert(String::new(), 0usize);
  let name_indices = object_names
    .into_iter()
    .map(|name| {
      if let Some(index) = string_indices.get(&name) {
        *index
      } else {
        let index = strings.len();
        string_indices.insert(name.clone(), index);
        strings.push(name);
        index
      }
    })
    .collect::<Vec<_>>();

  let mut json = String::from(
    "{\"snapshot\":{\"meta\":{\"node_fields\":[\"type\",\"name\",\"id\",\"self_size\",\"edge_count\",\"trace_node_id\",\"detachedness\"],\"node_types\":[[\"hidden\",\"array\",\"string\",\"object\",\"code\",\"closure\",\"regexp\",\"number\",\"native\",\"synthetic\",\"concatenated string\",\"sliced string\",\"symbol\",\"bigint\"],\"string\",\"number\",\"number\",\"number\",\"number\",\"number\"],\"edge_fields\":[\"type\",\"name_or_index\",\"to_node\"],\"edge_types\":[[\"context\",\"element\",\"property\",\"internal\",\"hidden\",\"shortcut\",\"weak\"],\"string_or_number\",\"node\"]},\"node_count\":",
  );
  json.push_str(&name_indices.len().to_string());
  json.push_str(",\"edge_count\":0,\"trace_function_count\":0},\"nodes\":[");
  for (index, name_index) in name_indices.iter().enumerate() {
    if index > 0 {
      json.push(',');
    }
    let id = index.saturating_mul(2).saturating_add(1);
    use std::fmt::Write;
    let _ = write!(json, "3,{name_index},{id},0,0,0,0");
  }
  json.push_str("],\"edges\":[],\"trace_function_infos\":[],\"trace_tree\":[],\"samples\":[],\"locations\":[],\"strings\":[");
  for (index, value) in strings.iter().enumerate() {
    if index > 0 {
      json.push(',');
    }
    push_json_string(&mut json, value);
  }
  json.push_str("]}");
  json.into_bytes()
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__HeapProfiler__TakeHeapSnapshot(
  isolate: *mut RealIsolate,
  callback: unsafe extern "C" fn(*mut c_void, *const u8, usize) -> bool,
  arg: *mut c_void,
) {
  let snapshot = quickjs_heap_snapshot_json(isolate);
  if snapshot.is_empty() {
    return;
  }
  unsafe {
    callback(arg, snapshot.as_ptr(), snapshot.len());
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__ScriptCompiler__CachedDataVersionTag() -> u32 {
  0x5145_4a53
}

// ---------------------------------------------------------------------------
// Link-stubs for v8 C-ABI symbols that `test_api.rs` references but this
// backend doesn't implement yet. Each returns a benign default
// (null / 0 / false / `Nothing`) so the target LINKS and the many tests that
// don't touch these paths run; tests that do exercise them fail gracefully
// without crashing. Promote individual stubs to real implementations over time.
// ---------------------------------------------------------------------------

#[unsafe(no_mangle)]
pub extern "C" fn icu_set_default_locale(locale: *const c_char) {
  if locale.is_null() {
    return;
  }
  let s = unsafe { std::ffi::CStr::from_ptr(locale) }.to_string_lossy();
  crate::quickjs::cli_extra::set_default_locale_str(&s);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__CompiledWasmModule__GetWireBytesRef(
  this: *mut std::os::raw::c_void,
  length: *mut std::os::raw::c_void,
) -> *const std::os::raw::c_void {
  super::wasm::compiled_module_wire_bytes(this, length)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__CompiledWasmModule__SourceUrl(
  this: *mut std::os::raw::c_void,
  length: *mut std::os::raw::c_void,
) -> *const std::os::raw::c_void {
  super::wasm::compiled_module_source_url(this, length)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Eternal__Clear(this: *mut std::os::raw::c_void) {
  if this.is_null() {
    return;
  }
  let slot = this as *mut *const Data;
  let stored = unsafe { slot.read_unaligned() };
  unsafe { slot.write_unaligned(ptr::null()) };
  if stored.is_null() {
    return;
  }

  let boxed = unsafe { Box::from_raw(stored as *mut JSValue) };
  let ctx = current_ctx();
  if !ctx.is_null() {
    unsafe { JS_FreeValue(ctx, *boxed) };
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Eternal__IsEmpty(
  this: *const std::os::raw::c_void,
) -> bool {
  if this.is_null() {
    return true;
  }
  let slot = this as *const *const Data;
  unsafe { slot.read_unaligned().is_null() }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__Clear(this: *const crate::Map) {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return;
  }
  unsafe {
    let r =
      call_collection_method(ctx, jsval_of(this), c"clear".as_ptr(), &mut []);
    JS_FreeValue(ctx, r);
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__Delete(
  this: *const crate::Map,
  context: *const Context,
  key: *const Value,
) -> crate::support::MaybeBool {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return crate::support::MaybeBool::Nothing;
  }
  unsafe {
    let mut args = [JS_DupValue(ctx, jsval_of(key))];
    let r = call_collection_method(
      ctx,
      jsval_of(this),
      c"delete".as_ptr(),
      &mut args,
    );
    JS_FreeValue(ctx, args[0]);
    if r.tag == JS_TAG_EXCEPTION {
      return crate::support::MaybeBool::Nothing;
    }
    let b = JS_ToBool(ctx, r) != 0;
    JS_FreeValue(ctx, r);
    mb(b)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__Get(
  this: *const crate::Map,
  context: *const Context,
  key: *const Value,
) -> *const Value {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  unsafe {
    let mut args = [JS_DupValue(ctx, jsval_of(key))];
    let r =
      call_collection_method(ctx, jsval_of(this), c"get".as_ptr(), &mut args);
    JS_FreeValue(ctx, args[0]);
    if r.tag == JS_TAG_EXCEPTION {
      return ptr::null();
    }
    intern::<Value>(r)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__Has(
  this: *const crate::Map,
  context: *const Context,
  key: *const Value,
) -> crate::support::MaybeBool {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return crate::support::MaybeBool::Nothing;
  }
  unsafe {
    let mut args = [JS_DupValue(ctx, jsval_of(key))];
    let r =
      call_collection_method(ctx, jsval_of(this), c"has".as_ptr(), &mut args);
    JS_FreeValue(ctx, args[0]);
    if r.tag == JS_TAG_EXCEPTION {
      return crate::support::MaybeBool::Nothing;
    }
    let b = JS_ToBool(ctx, r) != 0;
    JS_FreeValue(ctx, r);
    mb(b)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__New(isolate: *mut RealIsolate) -> *const crate::Map {
  let v = new_builtin(isolate, c"Map".as_ptr());
  if v.tag == JS_TAG_EXCEPTION {
    return ptr::null();
  }
  intern::<crate::Map>(v)
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Map__Set(
  this: *const crate::Map,
  context: *const Context,
  key: *const Value,
  value: *const Value,
) -> *const crate::Map {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return ptr::null();
  }
  unsafe {
    let mut args = [
      JS_DupValue(ctx, jsval_of(key)),
      JS_DupValue(ctx, jsval_of(value)),
    ];
    let r =
      call_collection_method(ctx, jsval_of(this), c"set".as_ptr(), &mut args);
    JS_FreeValue(ctx, args[0]);
    JS_FreeValue(ctx, args[1]);
    if r.tag == JS_TAG_EXCEPTION {
      return ptr::null();
    }
    // Map.prototype.set returns the map; return our handle to `this`.
    JS_FreeValue(ctx, r);
    intern::<crate::Map>(JS_DupValue(ctx, jsval_of(this)))
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Proxy__IsRevoked(
  this: *const std::os::raw::c_void,
) -> bool {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return false;
  }
  let proxy = jsval_of(this as *const Value);
  if let Some(revoked) = proxy_revoked_from_table(proxy) {
    return revoked;
  }
  let target = unsafe { JS_GetProxyTarget(ctx, proxy) };
  if target.tag == JS_TAG_EXCEPTION {
    let exc = unsafe { JS_GetException(ctx) };
    unsafe { JS_FreeValue(ctx, exc) };
    return true;
  }
  unsafe { JS_FreeValue(ctx, target) };
  false
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Proxy__New(
  context: *const std::os::raw::c_void,
  target: *const std::os::raw::c_void,
  handler: *const std::os::raw::c_void,
) -> *const std::os::raw::c_void {
  if context.is_null() || target.is_null() || handler.is_null() {
    return ptr::null();
  }
  let ctx = ctx_of(context as *const Context);
  if ctx.is_null() {
    return ptr::null();
  }

  unsafe {
    let global = JS_GetGlobalObject(ctx);
    let proxy_ctor = JS_GetPropertyStr(ctx, global, c"Proxy".as_ptr());
    JS_FreeValue(ctx, global);
    if !jsv_is_object(&proxy_ctor) {
      JS_FreeValue(ctx, proxy_ctor);
      return ptr::null();
    }
    let revocable = JS_GetPropertyStr(ctx, proxy_ctor, c"revocable".as_ptr());
    if !JS_IsFunction(ctx, revocable) {
      JS_FreeValue(ctx, revocable);
      JS_FreeValue(ctx, proxy_ctor);
      return ptr::null();
    }

    let mut args = [
      jsval_of(target as *const Object),
      jsval_of(handler as *const Object),
    ];
    let result = JS_Call(ctx, revocable, proxy_ctor, 2, args.as_mut_ptr());
    JS_FreeValue(ctx, revocable);
    JS_FreeValue(ctx, proxy_ctor);
    if result.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return ptr::null();
    }

    let proxy = JS_GetPropertyStr(ctx, result, c"proxy".as_ptr());
    let revoke = JS_GetPropertyStr(ctx, result, c"revoke".as_ptr());
    JS_FreeValue(ctx, result);
    if proxy.tag == JS_TAG_EXCEPTION
      || revoke.tag == JS_TAG_EXCEPTION
      || !JS_IsProxy(proxy)
      || !JS_IsFunction(ctx, revoke)
    {
      if proxy.tag != JS_TAG_EXCEPTION {
        JS_FreeValue(ctx, proxy);
      }
      if revoke.tag != JS_TAG_EXCEPTION {
        JS_FreeValue(ctx, revoke);
      }
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
      return ptr::null();
    }

    register_proxy_revoke(ctx, proxy, revoke);
    intern::<crate::Proxy>(proxy) as *const std::os::raw::c_void
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Proxy__Revoke(this: *const std::os::raw::c_void) {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return;
  }
  let proxy = jsval_of(this as *const Value);
  let Some(revoke) = proxy_revoke_function(ctx, proxy) else {
    return;
  };
  unsafe {
    let result = JS_Call(ctx, revoke, jsv_undefined(), 0, ptr::null_mut());
    JS_FreeValue(ctx, revoke);
    if result.tag == JS_TAG_EXCEPTION {
      let exc = JS_GetException(ctx);
      JS_FreeValue(ctx, exc);
    } else {
      JS_FreeValue(ctx, result);
    }
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__Clear(this: *const crate::Set) {
  let ctx = current_ctx();
  if ctx.is_null() || this.is_null() {
    return;
  }
  unsafe {
    let r =
      call_collection_method(ctx, jsval_of(this), c"clear".as_ptr(), &mut []);
    JS_FreeValue(ctx, r);
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__Delete(
  this: *const crate::Set,
  context: *const Context,
  key: *const Value,
) -> crate::support::MaybeBool {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return crate::support::MaybeBool::Nothing;
  }
  unsafe {
    let mut args = [JS_DupValue(ctx, jsval_of(key))];
    let r = call_collection_method(
      ctx,
      jsval_of(this),
      c"delete".as_ptr(),
      &mut args,
    );
    JS_FreeValue(ctx, args[0]);
    if r.tag == JS_TAG_EXCEPTION {
      return crate::support::MaybeBool::Nothing;
    }
    let b = JS_ToBool(ctx, r) != 0;
    JS_FreeValue(ctx, r);
    mb(b)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__Set__Has(
  this: *const crate::Set,
  context: *const Context,
  key: *const Value,
) -> crate::support::MaybeBool {
  let ctx = ctx_of(context);
  if ctx.is_null() || this.is_null() {
    return crate::support::MaybeBool::Nothing;
  }
  unsafe {
    let mut args = [JS_DupValue(ctx, jsval_of(key))];
    let r =
      call_collection_method(ctx, jsval_of(this), c"has".as_ptr(), &mut args);
    JS_FreeValue(ctx, args[0]);
    if r.tag == JS_TAG_EXCEPTION {
      return crate::support::MaybeBool::Nothing;
    }
    let b = JS_ToBool(ctx, r) != 0;
    JS_FreeValue(ctx, r);
    mb(b)
  }
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleCompilation__Abort(
  this: *mut std::os::raw::c_void,
) {
  super::wasm::module_compilation_abort(this);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleCompilation__Finish(
  this: *mut std::os::raw::c_void,
  isolate: *mut std::os::raw::c_void,
  caching_callback: *const std::os::raw::c_void,
  resolution_callback: *const std::os::raw::c_void,
  resolution_data: *mut std::os::raw::c_void,
  drop_resolution_data: *const std::os::raw::c_void,
) {
  super::wasm::module_compilation_finish(
    this,
    isolate,
    caching_callback,
    resolution_callback,
    resolution_data,
    drop_resolution_data,
  );
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleCompilation__OnBytesReceived(
  this: *mut std::os::raw::c_void,
  bytes: *const std::os::raw::c_void,
  size: usize,
) {
  super::wasm::module_compilation_on_bytes_received(this, bytes, size);
}

#[unsafe(no_mangle)]
pub extern "C" fn v8__WasmModuleCompilation__SetUrl(
  this: *mut std::os::raw::c_void,
  url: *const std::os::raw::c_void,
  length: usize,
) {
  super::wasm::module_compilation_set_url(this, url, length);
}