File: jsapi.cpp

package info (click to toggle)
thunderbird 1:60.8.0-1~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,339,208 kB
  • sloc: cpp: 5,456,704; ansic: 2,360,384; python: 596,095; asm: 340,963; java: 326,291; xml: 258,664; sh: 84,366; makefile: 23,702; perl: 17,317; objc: 3,768; yacc: 1,766; ada: 1,681; lex: 1,364; pascal: 1,264; cs: 879; exp: 527; php: 436; lisp: 258; ruby: 153; awk: 152; sed: 53; csh: 27
file content (6811 lines) | stat: -rw-r--r-- 240,128 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=8 sts=4 et sw=4 tw=99:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * JavaScript API.
 */

#include "jsapi.h"

#include "mozilla/FloatingPoint.h"
#include "mozilla/Maybe.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Sprintf.h"

#include <ctype.h>
#ifdef __linux__
#include <dlfcn.h>
#endif
#include <stdarg.h>
#include <string.h>
#include <sys/stat.h>

#include "jsarray.h"
#include "jsbool.h"
#include "jsdate.h"
#include "jsexn.h"
#include "jsfriendapi.h"
#include "jsmath.h"
#include "jsnum.h"
#include "jstypes.h"
#include "jsutil.h"

#include "builtin/AtomicsObject.h"
#include "builtin/Eval.h"
#include "builtin/JSON.h"
#include "builtin/MapObject.h"
#include "builtin/Promise.h"
#include "builtin/RegExp.h"
#include "builtin/Stream.h"
#include "builtin/String.h"
#include "builtin/Symbol.h"
#ifdef ENABLE_SIMD
#include "builtin/SIMD.h"
#endif
#ifdef ENABLE_BINARYDATA
#include "builtin/TypedObject.h"
#endif
#include "frontend/BytecodeCompiler.h"
#include "frontend/FullParseHandler.h"  // for JS_BufferIsCompileableUnit
#include "frontend/Parser.h"            // for JS_BufferIsCompileableUnit
#include "gc/FreeOp.h"
#include "gc/Marking.h"
#include "gc/Policy.h"
#include "gc/PublicIterators.h"
#include "gc/WeakMap.h"
#include "jit/JitCommon.h"
#include "js/CharacterEncoding.h"
#include "js/Conversions.h"
#include "js/Date.h"
#include "js/Initialization.h"
#include "js/Proxy.h"
#include "js/SliceBudget.h"
#include "js/StructuredClone.h"
#include "js/Utility.h"
#include "js/Wrapper.h"
#include "util/StringBuffer.h"
#include "util/Text.h"
#include "vm/AsyncFunction.h"
#include "vm/AsyncIteration.h"
#include "vm/DateObject.h"
#include "vm/Debugger.h"
#include "vm/EnvironmentObject.h"
#include "vm/ErrorObject.h"
#include "vm/HelperThreads.h"
#include "vm/Interpreter.h"
#include "vm/Iteration.h"
#include "vm/JSAtom.h"
#include "vm/JSContext.h"
#include "vm/JSFunction.h"
#include "vm/JSObject.h"
#include "vm/JSScript.h"
#include "vm/RegExpStatics.h"
#include "vm/Runtime.h"
#include "vm/SavedStacks.h"
#include "vm/SelfHosting.h"
#include "vm/Shape.h"
#include "vm/StringType.h"
#include "vm/SymbolType.h"
#include "vm/WrapperObject.h"
#include "vm/Xdr.h"
#include "wasm/AsmJS.h"
#include "wasm/WasmModule.h"

#include "vm/Interpreter-inl.h"
#include "vm/JSAtom-inl.h"
#include "vm/JSFunction-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/SavedStacks-inl.h"
#include "vm/StringType-inl.h"

using namespace js;
using namespace js::gc;

using mozilla::Maybe;
using mozilla::PodCopy;
using mozilla::Some;

#ifdef HAVE_VA_LIST_AS_ARRAY
#define JS_ADDRESSOF_VA_LIST(ap) ((va_list*)(ap))
#else
#define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
#endif

JS_PUBLIC_API bool JS::CallArgs::requireAtLeast(JSContext* cx,
                                                const char* fnname,
                                                unsigned required) const {
  if (length() < required) {
    char numArgsStr[40];
    SprintfLiteral(numArgsStr, "%u", required - 1);
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_MORE_ARGS_NEEDED, fnname, numArgsStr,
                              required == 2 ? "" : "s");
    return false;
  }

  return true;
}

static bool ErrorTakesArguments(unsigned msg) {
  MOZ_ASSERT(msg < JSErr_Limit);
  unsigned argCount = js_ErrorFormatString[msg].argCount;
  MOZ_ASSERT(argCount <= 2);
  return argCount == 1 || argCount == 2;
}

static bool ErrorTakesObjectArgument(unsigned msg) {
  MOZ_ASSERT(msg < JSErr_Limit);
  unsigned argCount = js_ErrorFormatString[msg].argCount;
  MOZ_ASSERT(argCount <= 2);
  return argCount == 2;
}

JS_PUBLIC_API bool JS::ObjectOpResult::reportStrictErrorOrWarning(
    JSContext* cx, HandleObject obj, HandleId id, bool strict) {
  static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR),
                "unsigned value of OkCode must not be an error code");
  MOZ_ASSERT(code_ != Uninitialized);
  MOZ_ASSERT(!ok());
  assertSameCompartment(cx, obj);

  unsigned flags =
      strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
  if (code_ == JSMSG_OBJECT_NOT_EXTENSIBLE) {
    RootedValue val(cx, ObjectValue(*obj));
    return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
                                 nullptr, nullptr, nullptr);
  }

  if (ErrorTakesArguments(code_)) {
    RootedValue idv(cx, IdToValue(id));
    RootedString str(cx, ValueToSource(cx, idv));
    if (!str) return false;

    JSAutoByteString propName;
    if (!propName.encodeUtf8(cx, str)) return false;

    if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
      // We know that the original receiver was a primitive, so unbox it.
      RootedValue val(cx, ObjectValue(*obj));
      if (!obj->is<ProxyObject>()) {
        if (!Unbox(cx, obj, &val)) return false;
      }
      return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
                                   nullptr, propName.ptr(), nullptr);
    }

    if (ErrorTakesObjectArgument(code_)) {
      return JS_ReportErrorFlagsAndNumberUTF8(
          cx, flags, GetErrorMessage, nullptr, code_, obj->getClass()->name,
          propName.ptr());
    }

    return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr,
                                            code_, propName.ptr());
  }
  return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr,
                                           code_);
}

JS_PUBLIC_API bool JS::ObjectOpResult::reportStrictErrorOrWarning(
    JSContext* cx, HandleObject obj, bool strict) {
  MOZ_ASSERT(code_ != Uninitialized);
  MOZ_ASSERT(!ok());
  MOZ_ASSERT(!ErrorTakesArguments(code_));
  assertSameCompartment(cx, obj);

  unsigned flags =
      strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
  return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr,
                                           code_);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantRedefineProp() {
  return fail(JSMSG_CANT_REDEFINE_PROP);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failReadOnly() {
  return fail(JSMSG_READ_ONLY);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failGetterOnly() {
  return fail(JSMSG_GETTER_ONLY);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantDelete() {
  return fail(JSMSG_CANT_DELETE);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetInterposed() {
  return fail(JSMSG_CANT_SET_INTERPOSED);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowElement() {
  return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowElement() {
  return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
  return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantPreventExtensions() {
  return fail(JSMSG_CANT_PREVENT_EXTENSIONS);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetProto() {
  return fail(JSMSG_CANT_SET_PROTO);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failNoNamedSetter() {
  return fail(JSMSG_NO_NAMED_SETTER);
}

JS_PUBLIC_API bool JS::ObjectOpResult::failNoIndexedSetter() {
  return fail(JSMSG_NO_INDEXED_SETTER);
}

JS_PUBLIC_API int64_t JS_Now() { return PRMJ_Now(); }

JS_PUBLIC_API Value JS_GetNaNValue(JSContext* cx) {
  return cx->runtime()->NaNValue;
}

JS_PUBLIC_API Value JS_GetNegativeInfinityValue(JSContext* cx) {
  return cx->runtime()->negativeInfinityValue;
}

JS_PUBLIC_API Value JS_GetPositiveInfinityValue(JSContext* cx) {
  return cx->runtime()->positiveInfinityValue;
}

JS_PUBLIC_API Value JS_GetEmptyStringValue(JSContext* cx) {
  return StringValue(cx->runtime()->emptyString);
}

JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx) {
  MOZ_ASSERT(cx->emptyString());
  return cx->emptyString();
}

namespace js {

void AssertHeapIsIdle() { MOZ_ASSERT(!JS::CurrentThreadIsHeapBusy()); }

}  // namespace js

static void AssertHeapIsIdleOrIterating() {
  MOZ_ASSERT(!JS::CurrentThreadIsHeapCollecting());
}

static void AssertHeapIsIdleOrStringIsFlat(JSString* str) {
  /*
   * We allow some functions to be called during a GC as long as the argument
   * is a flat string, since that will not cause allocation.
   */
  MOZ_ASSERT_IF(JS::CurrentThreadIsHeapBusy(), str->isFlat());
}

JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, HandleValue value,
                                    MutableHandleObject objp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  if (value.isNullOrUndefined()) {
    objp.set(nullptr);
    return true;
  }
  JSObject* obj = ToObject(cx, value);
  if (!obj) return false;
  objp.set(obj);
  return true;
}

JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx, HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  return ReportIfNotFunction(cx, value);
}

JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
                                                HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  return ReportIfNotFunction(cx, value);
}

JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx, HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  return ValueToSource(cx, value);
}

JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip) {
  return mozilla::NumberIsInt32(d, ip);
}

JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx, HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  return TypeOfValue(value);
}

JS_PUBLIC_API bool JS_StrictlyEqual(JSContext* cx, HandleValue value1,
                                    HandleValue value2, bool* equal) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value1, value2);
  MOZ_ASSERT(equal);
  return StrictlyEqual(cx, value1, value2, equal);
}

JS_PUBLIC_API bool JS_LooselyEqual(JSContext* cx, HandleValue value1,
                                   HandleValue value2, bool* equal) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value1, value2);
  MOZ_ASSERT(equal);
  return LooselyEqual(cx, value1, value2, equal);
}

JS_PUBLIC_API bool JS_SameValue(JSContext* cx, HandleValue value1,
                                HandleValue value2, bool* same) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value1, value2);
  MOZ_ASSERT(same);
  return SameValue(cx, value1, value2, same);
}

JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun) {
  return IsAnyBuiltinEval(fun);
}

JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun) {
  return fun->isBuiltinFunctionConstructor();
}

JS_PUBLIC_API bool JS_IsFunctionBound(JSFunction* fun) {
  return fun->isBoundFunction();
}

JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSFunction* fun) {
  return fun->isBoundFunction() ? fun->getBoundFunctionTarget() : nullptr;
}

  /************************************************************************/

#ifdef DEBUG
JS_FRIEND_API bool JS::isGCEnabled() { return !TlsContext.get()->suppressGC; }
#else
JS_FRIEND_API bool JS::isGCEnabled() { return true; }
#endif

JS_PUBLIC_API JSContext* JS_NewContext(uint32_t maxbytes,
                                       uint32_t maxNurseryBytes,
                                       JSRuntime* parentRuntime) {
  MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running,
             "must call JS_Init prior to creating any JSContexts");

  // Make sure that all parent runtimes are the topmost parent.
  while (parentRuntime && parentRuntime->parentRuntime)
    parentRuntime = parentRuntime->parentRuntime;

  return NewContext(maxbytes, maxNurseryBytes, parentRuntime);
}

JS_PUBLIC_API JSContext* JS_NewCooperativeContext(JSContext* siblingContext) {
  return NewCooperativeContext(siblingContext);
}

JS_PUBLIC_API void JS_YieldCooperativeContext(JSContext* cx) {
  YieldCooperativeContext(cx);
}

JS_PUBLIC_API void JS_ResumeCooperativeContext(JSContext* cx) {
  ResumeCooperativeContext(cx);
}

JS_PUBLIC_API void JS_DestroyContext(JSContext* cx) { DestroyContext(cx); }

JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx) { return cx->data; }

JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data) {
  cx->data = data;
}

JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx) {
  cx->fx.setCanWait(true);
}

static void StartRequest(JSContext* cx) {
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));

  if (cx->requestDepth) {
    cx->requestDepth++;
  } else {
    /* Indicate that a request is running. */
    cx->requestDepth = 1;
    cx->triggerActivityCallback(true);
  }
}

static void StopRequest(JSContext* cx) {
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));

  MOZ_ASSERT(cx->requestDepth != 0);
  if (cx->requestDepth != 1) {
    cx->requestDepth--;
  } else {
    cx->requestDepth = 0;
    cx->triggerActivityCallback(false);
  }
}

JS_PUBLIC_API void JS_BeginRequest(JSContext* cx) {
  cx->outstandingRequests++;
  StartRequest(cx);
}

JS_PUBLIC_API void JS_EndRequest(JSContext* cx) {
  MOZ_ASSERT(cx->outstandingRequests != 0);
  cx->outstandingRequests--;
  StopRequest(cx);
}

JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx) {
  return cx->runtime()->parentRuntime ? cx->runtime()->parentRuntime
                                      : cx->runtime();
}

JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx) { return cx->runtime(); }

JS_PUBLIC_API void JS::SetSingleThreadedExecutionCallbacks(
    JSContext* cx, BeginSingleThreadedExecutionCallback begin,
    EndSingleThreadedExecutionCallback end) {
  cx->runtime()->beginSingleThreadedExecutionCallback = begin;
  cx->runtime()->endSingleThreadedExecutionCallback = end;
}

JS_PUBLIC_API JS::ContextOptions& JS::ContextOptionsRef(JSContext* cx) {
  return cx->options();
}

JS_PUBLIC_API bool JS::InitSelfHostedCode(JSContext* cx) {
  MOZ_RELEASE_ASSERT(!cx->runtime()->hasInitializedSelfHosting(),
                     "JS::InitSelfHostedCode() called more than once");

  AutoNoteSingleThreadedRegion anstr;

  JSRuntime* rt = cx->runtime();

  JSAutoRequest ar(cx);
  if (!rt->initializeAtoms(cx)) return false;

#ifndef JS_CODEGEN_NONE
  if (!rt->getJitRuntime(cx)) return false;
#endif

  if (!rt->initSelfHosting(cx)) return false;

  if (!rt->parentRuntime && !rt->transformToPermanentAtoms(cx)) return false;

  return true;
}

JS_PUBLIC_API const char* JS_GetImplementationVersion(void) {
  return "JavaScript-C" MOZILLA_VERSION;
}

JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
    JSContext* cx, JSDestroyCompartmentCallback callback) {
  cx->runtime()->destroyCompartmentCallback = callback;
}

JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
    JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback) {
  cx->runtime()->sizeOfIncludingThisCompartmentCallback = callback;
}

JS_PUBLIC_API void JS_SetCompartmentNameCallback(
    JSContext* cx, JSCompartmentNameCallback callback) {
  cx->runtime()->compartmentNameCallback = callback;
}

#if defined(NIGHTLY_BUILD)
JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
    JSRuntime* rt, JSErrorInterceptor* callback) {
  rt->errorInterception.interceptor = callback;
}

JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
    JSRuntime* rt) {
  return rt->errorInterception.interceptor;
}

JS_PUBLIC_API Maybe<JSExnType> JS_GetErrorType(const JS::Value& val) {
  // All errors are objects.
  if (!val.isObject()) return mozilla::Nothing();

  const JSObject& obj = val.toObject();

  // All errors are `ErrorObject`.
  if (!obj.is<js::ErrorObject>()) {
    // Not one of the primitive errors.
    return mozilla::Nothing();
  }

  const js::ErrorObject& err = obj.as<js::ErrorObject>();
  return mozilla::Some(err.type());
}

#endif  // defined(NIGHTLY_BUILD)

JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
    JSContext* cx, const JSWrapObjectCallbacks* callbacks) {
  cx->runtime()->wrapObjectCallbacks = callbacks;
}

JS_PUBLIC_API void JS_SetExternalStringSizeofCallback(
    JSContext* cx, JSExternalStringSizeofCallback callback) {
  cx->runtime()->externalStringSizeofCallback = callback;
}

JS_PUBLIC_API JSCompartment* JS_EnterCompartment(JSContext* cx,
                                                 JSObject* target) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  JSCompartment* oldCompartment = cx->compartment();
  cx->enterCompartmentOf(target);
  return oldCompartment;
}

JS_PUBLIC_API void JS_LeaveCompartment(JSContext* cx,
                                       JSCompartment* oldCompartment) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  cx->leaveCompartment(oldCompartment);
}

JSAutoCompartment::JSAutoCompartment(
    JSContext* cx, JSObject* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : cx_(cx), oldCompartment_(cx->compartment()) {
  AssertHeapIsIdleOrIterating();
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
  cx_->enterCompartmentOf(target);
}

JSAutoCompartment::JSAutoCompartment(
    JSContext* cx, JSScript* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : cx_(cx), oldCompartment_(cx->compartment()) {
  AssertHeapIsIdleOrIterating();
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
  cx_->enterCompartmentOf(target);
}

JSAutoCompartment::~JSAutoCompartment() {
  cx_->leaveCompartment(oldCompartment_);
}

JSAutoNullableCompartment::JSAutoNullableCompartment(
    JSContext* cx,
    JSObject* targetOrNull MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
    : cx_(cx), oldCompartment_(cx->compartment()) {
  AssertHeapIsIdleOrIterating();
  MOZ_GUARD_OBJECT_NOTIFIER_INIT;
  if (targetOrNull)
    cx_->enterCompartmentOf(targetOrNull);
  else
    cx_->enterNullCompartment();
}

JSAutoNullableCompartment::~JSAutoNullableCompartment() {
  cx_->leaveCompartment(oldCompartment_);
}

JS_PUBLIC_API void JS_SetCompartmentPrivate(JSCompartment* compartment,
                                            void* data) {
  compartment->data = data;
}

JS_PUBLIC_API void* JS_GetCompartmentPrivate(JSCompartment* compartment) {
  return compartment->data;
}

JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id) {
  cx->markId(id);
}

JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx, const Value& value) {
  cx->markAtomValue(value);
}

JS_PUBLIC_API JSAddonId* JS::NewAddonId(JSContext* cx, HandleString str) {
  return static_cast<JSAddonId*>(JS_AtomizeAndPinJSString(cx, str));
}

JS_PUBLIC_API JSString* JS::StringOfAddonId(JSAddonId* id) { return id; }

JS_PUBLIC_API JSAddonId* JS::AddonIdOfObject(JSObject* obj) {
  return obj->compartment()->creationOptions().addonIdOrNull();
}

JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data) {
  zone->data = data;
}

JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone) { return zone->data; }

JS_PUBLIC_API bool JS_WrapObject(JSContext* cx, MutableHandleObject objp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (objp) JS::ExposeObjectToActiveJS(objp);
  return cx->compartment()->wrap(cx, objp);
}

JS_PUBLIC_API bool JS_WrapValue(JSContext* cx, MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JS::ExposeValueToActiveJS(vp);
  return cx->compartment()->wrap(cx, vp);
}

static void ReleaseAssertObjectHasNoWrappers(JSContext* cx,
                                             HandleObject target) {
  RootedValue origv(cx, ObjectValue(*target));

  for (CompartmentsIter c(cx->runtime(), SkipAtoms); !c.done(); c.next()) {
    if (c->lookupWrapper(origv)) MOZ_CRASH("wrapper found for target object");
  }
}

/*
 * Brain transplants. Not for beginners or the squeamish.
 *
 * Sometimes a web spec requires us to transplant an object from one
 * compartment to another, like when a DOM node is inserted into a document in
 * another window and thus gets "adopted". We cannot literally change the
 * `.compartment()` of a `JSObject`; that would break the compartment
 * invariants. However, as usual, we have a workaround using wrappers.
 *
 * Of all the wrapper-based workarounds we do, it's safe to say this is the
 * most spectacular and questionable.
 *
 * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
 * simulacrum of `target`, using highly esoteric means. To JS code, the effect
 * is as if `origobj` magically "became" `target`, but most often what actually
 * happens is that `origobj` gets turned into a cross-compartment wrapper for
 * `target`. The old behavior and contents of `origobj` are overwritten or
 * discarded.
 *
 * Thus, to "transplant" an object from one compartment to another:
 *
 * 1.  Let `origobj` be the object that you want to move. First, create a
 *     clone of it, `target`, in the destination compartment.
 *
 *     In our DOM adoption example, `target` will be a Node of the same type as
 *     `origobj`, same content, but in the adopting document.  We're not done
 *     yet: the spec for DOM adoption requires that `origobj.ownerDocument`
 *     actually change. All we've done so far is make a copy.
 *
 * 2.  Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
 *     `origobj` into a wrapper for `target`, so that any JS code that has a
 *     reference to `origobj` will observe it to have the behavior of `target`
 *     going forward. In addition, all existing wrappers for `origobj` are
 *     changed into wrappers for `target`, extending the illusion to those
 *     compartments as well.
 *
 * During navigation, we use the above technique to transplant the WindowProxy
 * into the new Window's compartment.
 *
 * A few rules:
 *
 * -   `origobj` and `target` must be two distinct objects of the same
 *     `JSClass`.  Some classes may not support transplantation; WindowProxy
 *     objects and DOM nodes are OK.
 *
 * -   `target` should be created specifically to be passed to this function.
 *     There must be no existing cross-compartment wrappers for it; ideally
 *     there shouldn't be any pointers to it at all, except the one passed in.
 *
 * -   `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
 *     returns a pointer to the transplanted object, which might be `target`
 *     but might be some other object in the same compartment. Use that.
 *
 * The reason for this last rule is that JS_TransplantObject does very strange
 * things in some cases, like swapping `target`'s brain with that of another
 * object. Leaving `target` behaving like its former self is not a goal.
 *
 * We don't have a good way to recover from failure in this function, so
 * we intentionally crash instead.
 */

JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx, HandleObject origobj,
                                            HandleObject target) {
  AssertHeapIsIdle();
  MOZ_ASSERT(origobj != target);
  MOZ_ASSERT(!origobj->is<CrossCompartmentWrapperObject>());
  MOZ_ASSERT(!target->is<CrossCompartmentWrapperObject>());
  MOZ_ASSERT(origobj->getClass() == target->getClass());
  ReleaseAssertObjectHasNoWrappers(cx, target);

  RootedValue origv(cx, ObjectValue(*origobj));
  RootedObject newIdentity(cx);

  // Don't allow a compacting GC to observe any intermediate state.
  AutoDisableCompactingGC nocgc(cx);

  AutoDisableProxyCheck adpc;

  JSCompartment* destination = target->compartment();

  if (origobj->compartment() == destination) {
    // If the original object is in the same compartment as the
    // destination, then we know that we won't find a wrapper in the
    // destination's cross compartment map and that the same
    // object will continue to work.
    AutoCompartment ac(cx, origobj);
    if (!JSObject::swap(cx, origobj, target)) MOZ_CRASH();
    newIdentity = origobj;
  } else if (WrapperMap::Ptr p = destination->lookupWrapper(origv)) {
    // There might already be a wrapper for the original object in
    // the new compartment. If there is, we use its identity and swap
    // in the contents of |target|.
    newIdentity = &p->value().get().toObject();

    // When we remove origv from the wrapper map, its wrapper, newIdentity,
    // must immediately cease to be a cross-compartment wrapper. Nuke it.
    destination->removeWrapper(p);
    NukeCrossCompartmentWrapper(cx, newIdentity);

    AutoCompartment ac(cx, newIdentity);
    if (!JSObject::swap(cx, newIdentity, target)) MOZ_CRASH();
  } else {
    // Otherwise, we use |target| for the new identity object.
    newIdentity = target;
  }

  // Now, iterate through other scopes looking for references to the old
  // object, and update the relevant cross-compartment wrappers. We do this
  // even if origobj is in the same compartment as target and thus
  // `newIdentity == origobj`, because this process also clears out any
  // cached wrapper state.
  if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) MOZ_CRASH();

  // Lastly, update the original object to point to the new one.
  if (origobj->compartment() != destination) {
    RootedObject newIdentityWrapper(cx, newIdentity);
    AutoCompartment ac(cx, origobj);
    if (!JS_WrapObject(cx, &newIdentityWrapper)) MOZ_CRASH();
    MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
    if (!JSObject::swap(cx, origobj, newIdentityWrapper)) MOZ_CRASH();
    if (!origobj->compartment()->putWrapper(
            cx, CrossCompartmentKey(newIdentity), origv))
      MOZ_CRASH();
  }

  // The new identity object might be one of several things. Return it to avoid
  // ambiguity.
  return newIdentity;
}

/*
 * Recompute all cross-compartment wrappers for an object, resetting state.
 * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
 * the inner window and global object.
 */
JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(JSContext* cx,
                                                      HandleObject obj) {
  return RemapAllWrappersForObject(cx, obj, obj);
}

JS_PUBLIC_API bool JS_InitStandardClasses(JSContext* cx, HandleObject obj) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  assertSameCompartment(cx, obj);

  Rooted<GlobalObject*> global(cx, &obj->global());
  return GlobalObject::initStandardClasses(cx, global);
}

#define EAGER_ATOM(name) NAME_OFFSET(name)

typedef struct JSStdName {
  size_t atomOffset; /* offset of atom pointer in JSAtomState */
  JSProtoKey key;
  bool isDummy() const { return key == JSProto_Null; }
  bool isSentinel() const { return key == JSProto_LIMIT; }
} JSStdName;

static const JSStdName* LookupStdName(const JSAtomState& names, JSAtom* name,
                                      const JSStdName* table) {
  for (unsigned i = 0; !table[i].isSentinel(); i++) {
    if (table[i].isDummy()) continue;
    JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
    MOZ_ASSERT(atom);
    if (name == atom) return &table[i];
  }

  return nullptr;
}

/*
 * Table of standard classes, indexed by JSProtoKey. For entries where the
 * JSProtoKey does not correspond to a class with a meaningful constructor, we
 * insert a null entry into the table.
 */
#define STD_NAME_ENTRY(name, init, clasp) {EAGER_ATOM(name), JSProto_##name},
#define STD_DUMMY_ENTRY(name, init, dummy) {0, JSProto_Null},
static const JSStdName standard_class_names[] = {
    JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY){0, JSProto_LIMIT}};

/*
 * Table of top-level function and constant names and the JSProtoKey of the
 * standard class that initializes them.
 */
static const JSStdName builtin_property_names[] = {
    {EAGER_ATOM(eval), JSProto_Object},

    /* Global properties and functions defined by the Number class. */
    {EAGER_ATOM(NaN), JSProto_Number},
    {EAGER_ATOM(Infinity), JSProto_Number},
    {EAGER_ATOM(isNaN), JSProto_Number},
    {EAGER_ATOM(isFinite), JSProto_Number},
    {EAGER_ATOM(parseFloat), JSProto_Number},
    {EAGER_ATOM(parseInt), JSProto_Number},

    /* String global functions. */
    {EAGER_ATOM(escape), JSProto_String},
    {EAGER_ATOM(unescape), JSProto_String},
    {EAGER_ATOM(decodeURI), JSProto_String},
    {EAGER_ATOM(encodeURI), JSProto_String},
    {EAGER_ATOM(decodeURIComponent), JSProto_String},
    {EAGER_ATOM(encodeURIComponent), JSProto_String},
    {EAGER_ATOM(uneval), JSProto_String},

    {0, JSProto_LIMIT}};

#undef EAGER_ATOM

JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx, HandleObject obj,
                                           HandleId id, bool* resolved) {
  const JSStdName* stdnm;

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);

  Handle<GlobalObject*> global = obj.as<GlobalObject>();
  *resolved = false;

  if (!JSID_IS_ATOM(id)) return true;

  /* Check whether we're resolving 'undefined', and define it if so. */
  JSAtom* idAtom = JSID_TO_ATOM(id);
  JSAtom* undefinedAtom = cx->names().undefined;
  if (idAtom == undefinedAtom) {
    *resolved = true;
    return DefineDataProperty(
        cx, global, id, UndefinedHandleValue,
        JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
  }

  /* Try for class constructors/prototypes named by well-known atoms. */
  stdnm = LookupStdName(cx->names(), idAtom, standard_class_names);

  /* Try less frequently used top-level functions and constants. */
  if (!stdnm)
    stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names);

  if (stdnm && GlobalObject::skipDeselectedConstructor(cx, stdnm->key))
    stdnm = nullptr;

  // If this class is anonymous, then it doesn't exist as a global
  // property, so we won't resolve anything.
  JSProtoKey key = stdnm ? stdnm->key : JSProto_Null;
  if (key != JSProto_Null) {
    const Class* clasp = ProtoKeyToClass(key);
    if (!clasp || !(clasp->flags & JSCLASS_IS_ANONYMOUS)) {
      if (!GlobalObject::ensureConstructor(cx, global, key)) return false;

      *resolved = true;
      return true;
    }
  }

  // There is no such property to resolve. An ordinary resolve hook would
  // just return true at this point. But the global object is special in one
  // more way: its prototype chain is lazily initialized. That is,
  // global->getProto() might be null right now because we haven't created
  // Object.prototype yet. Force it now.
  return GlobalObject::getOrCreateObjectPrototype(cx, global);
}

JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names, jsid id,
                                              JSObject* maybeObj) {
  MOZ_ASSERT_IF(maybeObj, maybeObj->is<GlobalObject>());

  // The global object's resolve hook is special: JS_ResolveStandardClass
  // initializes the prototype chain lazily. Only attempt to optimize here
  // if we know the prototype chain has been initialized.
  if (!maybeObj || !maybeObj->staticPrototype()) return true;

  if (!JSID_IS_ATOM(id)) return false;

  JSAtom* atom = JSID_TO_ATOM(id);

  // This will return true even for deselected constructors.  (To do
  // better, we need a JSContext here; it's fine as it is.)

  return atom == names.undefined ||
         LookupStdName(names, atom, standard_class_names) ||
         LookupStdName(names, atom, builtin_property_names);
}

JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
                                               HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  Handle<GlobalObject*> global = obj.as<GlobalObject>();
  return GlobalObject::initStandardClasses(cx, global);
}

static bool EnumerateUnresolvedStandardClasses(JSContext* cx,
                                               Handle<GlobalObject*> global,
                                               AutoIdVector& properties,
                                               const JSStdName* table) {
  for (unsigned i = 0; !table[i].isSentinel(); i++) {
    if (table[i].isDummy()) continue;

    JSProtoKey key = table[i].key;

    // If the standard class has been resolved, the properties have been
    // defined on the global so we don't need to add them here.
    if (global->isStandardClassResolved(key)) continue;

    if (GlobalObject::skipDeselectedConstructor(cx, key)) continue;

    if (const Class* clasp = ProtoKeyToClass(key)) {
      if (clasp->flags & JSCLASS_IS_ANONYMOUS) continue;
      if (!clasp->specShouldDefineConstructor()) continue;
    }

    jsid id = NameToId(AtomStateOffsetToName(cx->names(), table[i].atomOffset));
    if (!properties.append(id)) return false;
  }

  return true;
}

JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(JSContext* cx,
                                                  JS::HandleObject obj,
                                                  JS::AutoIdVector& properties,
                                                  bool enumerableOnly) {
  if (enumerableOnly) {
    // There are no enumerable lazy properties.
    return true;
  }

  Handle<GlobalObject*> global = obj.as<GlobalObject>();

  // It's fine to always append |undefined| here, it's non-configurable and
  // the enumeration code filters duplicates.
  if (!properties.append(NameToId(cx->names().undefined))) return false;

  if (!EnumerateUnresolvedStandardClasses(cx, global, properties,
                                          standard_class_names))
    return false;
  if (!EnumerateUnresolvedStandardClasses(cx, global, properties,
                                          builtin_property_names))
    return false;

  return true;
}

JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
                                     MutableHandleObject objp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JSObject* obj = GlobalObject::getOrCreateConstructor(cx, key);
  if (!obj) return false;
  objp.set(obj);
  return true;
}

JS_PUBLIC_API bool JS_GetClassPrototype(JSContext* cx, JSProtoKey key,
                                        MutableHandleObject objp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JSObject* proto = GlobalObject::getOrCreatePrototype(cx, key);
  if (!proto) return false;
  objp.set(proto);
  return true;
}

namespace JS {

JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
                                MutableHandleId idp) {
  idp.set(NameToId(ClassName(key, cx)));
}

} /* namespace JS */

JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, HandleId id) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, id);

  if (!JSID_IS_ATOM(id)) return JSProto_Null;

  JSAtom* atom = JSID_TO_ATOM(id);
  const JSStdName* stdnm =
      LookupStdName(cx->names(), atom, standard_class_names);
  if (!stdnm) return JSProto_Null;

  if (GlobalObject::skipDeselectedConstructor(cx, stdnm->key))
    return JSProto_Null;

  MOZ_ASSERT(MOZ_ARRAY_LENGTH(standard_class_names) == JSProto_LIMIT + 1);
  return static_cast<JSProtoKey>(stdnm - standard_class_names);
}

JS_PUBLIC_API JSObject* JS_GetObjectPrototype(JSContext* cx,
                                              HandleObject forObj) {
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, forObj);
  Rooted<GlobalObject*> global(cx, &forObj->global());
  return GlobalObject::getOrCreateObjectPrototype(cx, global);
}

JS_PUBLIC_API JSObject* JS_GetFunctionPrototype(JSContext* cx,
                                                HandleObject forObj) {
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, forObj);
  Rooted<GlobalObject*> global(cx, &forObj->global());
  return GlobalObject::getOrCreateFunctionPrototype(cx, global);
}

JS_PUBLIC_API JSObject* JS_GetArrayPrototype(JSContext* cx,
                                             HandleObject forObj) {
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, forObj);
  Rooted<GlobalObject*> global(cx, &forObj->global());
  return GlobalObject::getOrCreateArrayPrototype(cx, global);
}

JS_PUBLIC_API JSObject* JS_GetErrorPrototype(JSContext* cx) {
  CHECK_REQUEST(cx);
  Rooted<GlobalObject*> global(cx, cx->global());
  return GlobalObject::getOrCreateCustomErrorPrototype(cx, global, JSEXN_ERR);
}

JS_PUBLIC_API JSObject* JS_GetIteratorPrototype(JSContext* cx) {
  CHECK_REQUEST(cx);
  Rooted<GlobalObject*> global(cx, cx->global());
  return GlobalObject::getOrCreateIteratorPrototype(cx, global);
}

JS_PUBLIC_API JSObject* JS_GetGlobalForObject(JSContext* cx, JSObject* obj) {
  AssertHeapIsIdle();
  assertSameCompartment(cx, obj);
  return &obj->global();
}

extern JS_PUBLIC_API bool JS_IsGlobalObject(JSObject* obj) {
  return obj->is<GlobalObject>();
}

extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj) {
  return &obj->as<GlobalObject>().lexicalEnvironment();
}

extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj) {
  return obj->is<GlobalObject>() ||
         obj->compartment()->getNonSyntacticLexicalEnvironment(obj);
}

extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj) {
  JSObject* lexical = nullptr;
  if (obj->is<GlobalObject>())
    lexical = JS_GlobalLexicalEnvironment(obj);
  else
    lexical = obj->compartment()->getNonSyntacticLexicalEnvironment(obj);
  MOZ_ASSERT(lexical);
  return lexical;
}

JS_PUBLIC_API JSObject* JS_GetGlobalForCompartmentOrNull(JSContext* cx,
                                                         JSCompartment* c) {
  AssertHeapIsIdleOrIterating();
  assertSameCompartment(cx, c);
  return c->maybeGlobal();
}

JS_PUBLIC_API JSObject* JS::CurrentGlobalOrNull(JSContext* cx) {
  AssertHeapIsIdleOrIterating();
  CHECK_REQUEST(cx);
  if (!cx->compartment()) return nullptr;
  return cx->global();
}

JS_PUBLIC_API Value JS::detail::ComputeThis(JSContext* cx, Value* vp) {
  AssertHeapIsIdle();
  assertSameCompartment(cx, JSValueArray(vp, 2));

  MutableHandleValue thisv = MutableHandleValue::fromMarkedLocation(&vp[1]);
  if (!BoxNonStrictThis(cx, thisv, thisv)) return NullValue();

  return thisv;
}

JS_PUBLIC_API void* JS_malloc(JSContext* cx, size_t nbytes) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return static_cast<void*>(cx->zone()->pod_malloc<uint8_t>(nbytes));
}

JS_PUBLIC_API void* JS_realloc(JSContext* cx, void* p, size_t oldBytes,
                               size_t newBytes) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return static_cast<void*>(cx->zone()->pod_realloc<uint8_t>(
      static_cast<uint8_t*>(p), oldBytes, newBytes));
}

JS_PUBLIC_API void JS_free(JSContext* cx, void* p) { return js_free(p); }

JS_PUBLIC_API void JS_freeop(JSFreeOp* fop, void* p) {
  return FreeOp::get(fop)->free_(p);
}

JS_PUBLIC_API void JS_updateMallocCounter(JSContext* cx, size_t nbytes) {
  return cx->updateMallocCounter(nbytes);
}

JS_PUBLIC_API char* JS_strdup(JSContext* cx, const char* s) {
  AssertHeapIsIdle();
  return DuplicateString(cx, s).release();
}

#undef JS_AddRoot

JS_PUBLIC_API bool JS_AddExtraGCRootsTracer(JSContext* cx,
                                            JSTraceDataOp traceOp, void* data) {
  return cx->runtime()->gc.addBlackRootsTracer(traceOp, data);
}

JS_PUBLIC_API void JS_RemoveExtraGCRootsTracer(JSContext* cx,
                                               JSTraceDataOp traceOp,
                                               void* data) {
  return cx->runtime()->gc.removeBlackRootsTracer(traceOp, data);
}

JS_PUBLIC_API bool JS::IsIdleGCTaskNeeded(JSRuntime* rt) {
  // Currently, we only collect nursery during idle time.
  return rt->gc.nursery().needIdleTimeCollection();
}

JS_PUBLIC_API void JS::RunIdleTimeGCTask(JSRuntime* rt) {
  GCRuntime& gc = rt->gc;
  if (gc.nursery().needIdleTimeCollection()) {
    gc.minorGC(JS::gcreason::IDLE_TIME_COLLECTION);
  }
}

JS_PUBLIC_API void JS_GC(JSContext* cx) {
  AssertHeapIsIdle();
  JS::PrepareForFullGC(cx);
  cx->runtime()->gc.gc(GC_NORMAL, JS::gcreason::API);
}

JS_PUBLIC_API void JS_MaybeGC(JSContext* cx) {
  GCRuntime& gc = cx->runtime()->gc;
  gc.maybeGC(cx->zone());
}

JS_PUBLIC_API void JS_SetGCCallback(JSContext* cx, JSGCCallback cb,
                                    void* data) {
  AssertHeapIsIdle();
  cx->runtime()->gc.setGCCallback(cb, data);
}

JS_PUBLIC_API void JS_SetObjectsTenuredCallback(JSContext* cx,
                                                JSObjectsTenuredCallback cb,
                                                void* data) {
  AssertHeapIsIdle();
  cx->runtime()->gc.setObjectsTenuredCallback(cb, data);
}

JS_PUBLIC_API bool JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb,
                                          void* data) {
  AssertHeapIsIdle();
  return cx->runtime()->gc.addFinalizeCallback(cb, data);
}

JS_PUBLIC_API void JS_RemoveFinalizeCallback(JSContext* cx,
                                             JSFinalizeCallback cb) {
  cx->runtime()->gc.removeFinalizeCallback(cb);
}

JS_PUBLIC_API bool JS_AddWeakPointerZonesCallback(JSContext* cx,
                                                  JSWeakPointerZonesCallback cb,
                                                  void* data) {
  AssertHeapIsIdle();
  return cx->runtime()->gc.addWeakPointerZonesCallback(cb, data);
}

JS_PUBLIC_API void JS_RemoveWeakPointerZonesCallback(
    JSContext* cx, JSWeakPointerZonesCallback cb) {
  cx->runtime()->gc.removeWeakPointerZonesCallback(cb);
}

JS_PUBLIC_API bool JS_AddWeakPointerCompartmentCallback(
    JSContext* cx, JSWeakPointerCompartmentCallback cb, void* data) {
  AssertHeapIsIdle();
  return cx->runtime()->gc.addWeakPointerCompartmentCallback(cb, data);
}

JS_PUBLIC_API void JS_RemoveWeakPointerCompartmentCallback(
    JSContext* cx, JSWeakPointerCompartmentCallback cb) {
  cx->runtime()->gc.removeWeakPointerCompartmentCallback(cb);
}

JS_PUBLIC_API void JS_UpdateWeakPointerAfterGC(JS::Heap<JSObject*>* objp) {
  JS_UpdateWeakPointerAfterGCUnbarriered(objp->unsafeGet());
}

JS_PUBLIC_API void JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp) {
  if (IsAboutToBeFinalizedUnbarriered(objp)) *objp = nullptr;
}

JS_PUBLIC_API void JS_SetGCParameter(JSContext* cx, JSGCParamKey key,
                                     uint32_t value) {
  cx->runtime()->gc.waitBackgroundSweepEnd();
  AutoLockGC lock(cx->runtime());
  MOZ_ALWAYS_TRUE(cx->runtime()->gc.setParameter(key, value, lock));
}

JS_PUBLIC_API void JS_ResetGCParameter(JSContext* cx, JSGCParamKey key) {
  cx->runtime()->gc.waitBackgroundSweepEnd();
  AutoLockGC lock(cx->runtime());
  cx->runtime()->gc.resetParameter(key, lock);
}

JS_PUBLIC_API uint32_t JS_GetGCParameter(JSContext* cx, JSGCParamKey key) {
  AutoLockGC lock(cx->runtime());
  return cx->runtime()->gc.getParameter(key, lock);
}

static const size_t NumGCConfigs = 14;
struct JSGCConfig {
  JSGCParamKey key;
  uint32_t value;
};

JS_PUBLIC_API void JS_SetGCParametersBasedOnAvailableMemory(JSContext* cx,
                                                            uint32_t availMem) {
  static const JSGCConfig minimal[NumGCConfigs] = {
      {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024},
      {JSGC_SLICE_TIME_BUDGET, 30},
      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
      {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 40},
      {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 0},
      {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300},
      {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 120},
      {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 120},
      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
      {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
      {JSGC_ALLOCATION_THRESHOLD, 1},
      {JSGC_MODE, JSGC_MODE_INCREMENTAL}};

  const JSGCConfig* config = minimal;
  if (availMem > 512) {
    static const JSGCConfig nominal[NumGCConfigs] = {
        {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024},
        {JSGC_SLICE_TIME_BUDGET, 30},
        {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1000},
        {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 500},
        {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 100},
        {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300},
        {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 150},
        {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 150},
        {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
        {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
        {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
        {JSGC_ALLOCATION_THRESHOLD, 30},
        {JSGC_MODE, JSGC_MODE_ZONE}};

    config = nominal;
  }

  for (size_t i = 0; i < NumGCConfigs; i++)
    JS_SetGCParameter(cx, config[i].key, config[i].value);
}

JS_PUBLIC_API JSString* JS_NewExternalString(JSContext* cx,
                                             const char16_t* chars,
                                             size_t length,
                                             const JSStringFinalizer* fin) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JSString* s = JSExternalString::new_(cx, chars, length, fin);
  return s;
}

JS_PUBLIC_API JSString* JS_NewMaybeExternalString(JSContext* cx,
                                                  const char16_t* chars,
                                                  size_t length,
                                                  const JSStringFinalizer* fin,
                                                  bool* allocatedExternal) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewMaybeExternalString(cx, chars, length, fin, allocatedExternal);
}

extern JS_PUBLIC_API bool JS_IsExternalString(JSString* str) {
  return str->isExternal();
}

extern JS_PUBLIC_API const JSStringFinalizer* JS_GetExternalStringFinalizer(
    JSString* str) {
  return str->asExternal().externalFinalizer();
}

static void SetNativeStackQuotaAndLimit(JSContext* cx, JS::StackKind kind,
                                        size_t stackSize) {
  cx->nativeStackQuota[kind] = stackSize;

#if JS_STACK_GROWTH_DIRECTION > 0
  if (stackSize == 0) {
    cx->nativeStackLimit[kind] = UINTPTR_MAX;
  } else {
    MOZ_ASSERT(cx->nativeStackBase <= size_t(-1) - stackSize);
    cx->nativeStackLimit[kind] = cx->nativeStackBase + stackSize - 1;
  }
#else
  if (stackSize == 0) {
    cx->nativeStackLimit[kind] = 0;
  } else {
    MOZ_ASSERT(cx->nativeStackBase >= stackSize);
    cx->nativeStackLimit[kind] = cx->nativeStackBase - (stackSize - 1);
  }
#endif
}

JS_PUBLIC_API void JS_SetNativeStackQuota(JSContext* cx,
                                          size_t systemCodeStackSize,
                                          size_t trustedScriptStackSize,
                                          size_t untrustedScriptStackSize) {
  MOZ_ASSERT(cx->requestDepth == 0);

  if (!trustedScriptStackSize)
    trustedScriptStackSize = systemCodeStackSize;
  else
    MOZ_ASSERT(trustedScriptStackSize < systemCodeStackSize);

  if (!untrustedScriptStackSize)
    untrustedScriptStackSize = trustedScriptStackSize;
  else
    MOZ_ASSERT(untrustedScriptStackSize < trustedScriptStackSize);

  SetNativeStackQuotaAndLimit(cx, JS::StackForSystemCode, systemCodeStackSize);
  SetNativeStackQuotaAndLimit(cx, JS::StackForTrustedScript,
                              trustedScriptStackSize);
  SetNativeStackQuotaAndLimit(cx, JS::StackForUntrustedScript,
                              untrustedScriptStackSize);

  if (cx->isCooperativelyScheduled()) cx->initJitStackLimit();
}

/************************************************************************/

JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, HandleValue value,
                                MutableHandleId idp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  return ValueToId<CanGC>(cx, value, idp);
}

JS_PUBLIC_API bool JS_StringToId(JSContext* cx, HandleString string,
                                 MutableHandleId idp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, string);
  RootedValue value(cx, StringValue(string));
  return ValueToId<CanGC>(cx, value, idp);
}

JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id, MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, id);
  vp.set(IdToValue(id));
  assertSameCompartment(cx, vp);
  return true;
}

JS_PUBLIC_API bool JS::ToPrimitive(JSContext* cx, HandleObject obj, JSType hint,
                                   MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  MOZ_ASSERT(obj != nullptr);
  MOZ_ASSERT(hint == JSTYPE_UNDEFINED || hint == JSTYPE_STRING ||
             hint == JSTYPE_NUMBER);
  vp.setObject(*obj);
  return ToPrimitiveSlow(cx, hint, vp);
}

JS_PUBLIC_API bool JS::GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args,
                                                  JSType* result) {
  if (!args.get(0).isString()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
                              "\"string\", \"number\", or \"default\"",
                              InformalValueTypeName(args.get(0)));
    return false;
  }

  RootedString str(cx, args.get(0).toString());
  bool match;

  if (!EqualStrings(cx, str, cx->names().default_, &match)) return false;
  if (match) {
    *result = JSTYPE_UNDEFINED;
    return true;
  }

  if (!EqualStrings(cx, str, cx->names().string, &match)) return false;
  if (match) {
    *result = JSTYPE_STRING;
    return true;
  }

  if (!EqualStrings(cx, str, cx->names().number, &match)) return false;
  if (match) {
    *result = JSTYPE_NUMBER;
    return true;
  }

  JSAutoByteString bytes;
  const char* source = ValueToSourceForError(cx, args.get(0), bytes);
  if (!source) {
    ReportOutOfMemory(cx);
    return false;
  }

  JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
                             JSMSG_NOT_EXPECTED_TYPE, "Symbol.toPrimitive",
                             "\"string\", \"number\", or \"default\"", source);
  return false;
}

JS_PUBLIC_API JSObject* JS_InitClass(JSContext* cx, HandleObject obj,
                                     HandleObject parent_proto,
                                     const JSClass* clasp, JSNative constructor,
                                     unsigned nargs, const JSPropertySpec* ps,
                                     const JSFunctionSpec* fs,
                                     const JSPropertySpec* static_ps,
                                     const JSFunctionSpec* static_fs) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, parent_proto);
  return InitClass(cx, obj, parent_proto, Valueify(clasp), constructor, nargs,
                   ps, fs, static_ps, static_fs);
}

JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(JSContext* cx,
                                                  HandleObject ctor,
                                                  HandleObject proto) {
  return LinkConstructorAndPrototype(cx, ctor, proto);
}

JS_PUBLIC_API const JSClass* JS_GetClass(JSObject* obj) {
  return obj->getJSClass();
}

JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx, HandleObject obj,
                                 const JSClass* clasp, CallArgs* args) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
#ifdef DEBUG
  if (args) {
    assertSameCompartment(cx, obj);
    assertSameCompartment(cx, args->thisv(), args->calleev());
  }
#endif
  if (!obj || obj->getJSClass() != clasp) {
    if (args) ReportIncompatibleMethod(cx, *args, Valueify(clasp));
    return false;
  }
  return true;
}

JS_PUBLIC_API bool JS_HasInstance(JSContext* cx, HandleObject obj,
                                  HandleValue value, bool* bp) {
  AssertHeapIsIdle();
  assertSameCompartment(cx, obj, value);
  return HasInstance(cx, obj, value, bp);
}

JS_PUBLIC_API void* JS_GetPrivate(JSObject* obj) {
  /* This function can be called by a finalizer. */
  return obj->as<NativeObject>().getPrivate();
}

JS_PUBLIC_API void JS_SetPrivate(JSObject* obj, void* data) {
  /* This function can be called by a finalizer. */
  obj->as<NativeObject>().setPrivate(data);
}

JS_PUBLIC_API void* JS_GetInstancePrivate(JSContext* cx, HandleObject obj,
                                          const JSClass* clasp,
                                          CallArgs* args) {
  if (!JS_InstanceOf(cx, obj, clasp, args)) return nullptr;
  return obj->as<NativeObject>().getPrivate();
}

JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx, HandleObject proto) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, proto);

  RootedValue cval(cx);
  if (!GetProperty(cx, proto, proto, cx->names().constructor, &cval))
    return nullptr;
  if (!IsFunctionObject(cval)) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NO_CONSTRUCTOR, proto->getClass()->name);
    return nullptr;
  }
  return &cval.toObject();
}

bool JS::CompartmentBehaviors::extraWarnings(JSContext* cx) const {
  return extraWarningsOverride_.get(cx->options().extraWarnings());
}

JS::CompartmentCreationOptions&
JS::CompartmentCreationOptions::setSystemZone() {
  zoneSpec_ = JS::SystemZone;
  zonePointer_ = nullptr;
  return *this;
}

JS::CompartmentCreationOptions& JS::CompartmentCreationOptions::setExistingZone(
    JSObject* obj) {
  zoneSpec_ = JS::ExistingZone;
  zonePointer_ = obj->zone();
  return *this;
}

JS::CompartmentCreationOptions&
JS::CompartmentCreationOptions::setNewZoneInNewZoneGroup() {
  zoneSpec_ = JS::NewZoneInNewZoneGroup;
  zonePointer_ = nullptr;
  return *this;
}

JS::CompartmentCreationOptions&
JS::CompartmentCreationOptions::setNewZoneInSystemZoneGroup() {
  zoneSpec_ = JS::NewZoneInSystemZoneGroup;
  zonePointer_ = nullptr;
  return *this;
}

JS::CompartmentCreationOptions&
JS::CompartmentCreationOptions::setNewZoneInExistingZoneGroup(JSObject* obj) {
  zoneSpec_ = JS::NewZoneInExistingZoneGroup;
  zonePointer_ = obj->zone()->group();
  return *this;
}

const JS::CompartmentCreationOptions& JS::CompartmentCreationOptionsRef(
    JSCompartment* compartment) {
  return compartment->creationOptions();
}

const JS::CompartmentCreationOptions& JS::CompartmentCreationOptionsRef(
    JSObject* obj) {
  return obj->compartment()->creationOptions();
}

const JS::CompartmentCreationOptions& JS::CompartmentCreationOptionsRef(
    JSContext* cx) {
  return cx->compartment()->creationOptions();
}

bool JS::CompartmentCreationOptions::getSharedMemoryAndAtomicsEnabled() const {
#if defined(ENABLE_SHARED_ARRAY_BUFFER)
  return sharedMemoryAndAtomics_;
#else
  return false;
#endif
}

JS::CompartmentCreationOptions&
JS::CompartmentCreationOptions::setSharedMemoryAndAtomicsEnabled(bool flag) {
#if defined(ENABLE_SHARED_ARRAY_BUFFER)
  sharedMemoryAndAtomics_ = flag;
#endif
  return *this;
}

JS::CompartmentBehaviors& JS::CompartmentBehaviorsRef(
    JSCompartment* compartment) {
  return compartment->behaviors();
}

JS::CompartmentBehaviors& JS::CompartmentBehaviorsRef(JSObject* obj) {
  return obj->compartment()->behaviors();
}

JS::CompartmentBehaviors& JS::CompartmentBehaviorsRef(JSContext* cx) {
  return cx->compartment()->behaviors();
}

JS_PUBLIC_API JSObject* JS_NewGlobalObject(
    JSContext* cx, const JSClass* clasp, JSPrincipals* principals,
    JS::OnNewGlobalHookOption hookOption,
    const JS::CompartmentOptions& options) {
  MOZ_RELEASE_ASSERT(
      cx->runtime()->hasInitializedSelfHosting(),
      "Must call JS::InitSelfHostedCode() before creating a global");

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return GlobalObject::new_(cx, Valueify(clasp), principals, hookOption,
                            options);
}

JS_PUBLIC_API void JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global) {
  MOZ_ASSERT(global->is<GlobalObject>());

  // Off thread parsing and compilation tasks create a dummy global which is
  // then merged back into the host compartment. Since it used to be a
  // global, it will still have this trace hook, but it does not have a
  // meaning relative to its new compartment. We can safely skip it.
  //
  // Similarly, if we GC when creating the global, we may not have set that
  // global's compartment's global pointer yet. In this case, the compartment
  // will not yet contain anything that needs to be traced.
  if (!global->isOwnGlobal(trc)) return;

  // Trace the compartment for any GC things that should only stick around if
  // we know the global is live.
  global->compartment()->traceGlobal(trc);

  if (JSTraceOp trace = global->compartment()->creationOptions().getTrace())
    trace(trc, global);
}

JS_PUBLIC_API void JS_FireOnNewGlobalObject(JSContext* cx,
                                            JS::HandleObject global) {
  // This hook is infallible, because we don't really want arbitrary script
  // to be able to throw errors during delicate global creation routines.
  // This infallibility will eat OOM and slow script, but if that happens
  // we'll likely run up into them again soon in a fallible context.
  assertSameCompartment(cx, global);
  Rooted<js::GlobalObject*> globalObject(cx, &global->as<GlobalObject>());
  Debugger::onNewGlobalObject(cx, globalObject);
}

JS_PUBLIC_API JSObject* JS_NewObject(JSContext* cx, const JSClass* jsclasp) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  const Class* clasp = Valueify(jsclasp);
  if (!clasp) clasp = &PlainObject::class_; /* default class is Object */

  MOZ_ASSERT(clasp != &JSFunction::class_);
  MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));

  return NewObjectWithClassProto(cx, clasp, nullptr);
}

JS_PUBLIC_API JSObject* JS_NewObjectWithGivenProto(JSContext* cx,
                                                   const JSClass* jsclasp,
                                                   HandleObject proto) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, proto);

  const Class* clasp = Valueify(jsclasp);
  if (!clasp) clasp = &PlainObject::class_; /* default class is Object */

  MOZ_ASSERT(clasp != &JSFunction::class_);
  MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));

  return NewObjectWithGivenProto(cx, clasp, proto);
}

JS_PUBLIC_API JSObject* JS_NewPlainObject(JSContext* cx) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return NewBuiltinClassInstance<PlainObject>(cx);
}

JS_PUBLIC_API JSObject* JS_NewObjectForConstructor(JSContext* cx,
                                                   const JSClass* clasp,
                                                   const CallArgs& args) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  Value callee = args.calleev();
  assertSameCompartment(cx, callee);
  RootedObject obj(cx, &callee.toObject());
  return CreateThis(cx, Valueify(clasp), obj);
}

JS_PUBLIC_API bool JS_IsNative(JSObject* obj) { return obj->isNative(); }

JS_PUBLIC_API void JS::AssertObjectBelongsToCurrentThread(JSObject* obj) {
  JSRuntime* rt = obj->compartment()->runtimeFromAnyThread();
  MOZ_RELEASE_ASSERT(CurrentThreadCanAccessRuntime(rt));
}

/*** Standard internal methods **********************************************/

JS_PUBLIC_API bool JS_GetPrototype(JSContext* cx, HandleObject obj,
                                   MutableHandleObject result) {
  assertSameCompartment(cx, obj);
  return GetPrototype(cx, obj, result);
}

JS_PUBLIC_API bool JS_SetPrototype(JSContext* cx, HandleObject obj,
                                   HandleObject proto) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, proto);

  return SetPrototype(cx, obj, proto);
}

JS_PUBLIC_API bool JS_GetPrototypeIfOrdinary(JSContext* cx, HandleObject obj,
                                             bool* isOrdinary,
                                             MutableHandleObject result) {
  assertSameCompartment(cx, obj);
  return GetPrototypeIfOrdinary(cx, obj, isOrdinary, result);
}

JS_PUBLIC_API bool JS_IsExtensible(JSContext* cx, HandleObject obj,
                                   bool* extensible) {
  assertSameCompartment(cx, obj);
  return IsExtensible(cx, obj, extensible);
}

JS_PUBLIC_API bool JS_PreventExtensions(JSContext* cx, JS::HandleObject obj,
                                        ObjectOpResult& result) {
  assertSameCompartment(cx, obj);
  return PreventExtensions(cx, obj, result);
}

JS_PUBLIC_API bool JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj,
                                            bool* succeeded) {
  assertSameCompartment(cx, obj);
  return SetImmutablePrototype(cx, obj, succeeded);
}

JS_PUBLIC_API bool JS_GetOwnPropertyDescriptorById(
    JSContext* cx, HandleObject obj, HandleId id,
    MutableHandle<PropertyDescriptor> desc) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);

  return GetOwnPropertyDescriptor(cx, obj, id, desc);
}

JS_PUBLIC_API bool JS_GetOwnPropertyDescriptor(
    JSContext* cx, HandleObject obj, const char* name,
    MutableHandle<PropertyDescriptor> desc) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc);
}

JS_PUBLIC_API bool JS_GetOwnUCPropertyDescriptor(
    JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
    MutableHandle<PropertyDescriptor> desc) {
  JSAtom* atom = AtomizeChars(cx, name, namelen);
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc);
}

JS_PUBLIC_API bool JS_GetPropertyDescriptorById(
    JSContext* cx, HandleObject obj, HandleId id,
    MutableHandle<PropertyDescriptor> desc) {
  assertSameCompartment(cx, obj, id);
  return GetPropertyDescriptor(cx, obj, id, desc);
}

JS_PUBLIC_API bool JS_GetPropertyDescriptor(
    JSContext* cx, HandleObject obj, const char* name,
    MutableHandle<PropertyDescriptor> desc) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_GetPropertyDescriptorById(cx, obj, id, desc);
}

JS_PUBLIC_API bool JS_GetUCPropertyDescriptor(
    JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
    MutableHandle<PropertyDescriptor> desc) {
  JSAtom* atom = AtomizeChars(cx, name, namelen);
  if (!atom) {
    return false;
  }
  RootedId id(cx, AtomToId(atom));
  return JS_GetPropertyDescriptorById(cx, obj, id, desc);
}

static bool DefinePropertyByDescriptor(JSContext* cx, HandleObject obj,
                                       HandleId id,
                                       Handle<PropertyDescriptor> desc,
                                       ObjectOpResult& result) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id, desc);
  return DefineProperty(cx, obj, id, desc, result);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id,
                                         Handle<PropertyDescriptor> desc,
                                         ObjectOpResult& result) {
  return DefinePropertyByDescriptor(cx, obj, id, desc, result);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id,
                                         Handle<PropertyDescriptor> desc) {
  ObjectOpResult result;
  return DefinePropertyByDescriptor(cx, obj, id, desc, result) &&
         result.checkStrict(cx, obj, id);
}

static bool DefineAccessorPropertyById(JSContext* cx, HandleObject obj,
                                       HandleId id, const JSNativeWrapper& get,
                                       const JSNativeWrapper& set,
                                       unsigned attrs) {
  JSGetterOp getter = JS_CAST_NATIVE_TO(get.op, JSGetterOp);
  JSSetterOp setter = JS_CAST_NATIVE_TO(set.op, JSSetterOp);

  // JSPROP_READONLY has no meaning when accessors are involved. Ideally we'd
  // throw if this happens, but we've accepted it for long enough that it's
  // not worth trying to make callers change their ways. Just flip it off on
  // its way through the API layer so that we can enforce this internally.
  if (attrs & (JSPROP_GETTER | JSPROP_SETTER)) attrs &= ~JSPROP_READONLY;

  // When we use DefineProperty, we need full scriptable Function objects rather
  // than JSNatives. However, we might be pulling this property descriptor off
  // of something with JSNative property descriptors. If we are, wrap them in
  // JS Function objects.

  // If !(attrs & JSPROP_PROPOP_ACCESSORS), then getter/setter are both
  // possibly-null JSNatives (or possibly-null JSFunction* if JSPROP_GETTER or
  // JSPROP_SETTER is appropriately set).
  if (!(attrs & JSPROP_PROPOP_ACCESSORS)) {
    if (getter && !(attrs & JSPROP_GETTER)) {
      RootedAtom atom(cx, IdToFunctionName(cx, id, FunctionPrefixKind::Get));
      if (!atom) return false;
      JSFunction* getobj = NewNativeFunction(cx, (Native)getter, 0, atom);
      if (!getobj) return false;

      if (get.info) getobj->setJitInfo(get.info);

      getter = JS_DATA_TO_FUNC_PTR(GetterOp, getobj);
      attrs |= JSPROP_GETTER;
    }
    if (setter && !(attrs & JSPROP_SETTER)) {
      // Root just the getter, since the setter is not yet a JSObject.
      AutoRooterGetterSetter getRoot(cx, JSPROP_GETTER, &getter, nullptr);
      RootedAtom atom(cx, IdToFunctionName(cx, id, FunctionPrefixKind::Set));
      if (!atom) return false;
      JSFunction* setobj = NewNativeFunction(cx, (Native)setter, 1, atom);
      if (!setobj) return false;

      if (set.info) setobj->setJitInfo(set.info);

      setter = JS_DATA_TO_FUNC_PTR(SetterOp, setobj);
      attrs |= JSPROP_SETTER;
    }
  } else {
    attrs &= ~JSPROP_PROPOP_ACCESSORS;
  }

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(
      cx, obj, id,
      (attrs & JSPROP_GETTER) ? JS_FUNC_TO_DATA_PTR(JSObject*, getter)
                              : nullptr,
      (attrs & JSPROP_SETTER) ? JS_FUNC_TO_DATA_PTR(JSObject*, setter)
                              : nullptr);

  return js::DefineAccessorProperty(cx, obj, id, getter, setter, attrs);
}

static bool DefineDataPropertyById(JSContext* cx, HandleObject obj, HandleId id,
                                   HandleValue value, unsigned attrs) {
  MOZ_ASSERT(
      !(attrs & (JSPROP_GETTER | JSPROP_SETTER | JSPROP_PROPOP_ACCESSORS)));

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id, value);

  return js::DefineDataProperty(cx, obj, id, value, attrs);
}

/*
 * Wrapper functions to create wrappers with no corresponding JSJitInfo from API
 * function arguments.
 */
static JSNativeWrapper NativeOpWrapper(Native native) {
  JSNativeWrapper ret;
  ret.op = native;
  ret.info = nullptr;
  return ret;
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, HandleValue value,
                                         unsigned attrs) {
  return DefineDataPropertyById(cx, obj, id, value, attrs);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, Native getter,
                                         Native setter, unsigned attrs) {
  return DefineAccessorPropertyById(cx, obj, id, NativeOpWrapper(getter),
                                    NativeOpWrapper(setter), attrs);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, HandleObject valueArg,
                                         unsigned attrs) {
  RootedValue value(cx, ObjectValue(*valueArg));
  return DefineDataPropertyById(cx, obj, id, value, attrs);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, HandleString valueArg,
                                         unsigned attrs) {
  RootedValue value(cx, StringValue(valueArg));
  return DefineDataPropertyById(cx, obj, id, value, attrs);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, int32_t valueArg,
                                         unsigned attrs) {
  Value value = Int32Value(valueArg);
  return DefineDataPropertyById(cx, obj, id,
                                HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, uint32_t valueArg,
                                         unsigned attrs) {
  Value value = NumberValue(valueArg);
  return DefineDataPropertyById(cx, obj, id,
                                HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefinePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, double valueArg,
                                         unsigned attrs) {
  Value value = NumberValue(valueArg);
  return DefineDataPropertyById(cx, obj, id,
                                HandleValue::fromMarkedLocation(&value), attrs);
}

static bool DefineAccessorProperty(JSContext* cx, HandleObject obj,
                                   const char* name,
                                   const JSNativeWrapper& getter,
                                   const JSNativeWrapper& setter,
                                   unsigned attrs) {
  AutoRooterGetterSetter gsRoot(cx, attrs, const_cast<JSNative*>(&getter.op),
                                const_cast<JSNative*>(&setter.op));

  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));

  return DefineAccessorPropertyById(cx, obj, id, getter, setter, attrs);
}

static bool DefineDataProperty(JSContext* cx, HandleObject obj,
                               const char* name, HandleValue value,
                               unsigned attrs) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));

  return DefineDataPropertyById(cx, obj, id, value, attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, HandleValue value,
                                     unsigned attrs) {
  return DefineDataProperty(cx, obj, name, value, attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, Native getter,
                                     Native setter, unsigned attrs) {
  return DefineAccessorProperty(cx, obj, name, NativeOpWrapper(getter),
                                NativeOpWrapper(setter), attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, HandleObject valueArg,
                                     unsigned attrs) {
  RootedValue value(cx, ObjectValue(*valueArg));
  return DefineDataProperty(cx, obj, name, value, attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, HandleString valueArg,
                                     unsigned attrs) {
  RootedValue value(cx, StringValue(valueArg));
  return DefineDataProperty(cx, obj, name, value, attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, int32_t valueArg,
                                     unsigned attrs) {
  Value value = Int32Value(valueArg);
  return DefineDataProperty(cx, obj, name,
                            HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, uint32_t valueArg,
                                     unsigned attrs) {
  Value value = NumberValue(valueArg);
  return DefineDataProperty(cx, obj, name,
                            HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefineProperty(JSContext* cx, HandleObject obj,
                                     const char* name, double valueArg,
                                     unsigned attrs) {
  Value value = NumberValue(valueArg);
  return DefineDataProperty(cx, obj, name,
                            HandleValue::fromMarkedLocation(&value), attrs);
}

#define AUTO_NAMELEN(s, n) (((n) == (size_t)-1) ? js_strlen(s) : (n))

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       Handle<PropertyDescriptor> desc,
                                       ObjectOpResult& result) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return DefinePropertyByDescriptor(cx, obj, id, desc, result);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       Handle<PropertyDescriptor> desc) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  ObjectOpResult result;
  return DefinePropertyByDescriptor(cx, obj, id, desc, result) &&
         result.checkStrict(cx, obj, id);
}

static bool DefineUCAccessorProperty(JSContext* cx, HandleObject obj,
                                     const char16_t* name, size_t namelen,
                                     Native getter, Native setter,
                                     unsigned attrs) {
  AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter);
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return DefineAccessorPropertyById(cx, obj, id, NativeOpWrapper(getter),
                                    NativeOpWrapper(setter), attrs);
}

static bool DefineUCDataProperty(JSContext* cx, HandleObject obj,
                                 const char16_t* name, size_t namelen,
                                 HandleValue value, unsigned attrs) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return DefineDataPropertyById(cx, obj, id, value, attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       HandleValue value, unsigned attrs) {
  return DefineUCDataProperty(cx, obj, name, namelen, value, attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       Native getter, Native setter,
                                       unsigned attrs) {
  return DefineUCAccessorProperty(cx, obj, name, namelen, getter, setter,
                                  attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       HandleObject valueArg, unsigned attrs) {
  RootedValue value(cx, ObjectValue(*valueArg));
  return DefineUCDataProperty(cx, obj, name, namelen, value, attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       HandleString valueArg, unsigned attrs) {
  RootedValue value(cx, StringValue(valueArg));
  return DefineUCDataProperty(cx, obj, name, namelen, value, attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       int32_t valueArg, unsigned attrs) {
  Value value = Int32Value(valueArg);
  return DefineUCDataProperty(cx, obj, name, namelen,
                              HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       uint32_t valueArg, unsigned attrs) {
  Value value = NumberValue(valueArg);
  return DefineUCDataProperty(cx, obj, name, namelen,
                              HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefineUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       double valueArg, unsigned attrs) {
  Value value = NumberValue(valueArg);
  return DefineUCDataProperty(cx, obj, name, namelen,
                              HandleValue::fromMarkedLocation(&value), attrs);
}

static bool DefineAccessorElement(JSContext* cx, HandleObject obj,
                                  uint32_t index, unsigned attrs, Native getter,
                                  Native setter) {
  assertSameCompartment(cx, obj);
  AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter);
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) return false;
  return DefineAccessorPropertyById(cx, obj, id, NativeOpWrapper(getter),
                                    NativeOpWrapper(setter), attrs);
}

static bool DefineDataElement(JSContext* cx, HandleObject obj, uint32_t index,
                              HandleValue value, unsigned attrs) {
  assertSameCompartment(cx, obj, value);
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) return false;
  return DefineDataPropertyById(cx, obj, id, value, attrs);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, HandleValue value,
                                    unsigned attrs) {
  return ::DefineDataElement(cx, obj, index, value, attrs);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, Native getter,
                                    Native setter, unsigned attrs) {
  return DefineAccessorElement(cx, obj, index, attrs, getter, setter);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, HandleObject valueArg,
                                    unsigned attrs) {
  RootedValue value(cx, ObjectValue(*valueArg));
  return ::DefineDataElement(cx, obj, index, value, attrs);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, HandleString valueArg,
                                    unsigned attrs) {
  RootedValue value(cx, StringValue(valueArg));
  return ::DefineDataElement(cx, obj, index, value, attrs);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, int32_t valueArg,
                                    unsigned attrs) {
  Value value = Int32Value(valueArg);
  return ::DefineDataElement(cx, obj, index,
                             HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, uint32_t valueArg,
                                    unsigned attrs) {
  Value value = NumberValue(valueArg);
  return ::DefineDataElement(cx, obj, index,
                             HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_DefineElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, double valueArg,
                                    unsigned attrs) {
  Value value = NumberValue(valueArg);
  return ::DefineDataElement(cx, obj, index,
                             HandleValue::fromMarkedLocation(&value), attrs);
}

JS_PUBLIC_API bool JS_HasPropertyById(JSContext* cx, HandleObject obj,
                                      HandleId id, bool* foundp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);

  return HasProperty(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_HasProperty(JSContext* cx, HandleObject obj,
                                  const char* name, bool* foundp) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_HasPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_HasUCProperty(JSContext* cx, HandleObject obj,
                                    const char16_t* name, size_t namelen,
                                    bool* foundp) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_HasPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_HasElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, bool* foundp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) return false;
  return JS_HasPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_HasOwnPropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, bool* foundp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);

  return HasOwnProperty(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_HasOwnProperty(JSContext* cx, HandleObject obj,
                                     const char* name, bool* foundp) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_HasOwnPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_ForwardGetPropertyTo(JSContext* cx, HandleObject obj,
                                           HandleId id, HandleValue receiver,
                                           MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id, receiver);

  return GetProperty(cx, obj, receiver, id, vp);
}

JS_PUBLIC_API bool JS_ForwardGetElementTo(JSContext* cx, HandleObject obj,
                                          uint32_t index, HandleObject receiver,
                                          MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  return GetElement(cx, obj, receiver, index, vp);
}

JS_PUBLIC_API bool JS_GetPropertyById(JSContext* cx, HandleObject obj,
                                      HandleId id, MutableHandleValue vp) {
  RootedValue receiver(cx, ObjectValue(*obj));
  return JS_ForwardGetPropertyTo(cx, obj, id, receiver, vp);
}

JS_PUBLIC_API bool JS_GetProperty(JSContext* cx, HandleObject obj,
                                  const char* name, MutableHandleValue vp) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_GetPropertyById(cx, obj, id, vp);
}

JS_PUBLIC_API bool JS_GetUCProperty(JSContext* cx, HandleObject obj,
                                    const char16_t* name, size_t namelen,
                                    MutableHandleValue vp) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_GetPropertyById(cx, obj, id, vp);
}

JS_PUBLIC_API bool JS_GetElement(JSContext* cx, HandleObject objArg,
                                 uint32_t index, MutableHandleValue vp) {
  return JS_ForwardGetElementTo(cx, objArg, index, objArg, vp);
}

JS_PUBLIC_API bool JS_ForwardSetPropertyTo(JSContext* cx, HandleObject obj,
                                           HandleId id, HandleValue v,
                                           HandleValue receiver,
                                           ObjectOpResult& result) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id, v, receiver);

  return SetProperty(cx, obj, id, v, receiver, result);
}

JS_PUBLIC_API bool JS_SetPropertyById(JSContext* cx, HandleObject obj,
                                      HandleId id, HandleValue v) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id, v);

  RootedValue receiver(cx, ObjectValue(*obj));
  ObjectOpResult ignored;
  return SetProperty(cx, obj, id, v, receiver, ignored);
}

JS_PUBLIC_API bool JS_SetProperty(JSContext* cx, HandleObject obj,
                                  const char* name, HandleValue v) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_SetPropertyById(cx, obj, id, v);
}

JS_PUBLIC_API bool JS_SetUCProperty(JSContext* cx, HandleObject obj,
                                    const char16_t* name, size_t namelen,
                                    HandleValue v) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_SetPropertyById(cx, obj, id, v);
}

static bool SetElement(JSContext* cx, HandleObject obj, uint32_t index,
                       HandleValue v) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, v);

  RootedValue receiver(cx, ObjectValue(*obj));
  ObjectOpResult ignored;
  return SetElement(cx, obj, index, v, receiver, ignored);
}

JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, HandleValue v) {
  return SetElement(cx, obj, index, v);
}

JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, HandleObject v) {
  RootedValue value(cx, ObjectOrNullValue(v));
  return SetElement(cx, obj, index, value);
}

JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, HandleString v) {
  RootedValue value(cx, StringValue(v));
  return SetElement(cx, obj, index, value);
}

JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, int32_t v) {
  RootedValue value(cx, NumberValue(v));
  return SetElement(cx, obj, index, value);
}

JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, uint32_t v) {
  RootedValue value(cx, NumberValue(v));
  return SetElement(cx, obj, index, value);
}

JS_PUBLIC_API bool JS_SetElement(JSContext* cx, HandleObject obj,
                                 uint32_t index, double v) {
  RootedValue value(cx, NumberValue(v));
  return SetElement(cx, obj, index, value);
}

JS_PUBLIC_API bool JS_DeletePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id, ObjectOpResult& result) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);

  return DeleteProperty(cx, obj, id, result);
}

JS_PUBLIC_API bool JS_DeleteProperty(JSContext* cx, HandleObject obj,
                                     const char* name, ObjectOpResult& result) {
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return DeleteProperty(cx, obj, id, result);
}

JS_PUBLIC_API bool JS_DeleteUCProperty(JSContext* cx, HandleObject obj,
                                       const char16_t* name, size_t namelen,
                                       ObjectOpResult& result) {
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return DeleteProperty(cx, obj, id, result);
}

JS_PUBLIC_API bool JS_DeleteElement(JSContext* cx, HandleObject obj,
                                    uint32_t index, ObjectOpResult& result) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  return DeleteElement(cx, obj, index, result);
}

JS_PUBLIC_API bool JS_DeletePropertyById(JSContext* cx, HandleObject obj,
                                         HandleId id) {
  ObjectOpResult ignored;
  return JS_DeletePropertyById(cx, obj, id, ignored);
}

JS_PUBLIC_API bool JS_DeleteProperty(JSContext* cx, HandleObject obj,
                                     const char* name) {
  ObjectOpResult ignored;
  return JS_DeleteProperty(cx, obj, name, ignored);
}

JS_PUBLIC_API bool JS_DeleteElement(JSContext* cx, HandleObject obj,
                                    uint32_t index) {
  ObjectOpResult ignored;
  return JS_DeleteElement(cx, obj, index, ignored);
}

JS_PUBLIC_API bool JS_Enumerate(JSContext* cx, HandleObject obj,
                                JS::MutableHandle<IdVector> props) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, props);
  MOZ_ASSERT(props.empty());

  AutoIdVector ids(cx);
  if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, &ids)) return false;

  return props.append(ids.begin(), ids.end());
}

JS_PUBLIC_API bool JS::IsCallable(JSObject* obj) { return obj->isCallable(); }

JS_PUBLIC_API bool JS::IsConstructor(JSObject* obj) {
  return obj->isConstructor();
}

JS_PUBLIC_API bool JS_CallFunctionValue(JSContext* cx, HandleObject obj,
                                        HandleValue fval,
                                        const HandleValueArray& args,
                                        MutableHandleValue rval) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, fval, args);

  InvokeArgs iargs(cx);
  if (!FillArgumentsFromArraylike(cx, iargs, args)) return false;

  RootedValue thisv(cx, ObjectOrNullValue(obj));
  return Call(cx, fval, thisv, iargs, rval);
}

JS_PUBLIC_API bool JS_CallFunction(JSContext* cx, HandleObject obj,
                                   HandleFunction fun,
                                   const HandleValueArray& args,
                                   MutableHandleValue rval) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, fun, args);

  InvokeArgs iargs(cx);
  if (!FillArgumentsFromArraylike(cx, iargs, args)) return false;

  RootedValue fval(cx, ObjectValue(*fun));
  RootedValue thisv(cx, ObjectOrNullValue(obj));
  return Call(cx, fval, thisv, iargs, rval);
}

JS_PUBLIC_API bool JS_CallFunctionName(JSContext* cx, HandleObject obj,
                                       const char* name,
                                       const HandleValueArray& args,
                                       MutableHandleValue rval) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, args);

  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;

  RootedValue fval(cx);
  RootedId id(cx, AtomToId(atom));
  if (!GetProperty(cx, obj, obj, id, &fval)) return false;

  InvokeArgs iargs(cx);
  if (!FillArgumentsFromArraylike(cx, iargs, args)) return false;

  RootedValue thisv(cx, ObjectOrNullValue(obj));
  return Call(cx, fval, thisv, iargs, rval);
}

JS_PUBLIC_API bool JS::Call(JSContext* cx, HandleValue thisv, HandleValue fval,
                            const JS::HandleValueArray& args,
                            MutableHandleValue rval) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, thisv, fval, args);

  InvokeArgs iargs(cx);
  if (!FillArgumentsFromArraylike(cx, iargs, args)) return false;

  return Call(cx, fval, thisv, iargs, rval);
}

JS_PUBLIC_API bool JS::Construct(JSContext* cx, HandleValue fval,
                                 HandleObject newTarget,
                                 const JS::HandleValueArray& args,
                                 MutableHandleObject objp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, fval, newTarget, args);

  if (!IsConstructor(fval)) {
    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval,
                     nullptr);
    return false;
  }

  RootedValue newTargetVal(cx, ObjectValue(*newTarget));
  if (!IsConstructor(newTargetVal)) {
    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK,
                     newTargetVal, nullptr);
    return false;
  }

  ConstructArgs cargs(cx);
  if (!FillArgumentsFromArraylike(cx, cargs, args)) return false;

  return js::Construct(cx, fval, cargs, newTargetVal, objp);
}

JS_PUBLIC_API bool JS::Construct(JSContext* cx, HandleValue fval,
                                 const JS::HandleValueArray& args,
                                 MutableHandleObject objp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, fval, args);

  if (!IsConstructor(fval)) {
    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval,
                     nullptr);
    return false;
  }

  ConstructArgs cargs(cx);
  if (!FillArgumentsFromArraylike(cx, cargs, args)) return false;

  return js::Construct(cx, fval, cargs, fval, objp);
}

/* * */

JS_PUBLIC_API bool JS_AlreadyHasOwnPropertyById(JSContext* cx, HandleObject obj,
                                                HandleId id, bool* foundp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);

  if (!obj->isNative()) return js::HasOwnProperty(cx, obj, id, foundp);

  RootedNativeObject nativeObj(cx, &obj->as<NativeObject>());
  Rooted<PropertyResult> prop(cx);
  NativeLookupOwnPropertyNoResolve(cx, nativeObj, id, &prop);
  *foundp = prop.isFound();
  return true;
}

JS_PUBLIC_API bool JS_AlreadyHasOwnProperty(JSContext* cx, HandleObject obj,
                                            const char* name, bool* foundp) {
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_AlreadyHasOwnUCProperty(JSContext* cx, HandleObject obj,
                                              const char16_t* name,
                                              size_t namelen, bool* foundp) {
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return false;
  RootedId id(cx, AtomToId(atom));
  return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_AlreadyHasOwnElement(JSContext* cx, HandleObject obj,
                                           uint32_t index, bool* foundp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  RootedId id(cx);
  if (!IndexToId(cx, index, &id)) return false;
  return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
}

JS_PUBLIC_API bool JS_FreezeObject(JSContext* cx, HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  return FreezeObject(cx, obj);
}

static bool DeepFreezeSlot(JSContext* cx, const Value& v) {
  if (v.isPrimitive()) return true;
  RootedObject obj(cx, &v.toObject());
  return JS_DeepFreezeObject(cx, obj);
}

JS_PUBLIC_API bool JS_DeepFreezeObject(JSContext* cx, HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  /* Assume that non-extensible objects are already deep-frozen, to avoid
   * divergence. */
  bool extensible;
  if (!IsExtensible(cx, obj, &extensible)) return false;
  if (!extensible) return true;

  if (!FreezeObject(cx, obj)) return false;

  /* Walk slots in obj and if any value is a non-null object, seal it. */
  if (obj->isNative()) {
    RootedNativeObject nobj(cx, &obj->as<NativeObject>());
    for (uint32_t i = 0, n = nobj->slotSpan(); i < n; ++i) {
      if (!DeepFreezeSlot(cx, nobj->getSlot(i))) return false;
    }
    for (uint32_t i = 0, n = nobj->getDenseInitializedLength(); i < n; ++i) {
      if (!DeepFreezeSlot(cx, nobj->getDenseElement(i))) return false;
    }
  }

  return true;
}

static bool DefineSelfHostedProperty(JSContext* cx, HandleObject obj,
                                     HandleId id, const char* getterName,
                                     const char* setterName, unsigned attrs) {
  JSAtom* getterNameAtom = Atomize(cx, getterName, strlen(getterName));
  if (!getterNameAtom) return false;
  RootedPropertyName getterNameName(cx, getterNameAtom->asPropertyName());

  RootedAtom name(cx, IdToFunctionName(cx, id));
  if (!name) return false;

  RootedValue getterValue(cx);
  if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), getterNameName,
                                           name, 0, &getterValue)) {
    return false;
  }
  MOZ_ASSERT(getterValue.isObject() && getterValue.toObject().is<JSFunction>());
  RootedFunction getterFunc(cx, &getterValue.toObject().as<JSFunction>());
  JSNative getterOp = JS_DATA_TO_FUNC_PTR(JSNative, getterFunc.get());

  RootedFunction setterFunc(cx);
  if (setterName) {
    JSAtom* setterNameAtom = Atomize(cx, setterName, strlen(setterName));
    if (!setterNameAtom) return false;
    RootedPropertyName setterNameName(cx, setterNameAtom->asPropertyName());

    RootedValue setterValue(cx);
    if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), setterNameName,
                                             name, 0, &setterValue)) {
      return false;
    }
    MOZ_ASSERT(setterValue.isObject() &&
               setterValue.toObject().is<JSFunction>());
    setterFunc = &setterValue.toObject().as<JSFunction>();
  }
  JSNative setterOp = JS_DATA_TO_FUNC_PTR(JSNative, setterFunc.get());

  return DefineAccessorPropertyById(cx, obj, id, NativeOpWrapper(getterOp),
                                    NativeOpWrapper(setterOp), attrs);
}

JS_PUBLIC_API JSObject* JS_DefineObject(JSContext* cx, HandleObject obj,
                                        const char* name,
                                        const JSClass* jsclasp,
                                        unsigned attrs) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  const Class* clasp = Valueify(jsclasp);
  if (!clasp) clasp = &PlainObject::class_; /* default class is Object */

  RootedObject nobj(cx, NewObjectWithClassProto(cx, clasp, nullptr));
  if (!nobj) return nullptr;

  RootedValue nobjValue(cx, ObjectValue(*nobj));
  if (!DefineDataProperty(cx, obj, name, nobjValue, attrs)) return nullptr;

  return nobj;
}

static inline Value ValueFromScalar(double x) { return DoubleValue(x); }
static inline Value ValueFromScalar(int32_t x) { return Int32Value(x); }

template <typename T>
static bool DefineConstScalar(JSContext* cx, HandleObject obj,
                              const JSConstScalarSpec<T>* cds) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  unsigned attrs = JSPROP_READONLY | JSPROP_PERMANENT;
  for (; cds->name; cds++) {
    RootedValue value(cx, ValueFromScalar(cds->val));
    if (!DefineDataProperty(cx, obj, cds->name, value, attrs)) return false;
  }
  return true;
}

JS_PUBLIC_API bool JS_DefineConstDoubles(JSContext* cx, HandleObject obj,
                                         const JSConstDoubleSpec* cds) {
  return DefineConstScalar(cx, obj, cds);
}
JS_PUBLIC_API bool JS_DefineConstIntegers(JSContext* cx, HandleObject obj,
                                          const JSConstIntegerSpec* cis) {
  return DefineConstScalar(cx, obj, cis);
}

JS_PUBLIC_API bool JSPropertySpec::getValue(JSContext* cx,
                                            MutableHandleValue vp) const {
  MOZ_ASSERT(!isAccessor());

  if (value.type == JSVAL_TYPE_STRING) {
    RootedAtom atom(cx, Atomize(cx, value.string, strlen(value.string)));
    if (!atom) return false;
    vp.setString(atom);
  } else {
    MOZ_ASSERT(value.type == JSVAL_TYPE_INT32);
    vp.setInt32(value.int32);
  }

  return true;
}

static JS::SymbolCode PropertySpecNameToSymbolCode(const char* name) {
  MOZ_ASSERT(JS::PropertySpecNameIsSymbol(name));
  uintptr_t u = reinterpret_cast<uintptr_t>(name);
  return JS::SymbolCode(u - 1);
}

bool PropertySpecNameToId(JSContext* cx, const char* name, MutableHandleId id,
                          js::PinningBehavior pin = js::DoNotPinAtom) {
  if (JS::PropertySpecNameIsSymbol(name)) {
    JS::SymbolCode which = PropertySpecNameToSymbolCode(name);
    id.set(SYMBOL_TO_JSID(cx->wellKnownSymbols().get(which)));
  } else {
    JSAtom* atom = Atomize(cx, name, strlen(name), pin);
    if (!atom) return false;
    id.set(AtomToId(atom));
  }
  return true;
}

JS_PUBLIC_API bool JS::PropertySpecNameToPermanentId(JSContext* cx,
                                                     const char* name,
                                                     jsid* idp) {
  // We are calling fromMarkedLocation(idp) even though idp points to a
  // location that will never be marked. This is OK because the whole point
  // of this API is to populate *idp with a jsid that does not need to be
  // marked.
  return PropertySpecNameToId(
      cx, name, MutableHandleId::fromMarkedLocation(idp), js::PinAtom);
}

JS_PUBLIC_API bool JS_DefineProperties(JSContext* cx, HandleObject obj,
                                       const JSPropertySpec* ps) {
  RootedId id(cx);

  for (; ps->name; ps++) {
    if (!PropertySpecNameToId(cx, ps->name, &id)) return false;

    if (ps->isAccessor()) {
      if (ps->isSelfHosted()) {
        if (!DefineSelfHostedProperty(
                cx, obj, id, ps->accessors.getter.selfHosted.funname,
                ps->accessors.setter.selfHosted.funname, ps->flags)) {
          return false;
        }
      } else {
        if (!DefineAccessorPropertyById(
                cx, obj, id, ps->accessors.getter.native,
                ps->accessors.setter.native, ps->flags)) {
          return false;
        }
      }
    } else {
      RootedValue v(cx);
      if (!ps->getValue(cx, &v)) return false;

      if (!DefineDataPropertyById(cx, obj, id, v,
                                  ps->flags & ~JSPROP_INTERNAL_USE_BIT))
        return false;
    }
  }
  return true;
}

JS_PUBLIC_API bool JS::ObjectToCompletePropertyDescriptor(
    JSContext* cx, HandleObject obj, HandleValue descObj,
    MutableHandle<PropertyDescriptor> desc) {
  // |obj| can be in a different compartment here. The caller is responsible
  // for wrapping it (see JS_WrapPropertyDescriptor).
  assertSameCompartment(cx, descObj);
  if (!ToPropertyDescriptor(cx, descObj, true, desc)) return false;
  CompletePropertyDescriptor(desc);
  desc.object().set(obj);
  return true;
}

JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JSContext* cx,
                                                        JSObject* objArg) {
  RootedObject obj(cx, objArg);
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  if (!obj->isNative()) return;

  const Class* clasp = obj->getClass();
  unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp);
  unsigned numSlots = obj->as<NativeObject>().slotSpan();
  for (unsigned i = numReserved; i < numSlots; i++)
    obj->as<NativeObject>().setSlot(i, UndefinedValue());
}

JS_PUBLIC_API Value JS_GetReservedSlot(JSObject* obj, uint32_t index) {
  return obj->as<NativeObject>().getReservedSlot(index);
}

JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
                                      const Value& value) {
  obj->as<NativeObject>().setReservedSlot(index, value);
}

JS_PUBLIC_API JSObject* JS_NewArrayObject(
    JSContext* cx, const JS::HandleValueArray& contents) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  assertSameCompartment(cx, contents);
  return NewDenseCopiedArray(cx, contents.length(), contents.begin());
}

JS_PUBLIC_API JSObject* JS_NewArrayObject(JSContext* cx, size_t length) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return NewDenseFullyAllocatedArray(cx, length);
}

inline bool IsGivenTypeObject(JSContext* cx, JS::HandleObject obj,
                              const ESClass& typeClass, bool* isType) {
  assertSameCompartment(cx, obj);

  ESClass cls;
  if (!GetBuiltinClass(cx, obj, &cls)) return false;

  *isType = cls == typeClass;
  return true;
}

JS_PUBLIC_API bool JS_IsArrayObject(JSContext* cx, JS::HandleObject obj,
                                    bool* isArray) {
  return IsGivenTypeObject(cx, obj, ESClass::Array, isArray);
}

JS_PUBLIC_API bool JS_IsArrayObject(JSContext* cx, JS::HandleValue value,
                                    bool* isArray) {
  if (!value.isObject()) {
    *isArray = false;
    return true;
  }

  RootedObject obj(cx, &value.toObject());
  return JS_IsArrayObject(cx, obj, isArray);
}

JS_PUBLIC_API bool JS_GetArrayLength(JSContext* cx, HandleObject obj,
                                     uint32_t* lengthp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  return GetLengthProperty(cx, obj, lengthp);
}

JS_PUBLIC_API bool JS_SetArrayLength(JSContext* cx, HandleObject obj,
                                     uint32_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  return SetLengthProperty(cx, obj, length);
}

JS_PUBLIC_API bool JS::IsMapObject(JSContext* cx, JS::HandleObject obj,
                                   bool* isMap) {
  return IsGivenTypeObject(cx, obj, ESClass::Map, isMap);
}

JS_PUBLIC_API bool JS::IsSetObject(JSContext* cx, JS::HandleObject obj,
                                   bool* isSet) {
  return IsGivenTypeObject(cx, obj, ESClass::Set, isSet);
}

JS_PUBLIC_API void JS_HoldPrincipals(JSPrincipals* principals) {
  ++principals->refcount;
}

JS_PUBLIC_API void JS_DropPrincipals(JSContext* cx, JSPrincipals* principals) {
  int rc = --principals->refcount;
  if (rc == 0) cx->runtime()->destroyPrincipals(principals);
}

JS_PUBLIC_API void JS_SetSecurityCallbacks(JSContext* cx,
                                           const JSSecurityCallbacks* scb) {
  MOZ_ASSERT(scb != &NullSecurityCallbacks);
  cx->runtime()->securityCallbacks = scb ? scb : &NullSecurityCallbacks;
}

JS_PUBLIC_API const JSSecurityCallbacks* JS_GetSecurityCallbacks(
    JSContext* cx) {
  return (cx->runtime()->securityCallbacks != &NullSecurityCallbacks)
             ? cx->runtime()->securityCallbacks.ref()
             : nullptr;
}

JS_PUBLIC_API void JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin) {
  cx->runtime()->setTrustedPrincipals(prin);
}

extern JS_PUBLIC_API void JS_InitDestroyPrincipalsCallback(
    JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals) {
  MOZ_ASSERT(destroyPrincipals);
  MOZ_ASSERT(!cx->runtime()->destroyPrincipals);
  cx->runtime()->destroyPrincipals = destroyPrincipals;
}

extern JS_PUBLIC_API void JS_InitReadPrincipalsCallback(
    JSContext* cx, JSReadPrincipalsOp read) {
  MOZ_ASSERT(read);
  MOZ_ASSERT(!cx->runtime()->readPrincipals);
  cx->runtime()->readPrincipals = read;
}

JS_PUBLIC_API JSFunction* JS_NewFunction(JSContext* cx, JSNative native,
                                         unsigned nargs, unsigned flags,
                                         const char* name) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  RootedAtom atom(cx);
  if (name) {
    atom = Atomize(cx, name, strlen(name));
    if (!atom) return nullptr;
  }

  return (flags & JSFUN_CONSTRUCTOR)
             ? NewNativeConstructor(cx, native, nargs, atom)
             : NewNativeFunction(cx, native, nargs, atom);
}

JS_PUBLIC_API JSFunction* JS::GetSelfHostedFunction(JSContext* cx,
                                                    const char* selfHostedName,
                                                    HandleId id,
                                                    unsigned nargs) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, id);

  RootedAtom name(cx, IdToFunctionName(cx, id));
  if (!name) return nullptr;

  JSAtom* shAtom = Atomize(cx, selfHostedName, strlen(selfHostedName));
  if (!shAtom) return nullptr;
  RootedPropertyName shName(cx, shAtom->asPropertyName());
  RootedValue funVal(cx);
  if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
                                           nargs, &funVal))
    return nullptr;
  return &funVal.toObject().as<JSFunction>();
}

JS_PUBLIC_API JSFunction* JS::NewFunctionFromSpec(JSContext* cx,
                                                  const JSFunctionSpec* fs,
                                                  HandleId id) {
  assertSameCompartment(cx, id);

  // Delay cloning self-hosted functions until they are called. This is
  // achieved by passing DefineFunction a nullptr JSNative which produces an
  // interpreted JSFunction where !hasScript. Interpreted call paths then
  // call InitializeLazyFunctionScript if !hasScript.
  if (fs->selfHostedName) {
    MOZ_ASSERT(!fs->call.op);
    MOZ_ASSERT(!fs->call.info);

    JSAtom* shAtom =
        Atomize(cx, fs->selfHostedName, strlen(fs->selfHostedName));
    if (!shAtom) return nullptr;
    RootedPropertyName shName(cx, shAtom->asPropertyName());
    RootedAtom name(cx, IdToFunctionName(cx, id));
    if (!name) return nullptr;
    RootedValue funVal(cx);
    if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name,
                                             fs->nargs, &funVal)) {
      return nullptr;
    }
    return &funVal.toObject().as<JSFunction>();
  }

  RootedAtom atom(cx, IdToFunctionName(cx, id));
  if (!atom) return nullptr;

  JSFunction* fun;
  if (!fs->call.op)
    fun =
        NewScriptedFunction(cx, fs->nargs, JSFunction::INTERPRETED_LAZY, atom);
  else if (fs->flags & JSFUN_CONSTRUCTOR)
    fun = NewNativeConstructor(cx, fs->call.op, fs->nargs, atom);
  else
    fun = NewNativeFunction(cx, fs->call.op, fs->nargs, atom);
  if (!fun) return nullptr;

  if (fs->call.info) fun->setJitInfo(fs->call.info);
  return fun;
}

static bool CreateNonSyntacticEnvironmentChain(JSContext* cx,
                                               AutoObjectVector& envChain,
                                               MutableHandleObject env,
                                               MutableHandleScope scope) {
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  if (!js::CreateObjectsForEnvironmentChain(cx, envChain, globalLexical, env))
    return false;

  if (!envChain.empty()) {
    scope.set(GlobalScope::createEmpty(cx, ScopeKind::NonSyntactic));
    if (!scope) return false;

    // The XPConnect subscript loader, which may pass in its own
    // environments to load scripts in, expects the environment chain to
    // be the holder of "var" declarations. In SpiderMonkey, such objects
    // are called "qualified varobjs", the "qualified" part meaning the
    // declaration was qualified by "var". There is only sadness.
    //
    // See JSObject::isQualifiedVarObj.
    if (!JSObject::setQualifiedVarObj(cx, env)) return false;

    // Also get a non-syntactic lexical environment to capture 'let' and
    // 'const' bindings. To persist lexical bindings, we have a 1-1
    // mapping with the final unwrapped environment object (the
    // environment that stores the 'var' bindings) and the lexical
    // environment.
    //
    // TODOshu: disallow the subscript loader from using non-distinguished
    // objects as dynamic scopes.
    env.set(
        cx->compartment()->getOrCreateNonSyntacticLexicalEnvironment(cx, env));
    if (!env) return false;
  } else {
    scope.set(&cx->global()->emptyGlobalScope());
  }

  return true;
}

static bool IsFunctionCloneable(HandleFunction fun) {
  // If a function was compiled with non-global syntactic environments on
  // the environment chain, we could have baked in EnvironmentCoordinates
  // into the script. We cannot clone it without breaking the compiler's
  // assumptions.
  for (ScopeIter si(fun->nonLazyScript()->enclosingScope()); si; si++) {
    if (si.scope()->is<GlobalScope>()) return true;
    if (si.hasSyntacticEnvironment()) return false;
  }

  return true;
}

static JSObject* CloneFunctionObject(JSContext* cx, HandleObject funobj,
                                     HandleObject env, HandleScope scope) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, env);
  MOZ_ASSERT(env);
  // Note that funobj can be in a different compartment.

  if (!funobj->is<JSFunction>()) {
    AutoCompartment ac(cx, funobj);
    RootedValue v(cx, ObjectValue(*funobj));
    ReportIsNotFunction(cx, v);
    return nullptr;
  }

  RootedFunction fun(cx, &funobj->as<JSFunction>());
  if (fun->isInterpretedLazy()) {
    AutoCompartment ac(cx, funobj);
    if (!JSFunction::getOrCreateScript(cx, fun)) return nullptr;
  }

  // Only allow cloning normal, interpreted functions.
  if (fun->isNative() || fun->isBoundFunction() ||
      fun->kind() != JSFunction::NormalFunction || fun->isExtended()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_CANT_CLONE_OBJECT);
    return nullptr;
  }

  if (!IsFunctionCloneable(fun)) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BAD_CLONE_FUNOBJ_SCOPE);
    return nullptr;
  }

  if (CanReuseScriptForClone(cx->compartment(), fun, env)) {
  // If the script is to be reused, either the script can already handle
  // non-syntactic scopes, or there is only the standard global lexical
  // scope.
#ifdef DEBUG
    // Fail here if we OOM during debug asserting.
    // CloneFunctionReuseScript will delazify the script anyways, so we
    // are not creating an extra failure condition for DEBUG builds.
    if (!JSFunction::getOrCreateScript(cx, fun)) return nullptr;
    MOZ_ASSERT(scope->as<GlobalScope>().isSyntactic() ||
               fun->nonLazyScript()->hasNonSyntacticScope());
#endif
    return CloneFunctionReuseScript(cx, fun, env, fun->getAllocKind());
  }

  JSFunction* clone =
      CloneFunctionAndScript(cx, fun, env, scope, fun->getAllocKind());

#ifdef DEBUG
  // The cloned function should itself be cloneable.
  RootedFunction cloneRoot(cx, clone);
  MOZ_ASSERT_IF(cloneRoot, IsFunctionCloneable(cloneRoot));
#endif

  return clone;
}

JS_PUBLIC_API JSObject* JS::CloneFunctionObject(JSContext* cx,
                                                HandleObject funobj) {
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  RootedScope emptyGlobalScope(cx, &cx->global()->emptyGlobalScope());
  return CloneFunctionObject(cx, funobj, globalLexical, emptyGlobalScope);
}

extern JS_PUBLIC_API JSObject* JS::CloneFunctionObject(
    JSContext* cx, HandleObject funobj, AutoObjectVector& envChain) {
  RootedObject env(cx);
  RootedScope scope(cx);
  if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &scope))
    return nullptr;
  return CloneFunctionObject(cx, funobj, env, scope);
}

JS_PUBLIC_API JSObject* JS_GetFunctionObject(JSFunction* fun) { return fun; }

JS_PUBLIC_API JSString* JS_GetFunctionId(JSFunction* fun) {
  return fun->explicitName();
}

JS_PUBLIC_API JSString* JS_GetFunctionDisplayId(JSFunction* fun) {
  return fun->displayAtom();
}

JS_PUBLIC_API uint16_t JS_GetFunctionArity(JSFunction* fun) {
  return fun->nargs();
}

JS_PUBLIC_API bool JS_ObjectIsFunction(JSContext* cx, JSObject* obj) {
  return obj->is<JSFunction>();
}

JS_PUBLIC_API bool JS_IsNativeFunction(JSObject* funobj, JSNative call) {
  if (!funobj->is<JSFunction>()) return false;
  JSFunction* fun = &funobj->as<JSFunction>();
  return fun->isNative() && fun->native() == call;
}

extern JS_PUBLIC_API bool JS_IsConstructor(JSFunction* fun) {
  return fun->isConstructor();
}

JS_PUBLIC_API bool JS_DefineFunctions(JSContext* cx, HandleObject obj,
                                      const JSFunctionSpec* fs) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  return DefineFunctions(cx, obj, fs, NotIntrinsic);
}

JS_PUBLIC_API JSFunction* JS_DefineFunction(JSContext* cx, HandleObject obj,
                                            const char* name, JSNative call,
                                            unsigned nargs, unsigned attrs) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  JSAtom* atom = Atomize(cx, name, strlen(name));
  if (!atom) return nullptr;
  Rooted<jsid> id(cx, AtomToId(atom));
  return DefineFunction(cx, obj, id, call, nargs, attrs);
}

JS_PUBLIC_API JSFunction* JS_DefineUCFunction(JSContext* cx, HandleObject obj,
                                              const char16_t* name,
                                              size_t namelen, JSNative call,
                                              unsigned nargs, unsigned attrs) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
  if (!atom) return nullptr;
  Rooted<jsid> id(cx, AtomToId(atom));
  return DefineFunction(cx, obj, id, call, nargs, attrs);
}

extern JS_PUBLIC_API JSFunction* JS_DefineFunctionById(
    JSContext* cx, HandleObject obj, HandleId id, JSNative call, unsigned nargs,
    unsigned attrs) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj, id);
  return DefineFunction(cx, obj, id, call, nargs, attrs);
}

/* Use the fastest available getc. */
#if defined(HAVE_GETC_UNLOCKED)
#define fast_getc getc_unlocked
#elif defined(HAVE__GETC_NOLOCK)
#define fast_getc _getc_nolock
#else
#define fast_getc getc
#endif

typedef Vector<char, 8, TempAllocPolicy> FileContents;

static bool ReadCompleteFile(JSContext* cx, FILE* fp, FileContents& buffer) {
  /* Get the complete length of the file, if possible. */
  struct stat st;
  int ok = fstat(fileno(fp), &st);
  if (ok != 0) return false;
  if (st.st_size > 0) {
    if (!buffer.reserve(st.st_size)) return false;
  }

  // Read in the whole file. Note that we can't assume the data's length
  // is actually st.st_size, because 1) some files lie about their size
  // (/dev/zero and /dev/random), and 2) reading files in text mode on
  // Windows collapses "\r\n" pairs to single \n characters.
  for (;;) {
    int c = fast_getc(fp);
    if (c == EOF) break;
    if (!buffer.append(c)) return false;
  }

  return true;
}

namespace {

class AutoFile {
  FILE* fp_;

 public:
  AutoFile() : fp_(nullptr) {}
  ~AutoFile() {
    if (fp_ && fp_ != stdin) fclose(fp_);
  }
  FILE* fp() const { return fp_; }
  bool open(JSContext* cx, const char* filename);
  bool readAll(JSContext* cx, FileContents& buffer) {
    MOZ_ASSERT(fp_);
    return ReadCompleteFile(cx, fp_, buffer);
  }
};

} /* anonymous namespace */

/*
 * Open a source file for reading. Supports "-" and nullptr to mean stdin. The
 * return value must be fclosed unless it is stdin.
 */
bool AutoFile::open(JSContext* cx, const char* filename) {
  if (!filename || strcmp(filename, "-") == 0) {
    fp_ = stdin;
  } else {
    fp_ = fopen(filename, "r");
    if (!fp_) {
      /*
       * Use Latin1 variant here because the encoding of filename is
       * platform dependent.
       */
      JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr, JSMSG_CANT_OPEN,
                                 filename, "No such file or directory");
      return false;
    }
  }
  return true;
}

void JS::TransitiveCompileOptions::copyPODTransitiveOptions(
    const TransitiveCompileOptions& rhs) {
  mutedErrors_ = rhs.mutedErrors_;
  utf8 = rhs.utf8;
  selfHostingMode = rhs.selfHostingMode;
  canLazilyParse = rhs.canLazilyParse;
  strictOption = rhs.strictOption;
  extraWarningsOption = rhs.extraWarningsOption;
  expressionClosuresOption = rhs.expressionClosuresOption;
  werrorOption = rhs.werrorOption;
  asmJSOption = rhs.asmJSOption;
  throwOnAsmJSValidationFailureOption = rhs.throwOnAsmJSValidationFailureOption;
  forceAsync = rhs.forceAsync;
  sourceIsLazy = rhs.sourceIsLazy;
  introductionType = rhs.introductionType;
  introductionLineno = rhs.introductionLineno;
  introductionOffset = rhs.introductionOffset;
  hasIntroductionInfo = rhs.hasIntroductionInfo;
  isProbablySystemOrAddonCode = rhs.isProbablySystemOrAddonCode;
  hideScriptFromDebugger = rhs.hideScriptFromDebugger;
};

void JS::ReadOnlyCompileOptions::copyPODOptions(
    const ReadOnlyCompileOptions& rhs) {
  copyPODTransitiveOptions(rhs);
  lineno = rhs.lineno;
  column = rhs.column;
  scriptSourceOffset = rhs.scriptSourceOffset;
  isRunOnce = rhs.isRunOnce;
  noScriptRval = rhs.noScriptRval;
  nonSyntacticScope = rhs.nonSyntacticScope;
}

JS::OwningCompileOptions::OwningCompileOptions(JSContext* cx)
    : ReadOnlyCompileOptions(),
      elementRoot(cx),
      elementAttributeNameRoot(cx),
      introductionScriptRoot(cx) {}

JS::OwningCompileOptions::~OwningCompileOptions() {
  // OwningCompileOptions always owns these, so these casts are okay.
  js_free(const_cast<char*>(filename_));
  js_free(const_cast<char16_t*>(sourceMapURL_));
  js_free(const_cast<char*>(introducerFilename_));
}

bool JS::OwningCompileOptions::copy(JSContext* cx,
                                    const ReadOnlyCompileOptions& rhs) {
  copyPODOptions(rhs);

  setElement(rhs.element());
  setElementAttributeName(rhs.elementAttributeName());
  setIntroductionScript(rhs.introductionScript());

  return setFileAndLine(cx, rhs.filename(), rhs.lineno) &&
         setSourceMapURL(cx, rhs.sourceMapURL()) &&
         setIntroducerFilename(cx, rhs.introducerFilename());
}

bool JS::OwningCompileOptions::setFile(JSContext* cx, const char* f) {
  char* copy = nullptr;
  if (f) {
    copy = JS_strdup(cx, f);
    if (!copy) return false;
  }

  // OwningCompileOptions always owns filename_, so this cast is okay.
  js_free(const_cast<char*>(filename_));

  filename_ = copy;
  return true;
}

bool JS::OwningCompileOptions::setFileAndLine(JSContext* cx, const char* f,
                                              unsigned l) {
  if (!setFile(cx, f)) return false;

  lineno = l;
  return true;
}

bool JS::OwningCompileOptions::setSourceMapURL(JSContext* cx,
                                               const char16_t* s) {
  UniqueTwoByteChars copy;
  if (s) {
    copy = DuplicateString(cx, s);
    if (!copy) return false;
  }

  // OwningCompileOptions always owns sourceMapURL_, so this cast is okay.
  js_free(const_cast<char16_t*>(sourceMapURL_));

  sourceMapURL_ = copy.release();
  return true;
}

bool JS::OwningCompileOptions::setIntroducerFilename(JSContext* cx,
                                                     const char* s) {
  char* copy = nullptr;
  if (s) {
    copy = JS_strdup(cx, s);
    if (!copy) return false;
  }

  // OwningCompileOptions always owns introducerFilename_, so this cast is okay.
  js_free(const_cast<char*>(introducerFilename_));

  introducerFilename_ = copy;
  return true;
}

JS::CompileOptions::CompileOptions(JSContext* cx)
    : ReadOnlyCompileOptions(),
      elementRoot(cx),
      elementAttributeNameRoot(cx),
      introductionScriptRoot(cx) {
  strictOption = cx->options().strictMode();
  extraWarningsOption = cx->compartment()->behaviors().extraWarnings(cx);
  expressionClosuresOption = cx->options().expressionClosures();
  isProbablySystemOrAddonCode =
      cx->compartment()->isProbablySystemOrAddonCode();
  werrorOption = cx->options().werror();
  if (!cx->options().asmJS())
    asmJSOption = AsmJSOption::Disabled;
  else if (cx->compartment()->debuggerObservesAsmJS())
    asmJSOption = AsmJSOption::DisabledByDebugger;
  else
    asmJSOption = AsmJSOption::Enabled;
  throwOnAsmJSValidationFailureOption =
      cx->options().throwOnAsmJSValidationFailure();
}

static bool Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                    SourceBufferHolder& srcBuf, MutableHandleScript script) {
  ScopeKind scopeKind =
      options.nonSyntacticScope ? ScopeKind::NonSyntactic : ScopeKind::Global;

  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  script.set(frontend::CompileGlobalScript(cx, cx->tempLifoAlloc(), scopeKind,
                                           options, srcBuf));
  return !!script;
}

static bool Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                    const char16_t* chars, size_t length,
                    MutableHandleScript script) {
  SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
  return ::Compile(cx, options, srcBuf, script);
}

static bool Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                    const char* bytes, size_t length,
                    MutableHandleScript script) {
  UniqueTwoByteChars chars;
  if (options.utf8)
    chars.reset(
        UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length), &length)
            .get());
  else
    chars.reset(InflateString(cx, bytes, length));
  if (!chars) return false;

  return ::Compile(cx, options, chars.get(), length, script);
}

static bool Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                    FILE* fp, MutableHandleScript script) {
  FileContents buffer(cx);
  if (!ReadCompleteFile(cx, fp, buffer)) return false;

  return ::Compile(cx, options, buffer.begin(), buffer.length(), script);
}

static bool Compile(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
                    const char* filename, MutableHandleScript script) {
  AutoFile file;
  if (!file.open(cx, filename)) return false;
  CompileOptions options(cx, optionsArg);
  options.setFileAndLine(filename, 1);
  return ::Compile(cx, options, file.fp(), script);
}

bool JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                 SourceBufferHolder& srcBuf, JS::MutableHandleScript script) {
  return ::Compile(cx, options, srcBuf, script);
}

bool JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                 const char* bytes, size_t length,
                 JS::MutableHandleScript script) {
  return ::Compile(cx, options, bytes, length, script);
}

bool JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                 const char16_t* chars, size_t length,
                 JS::MutableHandleScript script) {
  return ::Compile(cx, options, chars, length, script);
}

bool JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                 FILE* file, JS::MutableHandleScript script) {
  return ::Compile(cx, options, file, script);
}

bool JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
                 const char* filename, JS::MutableHandleScript script) {
  return ::Compile(cx, options, filename, script);
}

bool JS::CompileForNonSyntacticScope(JSContext* cx,
                                     const ReadOnlyCompileOptions& optionsArg,
                                     SourceBufferHolder& srcBuf,
                                     JS::MutableHandleScript script) {
  CompileOptions options(cx, optionsArg);
  options.setNonSyntacticScope(true);
  return ::Compile(cx, options, srcBuf, script);
}

bool JS::CompileForNonSyntacticScope(JSContext* cx,
                                     const ReadOnlyCompileOptions& optionsArg,
                                     const char* bytes, size_t length,
                                     JS::MutableHandleScript script) {
  CompileOptions options(cx, optionsArg);
  options.setNonSyntacticScope(true);
  return ::Compile(cx, options, bytes, length, script);
}

bool JS::CompileForNonSyntacticScope(JSContext* cx,
                                     const ReadOnlyCompileOptions& optionsArg,
                                     const char16_t* chars, size_t length,
                                     JS::MutableHandleScript script) {
  CompileOptions options(cx, optionsArg);
  options.setNonSyntacticScope(true);
  return ::Compile(cx, options, chars, length, script);
}

bool JS::CompileForNonSyntacticScope(JSContext* cx,
                                     const ReadOnlyCompileOptions& optionsArg,
                                     FILE* file,
                                     JS::MutableHandleScript script) {
  CompileOptions options(cx, optionsArg);
  options.setNonSyntacticScope(true);
  return ::Compile(cx, options, file, script);
}

bool JS::CompileForNonSyntacticScope(JSContext* cx,
                                     const ReadOnlyCompileOptions& optionsArg,
                                     const char* filename,
                                     JS::MutableHandleScript script) {
  CompileOptions options(cx, optionsArg);
  options.setNonSyntacticScope(true);
  return ::Compile(cx, options, filename, script);
}

enum class OffThread {
  Compile,
  Decode,
};

static bool CanDoOffThread(JSContext* cx, const ReadOnlyCompileOptions& options,
                           size_t length, OffThread what) {
  static const size_t TINY_LENGTH = 5 * 1000;
  static const size_t HUGE_SRC_LENGTH = 100 * 1000;
  static const size_t HUGE_BC_LENGTH = 367 * 1000;

  // These are heuristics which the caller may choose to ignore (e.g., for
  // testing purposes).
  if (!options.forceAsync) {
    // Compiling off the active thread inolves creating a new Zone and other
    // significant overheads.  Don't bother if the script is tiny.
    if (length < TINY_LENGTH) return false;

    // If the parsing task would have to wait for GC to complete, it'll probably
    // be faster to just start it synchronously on the active thread unless the
    // script is huge.
    if (OffThreadParsingMustWaitForGC(cx->runtime())) {
      if (what == OffThread::Compile && length < HUGE_SRC_LENGTH) return false;
      if (what == OffThread::Decode && length < HUGE_BC_LENGTH) return false;
    }
  }

  return cx->runtime()->canUseParallelParsing() && CanUseExtraThreads();
}

JS_PUBLIC_API bool JS::CanCompileOffThread(
    JSContext* cx, const ReadOnlyCompileOptions& options, size_t length) {
  return CanDoOffThread(cx, options, length, OffThread::Compile);
}

JS_PUBLIC_API bool JS::CanDecodeOffThread(JSContext* cx,
                                          const ReadOnlyCompileOptions& options,
                                          size_t length) {
  return CanDoOffThread(cx, options, length, OffThread::Decode);
}

JS_PUBLIC_API bool JS::CompileOffThread(JSContext* cx,
                                        const ReadOnlyCompileOptions& options,
                                        const char16_t* chars, size_t length,
                                        OffThreadCompileCallback callback,
                                        void* callbackData) {
  MOZ_ASSERT(CanCompileOffThread(cx, options, length));
  return StartOffThreadParseScript(cx, options, chars, length, callback,
                                   callbackData);
}

JS_PUBLIC_API JSScript* JS::FinishOffThreadScript(JSContext* cx, void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  return HelperThreadState().finishScriptParseTask(cx, token);
}

JS_PUBLIC_API void JS::CancelOffThreadScript(JSContext* cx, void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  HelperThreadState().cancelParseTask(cx->runtime(), ParseTaskKind::Script,
                                      token);
}

JS_PUBLIC_API bool JS::CompileOffThreadModule(
    JSContext* cx, const ReadOnlyCompileOptions& options, const char16_t* chars,
    size_t length, OffThreadCompileCallback callback, void* callbackData) {
  MOZ_ASSERT(CanCompileOffThread(cx, options, length));
  return StartOffThreadParseModule(cx, options, chars, length, callback,
                                   callbackData);
}

JS_PUBLIC_API JSObject* JS::FinishOffThreadModule(JSContext* cx, void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  return HelperThreadState().finishModuleParseTask(cx, token);
}

JS_PUBLIC_API void JS::CancelOffThreadModule(JSContext* cx, void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  HelperThreadState().cancelParseTask(cx->runtime(), ParseTaskKind::Module,
                                      token);
}

JS_PUBLIC_API bool JS::DecodeOffThreadScript(
    JSContext* cx, const ReadOnlyCompileOptions& options,
    mozilla::Vector<uint8_t>& buffer /* TranscodeBuffer& */, size_t cursor,
    OffThreadCompileCallback callback, void* callbackData) {
  JS::TranscodeRange range(buffer.begin() + cursor, buffer.length() - cursor);
  MOZ_ASSERT(CanDecodeOffThread(cx, options, range.length()));
  return StartOffThreadDecodeScript(cx, options, range, callback, callbackData);
}

JS_PUBLIC_API bool JS::DecodeOffThreadScript(
    JSContext* cx, const ReadOnlyCompileOptions& options,
    const mozilla::Range<uint8_t>& range /* TranscodeRange& */,
    OffThreadCompileCallback callback, void* callbackData) {
  MOZ_ASSERT(CanDecodeOffThread(cx, options, range.length()));
  return StartOffThreadDecodeScript(cx, options, range, callback, callbackData);
}

JS_PUBLIC_API bool JS::DecodeMultiOffThreadScripts(
    JSContext* cx, const ReadOnlyCompileOptions& options,
    TranscodeSources& sources, OffThreadCompileCallback callback,
    void* callbackData) {
#ifdef DEBUG
  size_t length = 0;
  for (auto& source : sources) {
    length += source.range.length();
  }
  MOZ_ASSERT(CanCompileOffThread(cx, options, length));
#endif
  return StartOffThreadDecodeMultiScripts(cx, options, sources, callback,
                                          callbackData);
}

JS_PUBLIC_API JSScript* JS::FinishOffThreadScriptDecoder(JSContext* cx,
                                                         void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  return HelperThreadState().finishScriptDecodeTask(cx, token);
}

JS_PUBLIC_API void JS::CancelOffThreadScriptDecoder(JSContext* cx,
                                                    void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  HelperThreadState().cancelParseTask(cx->runtime(),
                                      ParseTaskKind::ScriptDecode, token);
}

JS_PUBLIC_API bool JS::FinishMultiOffThreadScriptsDecoder(
    JSContext* cx, void* token, MutableHandle<ScriptVector> scripts) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  return HelperThreadState().finishMultiScriptsDecodeTask(cx, token, scripts);
}

JS_PUBLIC_API void JS::CancelMultiOffThreadScriptsDecoder(JSContext* cx,
                                                          void* token) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
  HelperThreadState().cancelParseTask(cx->runtime(),
                                      ParseTaskKind::MultiScriptsDecode, token);
}

JS_PUBLIC_API bool JS_CompileScript(JSContext* cx, const char* ascii,
                                    size_t length,
                                    const JS::CompileOptions& options,
                                    MutableHandleScript script) {
  return ::Compile(cx, options, ascii, length, script);
}

JS_PUBLIC_API bool JS_CompileUCScript(JSContext* cx, const char16_t* chars,
                                      size_t length,
                                      const JS::CompileOptions& options,
                                      MutableHandleScript script) {
  return ::Compile(cx, options, chars, length, script);
}

JS_PUBLIC_API bool JS_BufferIsCompilableUnit(JSContext* cx, HandleObject obj,
                                             const char* utf8, size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);

  cx->clearPendingException();

  char16_t* chars =
      JS::UTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(utf8, length), &length)
          .get();
  if (!chars) return true;

  // Return true on any out-of-memory error or non-EOF-related syntax error, so
  // our caller doesn't try to collect more buffered source.
  bool result = true;

  CompileOptions options(cx);
  frontend::UsedNameTracker usedNames(cx);
  if (!usedNames.init()) return false;
  frontend::Parser<frontend::FullParseHandler, char16_t> parser(
      cx, cx->tempLifoAlloc(), options, chars, length,
      /* foldConstants = */ true, usedNames, nullptr, nullptr);
  JS::WarningReporter older = JS::SetWarningReporter(cx, nullptr);
  if (!parser.checkOptions() || !parser.parse()) {
    // We ran into an error. If it was because we ran out of source, we
    // return false so our caller knows to try to collect more buffered
    // source.
    if (parser.isUnexpectedEOF()) result = false;

    cx->clearPendingException();
  }
  JS::SetWarningReporter(cx, older);

  js_free(chars);
  return result;
}

JS_PUBLIC_API JSObject* JS_GetGlobalFromScript(JSScript* script) {
  MOZ_ASSERT(!script->isCachedEval());
  return &script->global();
}

JS_PUBLIC_API const char* JS_GetScriptFilename(JSScript* script) {
  // This is called from ThreadStackHelper which can be called from another
  // thread or inside a signal hander, so we need to be careful in case a
  // copmacting GC is currently moving things around.
  return script->maybeForwardedFilename();
}

JS_PUBLIC_API unsigned JS_GetScriptBaseLineNumber(JSContext* cx,
                                                  JSScript* script) {
  return script->lineno();
}

JS_PUBLIC_API JSScript* JS_GetFunctionScript(JSContext* cx,
                                             HandleFunction fun) {
  if (fun->isNative()) return nullptr;
  if (fun->isInterpretedLazy()) {
    AutoCompartment funCompartment(cx, fun);
    JSScript* script = JSFunction::getOrCreateScript(cx, fun);
    if (!script) MOZ_CRASH();
    return script;
  }
  return fun->nonLazyScript();
}

/*
 * enclosingScope is a scope, if any (e.g. a WithScope).  If the scope is the
 * global scope, this must be null.
 *
 * enclosingEnv is an environment to use, if it's not the global.
 */
static bool CompileFunction(
    JSContext* cx, const ReadOnlyCompileOptions& optionsArg, HandleAtom name,
    bool isInvalidName, SourceBufferHolder& srcBuf, uint32_t parameterListEnd,
    HandleObject enclosingEnv, HandleScope enclosingScope,
    MutableHandleFunction fun) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, enclosingEnv);
  RootedAtom funAtom(cx);

  fun.set(NewScriptedFunction(cx, 0, JSFunction::INTERPRETED_NORMAL,
                              isInvalidName ? nullptr : name,
                              /* proto = */ nullptr, gc::AllocKind::FUNCTION,
                              TenuredObject, enclosingEnv));
  if (!fun) return false;

  // Make sure the static scope chain matches up when we have a
  // non-syntactic scope.
  MOZ_ASSERT_IF(!IsGlobalLexicalEnvironment(enclosingEnv),
                enclosingScope->hasOnChain(ScopeKind::NonSyntactic));

  if (!frontend::CompileStandaloneFunction(cx, fun, optionsArg, srcBuf,
                                           Some(parameterListEnd),
                                           enclosingScope)) {
    return false;
  }

  // When function name is not valid identifier, generated function source
  // in srcBuf doesn't have function name.  Set it here.
  if (isInvalidName) fun->setAtom(name);

  return true;
}

static MOZ_MUST_USE bool BuildFunctionString(const char* name, size_t nameLen,
                                             unsigned nargs,
                                             const char* const* argnames,
                                             const SourceBufferHolder& srcBuf,
                                             StringBuffer* out,
                                             uint32_t* parameterListEnd) {
  MOZ_ASSERT(out);
  MOZ_ASSERT(parameterListEnd);

  if (!out->ensureTwoByteChars()) return false;
  if (!out->append("function ")) return false;
  if (name) {
    if (!out->append(name, nameLen)) return false;
  }
  if (!out->append("(")) return false;
  for (unsigned i = 0; i < nargs; i++) {
    if (i != 0) {
      if (!out->append(", ")) return false;
    }
    if (!out->append(argnames[i], strlen(argnames[i]))) return false;
  }

  // Remember the position of ")".
  *parameterListEnd = out->length();
  MOZ_ASSERT(FunctionConstructorMedialSigils[0] == ')');

  if (!out->append(FunctionConstructorMedialSigils)) return false;
  if (!out->append(srcBuf.get(), srcBuf.length())) return false;
  if (!out->append(FunctionConstructorFinalBrace)) return false;

  return true;
}

JS_PUBLIC_API bool JS::CompileFunction(JSContext* cx,
                                       AutoObjectVector& envChain,
                                       const ReadOnlyCompileOptions& options,
                                       const char* name, unsigned nargs,
                                       const char* const* argnames,
                                       SourceBufferHolder& srcBuf,
                                       MutableHandleFunction fun) {
  RootedObject env(cx);
  RootedScope scope(cx);
  if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &scope))
    return false;

  size_t nameLen = 0;
  bool isInvalidName = false;
  RootedAtom nameAtom(cx);
  if (name) {
    nameLen = strlen(name);
    nameAtom = Atomize(cx, name, nameLen);
    if (!nameAtom) return false;

    // If name is not valid identifier
    if (!js::frontend::IsIdentifier(name, nameLen)) isInvalidName = true;
  }

  uint32_t parameterListEnd;
  StringBuffer funStr(cx);
  if (!BuildFunctionString(isInvalidName ? nullptr : name, nameLen, nargs,
                           argnames, srcBuf, &funStr, &parameterListEnd)) {
    return false;
  }

  size_t newLen = funStr.length();
  SourceBufferHolder newSrcBuf(funStr.stealChars(), newLen,
                               SourceBufferHolder::GiveOwnership);

  return CompileFunction(cx, options, nameAtom, isInvalidName, newSrcBuf,
                         parameterListEnd, env, scope, fun);
}

JS_PUBLIC_API bool JS::CompileFunction(JSContext* cx,
                                       AutoObjectVector& envChain,
                                       const ReadOnlyCompileOptions& options,
                                       const char* name, unsigned nargs,
                                       const char* const* argnames,
                                       const char16_t* chars, size_t length,
                                       MutableHandleFunction fun) {
  SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
  return CompileFunction(cx, envChain, options, name, nargs, argnames, srcBuf,
                         fun);
}

JS_PUBLIC_API bool JS::CompileFunction(JSContext* cx,
                                       AutoObjectVector& envChain,
                                       const ReadOnlyCompileOptions& options,
                                       const char* name, unsigned nargs,
                                       const char* const* argnames,
                                       const char* bytes, size_t length,
                                       MutableHandleFunction fun) {
  UniqueTwoByteChars chars;
  if (options.utf8)
    chars.reset(
        UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length), &length)
            .get());
  else
    chars.reset(InflateString(cx, bytes, length));
  if (!chars) return false;

  return CompileFunction(cx, envChain, options, name, nargs, argnames,
                         chars.get(), length, fun);
}

JS_PUBLIC_API bool JS::InitScriptSourceElement(JSContext* cx,
                                               HandleScript script,
                                               HandleObject element,
                                               HandleString elementAttrName) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));

  RootedScriptSource sso(cx, &script->sourceObject()->as<ScriptSourceObject>());
  return ScriptSourceObject::initElementProperties(cx, sso, element,
                                                   elementAttrName);
}

JS_PUBLIC_API void JS::ExposeScriptToDebugger(JSContext* cx,
                                              HandleScript script) {
  MOZ_ASSERT(cx);
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));

  MOZ_ASSERT(script->hideScriptFromDebugger());
  script->clearHideScriptFromDebugger();
  Debugger::onNewScript(cx, script);
}

JS_PUBLIC_API JSString* JS_DecompileScript(JSContext* cx, HandleScript script) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  script->ensureNonLazyCanonicalFunction();
  RootedFunction fun(cx, script->functionNonDelazifying());
  if (fun) return JS_DecompileFunction(cx, fun);
  bool haveSource = script->scriptSource()->hasSourceData();
  if (!haveSource &&
      !JSScript::loadSource(cx, script->scriptSource(), &haveSource))
    return nullptr;
  return haveSource ? JSScript::sourceData(cx, script)
                    : NewStringCopyZ<CanGC>(cx, "[no source]");
}

JS_PUBLIC_API JSString* JS_DecompileFunction(JSContext* cx,
                                             HandleFunction fun) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, fun);
  return FunctionToString(cx, fun, /* isToSource = */ false);
}

MOZ_NEVER_INLINE static bool ExecuteScript(JSContext* cx, HandleObject scope,
                                           HandleScript script, Value* rval) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, scope, script);
  MOZ_ASSERT_IF(!IsGlobalLexicalEnvironment(scope),
                script->hasNonSyntacticScope());
  return Execute(cx, script, *scope, rval);
}

static bool ExecuteScript(JSContext* cx, AutoObjectVector& envChain,
                          HandleScript scriptArg, Value* rval) {
  RootedObject env(cx);
  RootedScope dummy(cx);
  if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &dummy))
    return false;

  RootedScript script(cx, scriptArg);
  if (!script->hasNonSyntacticScope() && !IsGlobalLexicalEnvironment(env)) {
    script = CloneGlobalScript(cx, ScopeKind::NonSyntactic, script);
    if (!script) return false;
    js::Debugger::onNewScript(cx, script);
  }

  return ExecuteScript(cx, env, script, rval);
}

MOZ_NEVER_INLINE JS_PUBLIC_API bool JS_ExecuteScript(JSContext* cx,
                                                     HandleScript scriptArg,
                                                     MutableHandleValue rval) {
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  return ExecuteScript(cx, globalLexical, scriptArg, rval.address());
}

MOZ_NEVER_INLINE JS_PUBLIC_API bool JS_ExecuteScript(JSContext* cx,
                                                     HandleScript scriptArg) {
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  return ExecuteScript(cx, globalLexical, scriptArg, nullptr);
}

MOZ_NEVER_INLINE JS_PUBLIC_API bool JS_ExecuteScript(JSContext* cx,
                                                     AutoObjectVector& envChain,
                                                     HandleScript scriptArg,
                                                     MutableHandleValue rval) {
  return ExecuteScript(cx, envChain, scriptArg, rval.address());
}

MOZ_NEVER_INLINE JS_PUBLIC_API bool JS_ExecuteScript(JSContext* cx,
                                                     AutoObjectVector& envChain,
                                                     HandleScript scriptArg) {
  return ExecuteScript(cx, envChain, scriptArg, nullptr);
}

JS_PUBLIC_API bool JS::CloneAndExecuteScript(JSContext* cx,
                                             HandleScript scriptArg,
                                             JS::MutableHandleValue rval) {
  CHECK_REQUEST(cx);
  RootedScript script(cx, scriptArg);
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  if (script->compartment() != cx->compartment()) {
    script = CloneGlobalScript(cx, ScopeKind::Global, script);
    if (!script) return false;

    js::Debugger::onNewScript(cx, script);
  }
  return ExecuteScript(cx, globalLexical, script, rval.address());
}

JS_PUBLIC_API bool JS::CloneAndExecuteScript(JSContext* cx,
                                             JS::AutoObjectVector& envChain,
                                             HandleScript scriptArg,
                                             JS::MutableHandleValue rval) {
  CHECK_REQUEST(cx);
  RootedScript script(cx, scriptArg);
  if (script->compartment() != cx->compartment()) {
    script = CloneGlobalScript(cx, ScopeKind::NonSyntactic, script);
    if (!script) return false;

    js::Debugger::onNewScript(cx, script);
  }
  return ExecuteScript(cx, envChain, script, rval.address());
}

static bool Evaluate(JSContext* cx, ScopeKind scopeKind, HandleObject env,
                     const ReadOnlyCompileOptions& optionsArg,
                     SourceBufferHolder& srcBuf, MutableHandleValue rval) {
  CompileOptions options(cx, optionsArg);
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, env);
  MOZ_ASSERT_IF(!IsGlobalLexicalEnvironment(env),
                scopeKind == ScopeKind::NonSyntactic);

  options.setIsRunOnce(true);
  RootedScript script(
      cx, frontend::CompileGlobalScript(cx, cx->tempLifoAlloc(), scopeKind,
                                        options, srcBuf));
  if (!script) return false;

  bool result = Execute(cx, script, *env,
                        options.noScriptRval ? nullptr : rval.address());

  return result;
}

static bool Evaluate(JSContext* cx, AutoObjectVector& envChain,
                     const ReadOnlyCompileOptions& optionsArg,
                     SourceBufferHolder& srcBuf, MutableHandleValue rval) {
  RootedObject env(cx);
  RootedScope scope(cx);
  if (!CreateNonSyntacticEnvironmentChain(cx, envChain, &env, &scope))
    return false;
  return ::Evaluate(cx, scope->kind(), env, optionsArg, srcBuf, rval);
}

static bool Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
                     const char16_t* chars, size_t length,
                     MutableHandleValue rval) {
  SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  return ::Evaluate(cx, ScopeKind::Global, globalLexical, optionsArg, srcBuf,
                    rval);
}

extern JS_PUBLIC_API bool JS::Evaluate(JSContext* cx,
                                       const ReadOnlyCompileOptions& options,
                                       const char* bytes, size_t length,
                                       MutableHandleValue rval) {
  char16_t* chars;
  if (options.utf8)
    chars =
        UTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(bytes, length), &length)
            .get();
  else
    chars = InflateString(cx, bytes, length);
  if (!chars) return false;

  SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::GiveOwnership);
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  bool ok =
      ::Evaluate(cx, ScopeKind::Global, globalLexical, options, srcBuf, rval);
  return ok;
}

static bool Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
                     const char* filename, MutableHandleValue rval) {
  FileContents buffer(cx);
  {
    AutoFile file;
    if (!file.open(cx, filename) || !file.readAll(cx, buffer)) return false;
  }

  CompileOptions options(cx, optionsArg);
  options.setFileAndLine(filename, 1);
  return Evaluate(cx, options, buffer.begin(), buffer.length(), rval);
}

JS_PUBLIC_API bool JS::Evaluate(JSContext* cx,
                                const ReadOnlyCompileOptions& optionsArg,
                                SourceBufferHolder& srcBuf,
                                MutableHandleValue rval) {
  RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
  return ::Evaluate(cx, ScopeKind::Global, globalLexical, optionsArg, srcBuf,
                    rval);
}

JS_PUBLIC_API bool JS::Evaluate(JSContext* cx, AutoObjectVector& envChain,
                                const ReadOnlyCompileOptions& optionsArg,
                                SourceBufferHolder& srcBuf,
                                MutableHandleValue rval) {
  return ::Evaluate(cx, envChain, optionsArg, srcBuf, rval);
}

JS_PUBLIC_API bool JS::Evaluate(JSContext* cx,
                                const ReadOnlyCompileOptions& optionsArg,
                                const char16_t* chars, size_t length,
                                MutableHandleValue rval) {
  return ::Evaluate(cx, optionsArg, chars, length, rval);
}

JS_PUBLIC_API bool JS::Evaluate(JSContext* cx, AutoObjectVector& envChain,
                                const ReadOnlyCompileOptions& optionsArg,
                                const char16_t* chars, size_t length,
                                MutableHandleValue rval) {
  SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
  return ::Evaluate(cx, envChain, optionsArg, srcBuf, rval);
}

JS_PUBLIC_API bool JS::Evaluate(JSContext* cx,
                                const ReadOnlyCompileOptions& optionsArg,
                                const char* filename, MutableHandleValue rval) {
  return ::Evaluate(cx, optionsArg, filename, rval);
}

JS_PUBLIC_API JSFunction* JS::GetModuleResolveHook(JSContext* cx) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return cx->global()->moduleResolveHook();
}

JS_PUBLIC_API void JS::SetModuleResolveHook(JSContext* cx,
                                            HandleFunction func) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, func);
  cx->global()->setModuleResolveHook(func);
}

JS_PUBLIC_API bool JS::CompileModule(JSContext* cx,
                                     const ReadOnlyCompileOptions& options,
                                     SourceBufferHolder& srcBuf,
                                     JS::MutableHandleObject module) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  module.set(frontend::CompileModule(cx, options, srcBuf));
  return !!module;
}

JS_PUBLIC_API void JS::SetModuleHostDefinedField(JSObject* module,
                                                 const JS::Value& value) {
  module->as<ModuleObject>().setHostDefinedField(value);
}

JS_PUBLIC_API JS::Value JS::GetModuleHostDefinedField(JSObject* module) {
  return module->as<ModuleObject>().hostDefinedField();
}

JS_PUBLIC_API bool JS::ModuleInstantiate(JSContext* cx,
                                         JS::HandleObject moduleArg) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  releaseAssertSameCompartment(cx, moduleArg);
  return ModuleObject::Instantiate(cx, moduleArg.as<ModuleObject>());
}

JS_PUBLIC_API bool JS::ModuleEvaluate(JSContext* cx,
                                      JS::HandleObject moduleArg) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  releaseAssertSameCompartment(cx, moduleArg);
  return ModuleObject::Evaluate(cx, moduleArg.as<ModuleObject>());
}

JS_PUBLIC_API JSObject* JS::GetRequestedModules(JSContext* cx,
                                                JS::HandleObject moduleArg) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, moduleArg);
  return &moduleArg->as<ModuleObject>().requestedModules();
}

JS_PUBLIC_API JSString* JS::GetRequestedModuleSpecifier(JSContext* cx,
                                                        JS::HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  JSObject* obj = &value.toObject();
  return obj->as<RequestedModuleObject>().moduleSpecifier();
}

JS_PUBLIC_API void JS::GetRequestedModuleSourcePos(JSContext* cx,
                                                   JS::HandleValue value,
                                                   uint32_t* lineNumber,
                                                   uint32_t* columnNumber) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
  MOZ_ASSERT(lineNumber);
  MOZ_ASSERT(columnNumber);
  auto& requested = value.toObject().as<RequestedModuleObject>();
  *lineNumber = requested.lineNumber();
  *columnNumber = requested.columnNumber();
}

JS_PUBLIC_API JSScript* JS::GetModuleScript(JS::HandleObject moduleRecord) {
  AssertHeapIsIdle();
  return moduleRecord->as<ModuleObject>().script();
}

JS_PUBLIC_API JSObject* JS_New(JSContext* cx, HandleObject ctor,
                               const JS::HandleValueArray& inputArgs) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, ctor, inputArgs);

  RootedValue ctorVal(cx, ObjectValue(*ctor));
  if (!IsConstructor(ctorVal)) {
    ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, ctorVal,
                     nullptr);
    return nullptr;
  }

  ConstructArgs args(cx);
  if (!FillArgumentsFromArraylike(cx, args, inputArgs)) return nullptr;

  RootedObject obj(cx);
  if (!js::Construct(cx, ctorVal, args, ctorVal, &obj)) return nullptr;

  return obj;
}

JS_PUBLIC_API bool JS_CheckForInterrupt(JSContext* cx) {
  return js::CheckForInterrupt(cx);
}

JS_PUBLIC_API bool JS_AddInterruptCallback(JSContext* cx,
                                           JSInterruptCallback callback) {
  return cx->interruptCallbacks().append(callback);
}

JS_PUBLIC_API bool JS_DisableInterruptCallback(JSContext* cx) {
  bool result = cx->interruptCallbackDisabled;
  cx->interruptCallbackDisabled = true;
  return result;
}

JS_PUBLIC_API void JS_ResetInterruptCallback(JSContext* cx, bool enable) {
  cx->interruptCallbackDisabled = enable;
}

/************************************************************************/

/*
 * Promises.
 */
JS_PUBLIC_API void JS::SetGetIncumbentGlobalCallback(
    JSContext* cx, JSGetIncumbentGlobalCallback callback) {
  cx->getIncumbentGlobalCallback = callback;
}

JS_PUBLIC_API void JS::SetEnqueuePromiseJobCallback(
    JSContext* cx, JSEnqueuePromiseJobCallback callback,
    void* data /* = nullptr */) {
  cx->enqueuePromiseJobCallback = callback;
  cx->enqueuePromiseJobCallbackData = data;
}

extern JS_PUBLIC_API void JS::SetPromiseRejectionTrackerCallback(
    JSContext* cx, JSPromiseRejectionTrackerCallback callback,
    void* data /* = nullptr */) {
  cx->promiseRejectionTrackerCallback = callback;
  cx->promiseRejectionTrackerCallbackData = data;
}

JS_PUBLIC_API JSObject* JS::NewPromiseObject(
    JSContext* cx, HandleObject executor, HandleObject proto /* = nullptr */) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, executor, proto);

  if (!executor) return PromiseObject::createSkippingExecutor(cx);

  MOZ_ASSERT(IsCallable(executor));
  return PromiseObject::create(cx, executor, proto);
}

JS_PUBLIC_API bool JS::IsPromiseObject(JS::HandleObject obj) {
  return obj->is<PromiseObject>();
}

JS_PUBLIC_API JSObject* JS::GetPromiseConstructor(JSContext* cx) {
  CHECK_REQUEST(cx);
  Rooted<GlobalObject*> global(cx, cx->global());
  return GlobalObject::getOrCreatePromiseConstructor(cx, global);
}

JS_PUBLIC_API JSObject* JS::GetPromisePrototype(JSContext* cx) {
  CHECK_REQUEST(cx);
  Rooted<GlobalObject*> global(cx, cx->global());
  return GlobalObject::getOrCreatePromisePrototype(cx, global);
}

JS_PUBLIC_API JS::PromiseState JS::GetPromiseState(
    JS::HandleObject promiseObj_) {
  JSObject* promiseObj = CheckedUnwrap(promiseObj_);
  if (!promiseObj || !promiseObj->is<PromiseObject>())
    return JS::PromiseState::Pending;

  return promiseObj->as<PromiseObject>().state();
}

JS_PUBLIC_API uint64_t JS::GetPromiseID(JS::HandleObject promise) {
  return promise->as<PromiseObject>().getID();
}

JS_PUBLIC_API JS::Value JS::GetPromiseResult(JS::HandleObject promiseObj) {
  PromiseObject* promise = &promiseObj->as<PromiseObject>();
  MOZ_ASSERT(promise->state() != JS::PromiseState::Pending);
  return promise->state() == JS::PromiseState::Fulfilled ? promise->value()
                                                         : promise->reason();
}

JS_PUBLIC_API JSObject* JS::GetPromiseAllocationSite(JS::HandleObject promise) {
  return promise->as<PromiseObject>().allocationSite();
}

JS_PUBLIC_API JSObject* JS::GetPromiseResolutionSite(JS::HandleObject promise) {
  return promise->as<PromiseObject>().resolutionSite();
}

#ifdef DEBUG
JS_PUBLIC_API void JS::DumpPromiseAllocationSite(JSContext* cx,
                                                 JS::HandleObject promise) {
  RootedObject stack(cx, promise->as<PromiseObject>().allocationSite());
  UniqueChars stackStr(
      reinterpret_cast<char*>(BuildUTF8StackString(cx, stack).get()));
  if (stackStr.get()) fputs(stackStr.get(), stderr);
}

JS_PUBLIC_API void JS::DumpPromiseResolutionSite(JSContext* cx,
                                                 JS::HandleObject promise) {
  RootedObject stack(cx, promise->as<PromiseObject>().resolutionSite());
  UniqueChars stackStr(
      reinterpret_cast<char*>(BuildUTF8StackString(cx, stack).get()));
  if (stackStr.get()) fputs(stackStr.get(), stderr);
}
#endif

JS_PUBLIC_API JSObject* JS::CallOriginalPromiseResolve(
    JSContext* cx, JS::HandleValue resolutionValue) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, resolutionValue);

  RootedObject promise(cx,
                       PromiseObject::unforgeableResolve(cx, resolutionValue));
  MOZ_ASSERT_IF(promise, CheckedUnwrap(promise)->is<PromiseObject>());
  return promise;
}

JS_PUBLIC_API JSObject* JS::CallOriginalPromiseReject(
    JSContext* cx, JS::HandleValue rejectionValue) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, rejectionValue);

  RootedObject promise(cx,
                       PromiseObject::unforgeableReject(cx, rejectionValue));
  MOZ_ASSERT_IF(promise, CheckedUnwrap(promise)->is<PromiseObject>());
  return promise;
}

static bool ResolveOrRejectPromise(JSContext* cx, JS::HandleObject promiseObj,
                                   JS::HandleValue resultOrReason_,
                                   bool reject) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, promiseObj, resultOrReason_);

  mozilla::Maybe<AutoCompartment> ac;
  Rooted<PromiseObject*> promise(cx);
  RootedValue resultOrReason(cx, resultOrReason_);
  if (IsWrapper(promiseObj)) {
    JSObject* unwrappedPromiseObj = CheckedUnwrap(promiseObj);
    if (!unwrappedPromiseObj) {
      ReportAccessDenied(cx);
      return false;
    }
    promise = &unwrappedPromiseObj->as<PromiseObject>();
    ac.emplace(cx, promise);
    if (!cx->compartment()->wrap(cx, &resultOrReason)) return false;
  } else {
    promise = promiseObj.as<PromiseObject>();
  }

  return reject ? PromiseObject::reject(cx, promise, resultOrReason)
                : PromiseObject::resolve(cx, promise, resultOrReason);
}

JS_PUBLIC_API bool JS::ResolvePromise(JSContext* cx,
                                      JS::HandleObject promiseObj,
                                      JS::HandleValue resolutionValue) {
  return ResolveOrRejectPromise(cx, promiseObj, resolutionValue, false);
}

JS_PUBLIC_API bool JS::RejectPromise(JSContext* cx, JS::HandleObject promiseObj,
                                     JS::HandleValue rejectionValue) {
  return ResolveOrRejectPromise(cx, promiseObj, rejectionValue, true);
}

static bool CallOriginalPromiseThenImpl(JSContext* cx,
                                        JS::HandleObject promiseObj,
                                        JS::HandleObject onResolvedObj_,
                                        JS::HandleObject onRejectedObj_,
                                        JS::MutableHandleObject resultObj,
                                        bool createDependent) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, promiseObj, onResolvedObj_, onRejectedObj_);

  MOZ_ASSERT_IF(onResolvedObj_, IsCallable(onResolvedObj_));
  MOZ_ASSERT_IF(onRejectedObj_, IsCallable(onRejectedObj_));

  {
    mozilla::Maybe<AutoCompartment> ac;
    Rooted<PromiseObject*> promise(cx);
    RootedObject onResolvedObj(cx, onResolvedObj_);
    RootedObject onRejectedObj(cx, onRejectedObj_);
    if (IsWrapper(promiseObj)) {
      JSObject* unwrappedPromiseObj = CheckedUnwrap(promiseObj);
      if (!unwrappedPromiseObj) {
        ReportAccessDenied(cx);
        return false;
      }
      promise = &unwrappedPromiseObj->as<PromiseObject>();
      ac.emplace(cx, promise);
      if (!cx->compartment()->wrap(cx, &onResolvedObj) ||
          !cx->compartment()->wrap(cx, &onRejectedObj)) {
        return false;
      }
    } else {
      promise = promiseObj.as<PromiseObject>();
    }

    RootedValue onFulfilled(cx, ObjectOrNullValue(onResolvedObj));
    RootedValue onRejected(cx, ObjectOrNullValue(onRejectedObj));
    if (!OriginalPromiseThen(cx, promise, onFulfilled, onRejected, resultObj,
                             createDependent))
      return false;
  }

  if (resultObj) {
    if (!cx->compartment()->wrap(cx, resultObj)) return false;
  }
  return true;
}

JS_PUBLIC_API JSObject* JS::CallOriginalPromiseThen(
    JSContext* cx, JS::HandleObject promiseObj, JS::HandleObject onResolvedObj,
    JS::HandleObject onRejectedObj) {
  RootedObject resultPromise(cx);
  if (!CallOriginalPromiseThenImpl(cx, promiseObj, onResolvedObj, onRejectedObj,
                                   &resultPromise, true))
    return nullptr;
  return resultPromise;
}

JS_PUBLIC_API bool JS::AddPromiseReactions(JSContext* cx,
                                           JS::HandleObject promiseObj,
                                           JS::HandleObject onResolvedObj,
                                           JS::HandleObject onRejectedObj) {
  RootedObject resultPromise(cx);
  bool result = CallOriginalPromiseThenImpl(
      cx, promiseObj, onResolvedObj, onRejectedObj, &resultPromise, false);
  MOZ_ASSERT(!resultPromise);
  return result;
}

/**
 * Unforgeable version of Promise.all for internal use.
 *
 * Takes a dense array of Promise objects and returns a promise that's
 * resolved with an array of resolution values when all those promises ahve
 * been resolved, or rejected with the rejection value of the first rejected
 * promise.
 *
 * Asserts that the array is dense and all entries are Promise objects.
 */
JS_PUBLIC_API JSObject* JS::GetWaitForAllPromise(
    JSContext* cx, const JS::AutoObjectVector& promises) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return js::GetWaitForAllPromise(cx, promises);
}

JS_PUBLIC_API JSObject* JS::NewReadableDefaultStreamObject(
    JSContext* cx, JS::HandleObject underlyingSource /* = nullptr */,
    JS::HandleFunction size /* = nullptr */, double highWaterMark /* = 1 */,
    JS::HandleObject proto /* = nullptr */) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  RootedObject source(cx, underlyingSource);
  if (!source) {
    source = NewBuiltinClassInstance<PlainObject>(cx);
    if (!source) return nullptr;
  }
  RootedValue sourceVal(cx, ObjectValue(*source));
  RootedValue sizeVal(cx, size ? ObjectValue(*size) : UndefinedValue());
  RootedValue highWaterMarkVal(cx, NumberValue(highWaterMark));
  return ReadableStream::createDefaultStream(cx, sourceVal, sizeVal,
                                             highWaterMarkVal, proto);
}

JS_PUBLIC_API JSObject* JS::NewReadableByteStreamObject(
    JSContext* cx, JS::HandleObject underlyingSource /* = nullptr */,
    double highWaterMark /* = 1 */, JS::HandleObject proto /* = nullptr */) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  RootedObject source(cx, underlyingSource);
  if (!source) {
    source = NewBuiltinClassInstance<PlainObject>(cx);
    if (!source) return nullptr;
  }
  RootedValue sourceVal(cx, ObjectValue(*source));
  RootedValue highWaterMarkVal(cx, NumberValue(highWaterMark));
  return ReadableStream::createByteStream(cx, sourceVal, highWaterMarkVal,
                                          proto);
}

extern JS_PUBLIC_API void JS::SetReadableStreamCallbacks(
    JSContext* cx, JS::RequestReadableStreamDataCallback dataRequestCallback,
    JS::WriteIntoReadRequestBufferCallback writeIntoReadRequestCallback,
    JS::CancelReadableStreamCallback cancelCallback,
    JS::ReadableStreamClosedCallback closedCallback,
    JS::ReadableStreamErroredCallback erroredCallback,
    JS::ReadableStreamFinalizeCallback finalizeCallback) {
  MOZ_ASSERT(dataRequestCallback);
  MOZ_ASSERT(writeIntoReadRequestCallback);
  MOZ_ASSERT(cancelCallback);
  MOZ_ASSERT(closedCallback);
  MOZ_ASSERT(erroredCallback);
  MOZ_ASSERT(finalizeCallback);

  JSRuntime* rt = cx->runtime();

  MOZ_ASSERT(!rt->readableStreamDataRequestCallback);
  MOZ_ASSERT(!rt->readableStreamWriteIntoReadRequestCallback);
  MOZ_ASSERT(!rt->readableStreamCancelCallback);
  MOZ_ASSERT(!rt->readableStreamClosedCallback);
  MOZ_ASSERT(!rt->readableStreamErroredCallback);
  MOZ_ASSERT(!rt->readableStreamFinalizeCallback);

  rt->readableStreamDataRequestCallback = dataRequestCallback;
  rt->readableStreamWriteIntoReadRequestCallback = writeIntoReadRequestCallback;
  rt->readableStreamCancelCallback = cancelCallback;
  rt->readableStreamClosedCallback = closedCallback;
  rt->readableStreamErroredCallback = erroredCallback;
  rt->readableStreamFinalizeCallback = finalizeCallback;
}

JS_PUBLIC_API bool JS::HasReadableStreamCallbacks(JSContext* cx) {
  return cx->runtime()->readableStreamDataRequestCallback;
}

JS_PUBLIC_API JSObject* JS::NewReadableExternalSourceStreamObject(
    JSContext* cx, void* underlyingSource, uint8_t flags /* = 0 */,
    HandleObject proto /* = nullptr */) {
  MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

#ifdef DEBUG
  JSRuntime* rt = cx->runtime();
  MOZ_ASSERT(rt->readableStreamDataRequestCallback);
  MOZ_ASSERT(rt->readableStreamWriteIntoReadRequestCallback);
  MOZ_ASSERT(rt->readableStreamCancelCallback);
  MOZ_ASSERT(rt->readableStreamClosedCallback);
  MOZ_ASSERT(rt->readableStreamErroredCallback);
  MOZ_ASSERT(rt->readableStreamFinalizeCallback);
#endif  // DEBUG

  return ReadableStream::createExternalSourceStream(cx, underlyingSource, flags,
                                                    proto);
}

JS_PUBLIC_API uint8_t
JS::ReadableStreamGetEmbeddingFlags(const JSObject* stream) {
  return stream->as<ReadableStream>().embeddingFlags();
}

JS_PUBLIC_API bool JS::IsReadableStream(const JSObject* obj) {
  return obj->is<ReadableStream>();
}

JS_PUBLIC_API bool JS::IsReadableStreamReader(const JSObject* obj) {
  return obj->is<ReadableStreamDefaultReader>() ||
         obj->is<ReadableStreamBYOBReader>();
}

JS_PUBLIC_API bool JS::IsReadableStreamDefaultReader(const JSObject* obj) {
  return obj->is<ReadableStreamDefaultReader>();
}

JS_PUBLIC_API bool JS::IsReadableStreamBYOBReader(const JSObject* obj) {
  return obj->is<ReadableStreamBYOBReader>();
}

JS_PUBLIC_API bool JS::ReadableStreamIsReadable(const JSObject* stream) {
  return stream->as<ReadableStream>().readable();
}

JS_PUBLIC_API bool JS::ReadableStreamIsLocked(const JSObject* stream) {
  return stream->as<ReadableStream>().locked();
}

JS_PUBLIC_API bool JS::ReadableStreamIsDisturbed(const JSObject* stream) {
  return stream->as<ReadableStream>().disturbed();
}

JS_PUBLIC_API JSObject* JS::ReadableStreamCancel(JSContext* cx,
                                                 HandleObject streamObj,
                                                 HandleValue reason) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);
  assertSameCompartment(cx, reason);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  return ReadableStream::cancel(cx, stream, reason);
}

JS_PUBLIC_API JS::ReadableStreamMode JS::ReadableStreamGetMode(
    const JSObject* stream) {
  return stream->as<ReadableStream>().mode();
}

JS_PUBLIC_API JSObject* JS::ReadableStreamGetReader(
    JSContext* cx, HandleObject streamObj, ReadableStreamReaderMode mode) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  return ReadableStream::getReader(cx, stream, mode);
}

JS_PUBLIC_API bool JS::ReadableStreamGetExternalUnderlyingSource(
    JSContext* cx, HandleObject streamObj, void** source) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  return ReadableStream::getExternalSource(cx, stream, source);
}

JS_PUBLIC_API void JS::ReadableStreamReleaseExternalUnderlyingSource(
    JSObject* stream) {
  stream->as<ReadableStream>().releaseExternalSource();
}

JS_PUBLIC_API bool JS::ReadableStreamUpdateDataAvailableFromSource(
    JSContext* cx, JS::HandleObject streamObj, uint32_t availableData) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  return ReadableStream::updateDataAvailableFromSource(cx, stream,
                                                       availableData);
}

JS_PUBLIC_API bool JS::ReadableStreamTee(JSContext* cx, HandleObject streamObj,
                                         MutableHandleObject branch1Obj,
                                         MutableHandleObject branch2Obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  Rooted<ReadableStream*> branch1Stream(cx);
  Rooted<ReadableStream*> branch2Stream(cx);

  if (!ReadableStream::tee(cx, stream, false, &branch1Stream, &branch2Stream))
    return false;

  branch1Obj.set(branch1Stream);
  branch2Obj.set(branch2Stream);

  return true;
}

JS_PUBLIC_API void JS::ReadableStreamGetDesiredSize(JSObject* streamObj,
                                                    bool* hasValue,
                                                    double* value) {
  streamObj->as<ReadableStream>().desiredSize(hasValue, value);
}

JS_PUBLIC_API bool JS::ReadableStreamClose(JSContext* cx,
                                           HandleObject streamObj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  return ReadableStream::close(cx, stream);
}

JS_PUBLIC_API bool JS::ReadableStreamEnqueue(JSContext* cx,
                                             HandleObject streamObj,
                                             HandleValue chunk) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);
  assertSameCompartment(cx, chunk);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  if (stream->mode() != JS::ReadableStreamMode::Default) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_NOT_DEFAULT_CONTROLLER,
                              "JS::ReadableStreamEnqueue");
    return false;
  }
  return ReadableStream::enqueue(cx, stream, chunk);
}

JS_PUBLIC_API bool JS::ReadableByteStreamEnqueueBuffer(JSContext* cx,
                                                       HandleObject streamObj,
                                                       HandleObject chunkObj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);
  assertSameCompartment(cx, chunkObj);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  if (stream->mode() != JS::ReadableStreamMode::Byte) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_NOT_BYTE_STREAM_CONTROLLER,
                              "JS::ReadableByteStreamEnqueueBuffer");
    return false;
  }

  Rooted<ArrayBufferObject*> buffer(cx);
  if (chunkObj->is<ArrayBufferViewObject>()) {
    bool dummy;
    buffer = &JS_GetArrayBufferViewBuffer(cx, chunkObj, &dummy)
                  ->as<ArrayBufferObject>();
  } else if (chunkObj->is<ArrayBufferObject>()) {
    buffer = &chunkObj->as<ArrayBufferObject>();
  } else {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLEBYTESTREAMCONTROLLER_BAD_CHUNK,
                              "JS::ReadableByteStreamEnqueueBuffer");
    return false;
  }

  return ReadableStream::enqueueBuffer(cx, stream, buffer);
}

JS_PUBLIC_API bool JS::ReadableStreamError(JSContext* cx,
                                           HandleObject streamObj,
                                           HandleValue error) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, streamObj);
  assertSameCompartment(cx, error);

  Rooted<ReadableStream*> stream(cx, &streamObj->as<ReadableStream>());
  return js::ReadableStream::error(cx, stream, error);
}

JS_PUBLIC_API bool JS::ReadableStreamReaderIsClosed(const JSObject* reader) {
  return js::ReadableStreamReaderIsClosed(reader);
}

JS_PUBLIC_API bool JS::ReadableStreamReaderCancel(JSContext* cx,
                                                  HandleObject reader,
                                                  HandleValue reason) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, reader);
  assertSameCompartment(cx, reason);

  return js::ReadableStreamReaderCancel(cx, reader, reason);
}

JS_PUBLIC_API bool JS::ReadableStreamReaderReleaseLock(JSContext* cx,
                                                       HandleObject reader) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, reader);

  return js::ReadableStreamReaderReleaseLock(cx, reader);
}

JS_PUBLIC_API JSObject* JS::ReadableStreamDefaultReaderRead(
    JSContext* cx, HandleObject readerObj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, readerObj);

  Rooted<ReadableStreamDefaultReader*> reader(
      cx, &readerObj->as<ReadableStreamDefaultReader>());
  return js::ReadableStreamDefaultReader::read(cx, reader);
}

JS_PUBLIC_API JSObject* JS::ReadableStreamBYOBReaderRead(JSContext* cx,
                                                         HandleObject readerObj,
                                                         HandleObject viewObj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, readerObj);
  assertSameCompartment(cx, viewObj);

  Rooted<ReadableStreamBYOBReader*> reader(
      cx, &readerObj->as<ReadableStreamBYOBReader>());
  Rooted<ArrayBufferViewObject*> view(cx,
                                      &viewObj->as<ArrayBufferViewObject>());
  return js::ReadableStreamBYOBReader::read(cx, reader, view);
}

JS_PUBLIC_API void JS::InitDispatchToEventLoop(
    JSContext* cx, JS::DispatchToEventLoopCallback callback, void* closure) {
  cx->runtime()->offThreadPromiseState.ref().init(callback, closure);
}

JS_PUBLIC_API void JS::ShutdownAsyncTasks(JSContext* cx) {
  cx->runtime()->offThreadPromiseState.ref().shutdown(cx);
}

JS_PUBLIC_API void JS::InitConsumeStreamCallback(
    JSContext* cx, ConsumeStreamCallback callback) {
  cx->runtime()->consumeStreamCallback = callback;
}

JS_PUBLIC_API void JS_RequestInterruptCallback(JSContext* cx) {
  cx->requestInterrupt(JSContext::RequestInterruptUrgent);
}

JS_PUBLIC_API void JS_RequestInterruptCallbackCanWait(JSContext* cx) {
  cx->requestInterrupt(JSContext::RequestInterruptCanWait);
}

JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
    JSContext* cx, HandleObject stack, const char* asyncCause,
    JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)
    : cx(cx),
      oldAsyncStack(cx, cx->asyncStackForNewActivations()),
      oldAsyncCause(cx->asyncCauseForNewActivations),
      oldAsyncCallIsExplicit(cx->asyncCallIsExplicit) {
  CHECK_REQUEST(cx);

  // The option determines whether we actually use the new values at this
  // point. It will not affect restoring the previous values when the object
  // is destroyed, so if the option changes it won't cause consistency issues.
  if (!cx->options().asyncStack()) return;

  SavedFrame* asyncStack = &stack->as<SavedFrame>();

  cx->asyncStackForNewActivations() = asyncStack;
  cx->asyncCauseForNewActivations = asyncCause;
  cx->asyncCallIsExplicit = kind == AsyncCallKind::EXPLICIT;
}

JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls() {
  cx->asyncCauseForNewActivations = oldAsyncCause;
  cx->asyncStackForNewActivations() =
      oldAsyncStack ? &oldAsyncStack->as<SavedFrame>() : nullptr;
  cx->asyncCallIsExplicit = oldAsyncCallIsExplicit;
}

/************************************************************************/
JS_PUBLIC_API JSString* JS_NewStringCopyN(JSContext* cx, const char* s,
                                          size_t n) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewStringCopyN<CanGC>(cx, s, n);
}

JS_PUBLIC_API JSString* JS_NewStringCopyZ(JSContext* cx, const char* s) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (!s) return cx->runtime()->emptyString;
  return NewStringCopyZ<CanGC>(cx, s);
}

JS_PUBLIC_API JSString* JS_NewStringCopyUTF8Z(JSContext* cx,
                                              const JS::ConstUTF8CharsZ s) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewStringCopyUTF8Z<CanGC>(cx, s);
}

JS_PUBLIC_API JSString* JS_NewStringCopyUTF8N(JSContext* cx,
                                              const JS::UTF8Chars s) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewStringCopyUTF8N<CanGC>(cx, s);
}

JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  if (!str->isAtom()) return false;

  return AtomIsPinned(cx, &str->asAtom());
}

JS_PUBLIC_API jsid INTERNED_STRING_TO_JSID(JSContext* cx, JSString* str) {
  MOZ_ASSERT(str);
  MOZ_ASSERT(((size_t)str & JSID_TYPE_MASK) == 0);
  MOZ_ASSERT_IF(cx, JS_StringHasBeenPinned(cx, str));
  return AtomToId(&str->asAtom());
}

JS_PUBLIC_API JSString* JS_AtomizeAndPinJSString(JSContext* cx,
                                                 HandleString str) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JSAtom* atom = AtomizeString(cx, str, PinAtom);
  MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
  return atom;
}

JS_PUBLIC_API JSString* JS_AtomizeString(JSContext* cx, const char* s) {
  return JS_AtomizeStringN(cx, s, strlen(s));
}

JS_PUBLIC_API JSString* JS_AtomizeStringN(JSContext* cx, const char* s,
                                          size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return Atomize(cx, s, length, DoNotPinAtom);
}

JS_PUBLIC_API JSString* JS_AtomizeAndPinString(JSContext* cx, const char* s) {
  return JS_AtomizeAndPinStringN(cx, s, strlen(s));
}

JS_PUBLIC_API JSString* JS_AtomizeAndPinStringN(JSContext* cx, const char* s,
                                                size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JSAtom* atom = Atomize(cx, s, length, PinAtom);
  MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
  return atom;
}

JS_PUBLIC_API JSString* JS_NewLatin1String(JSContext* cx, JS::Latin1Char* chars,
                                           size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewString<CanGC>(cx, chars, length);
}

JS_PUBLIC_API JSString* JS_NewUCString(JSContext* cx, char16_t* chars,
                                       size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewString<CanGC>(cx, chars, length);
}

JS_PUBLIC_API JSString* JS_NewUCStringCopyN(JSContext* cx, const char16_t* s,
                                            size_t n) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (!n) return cx->names().empty;
  return NewStringCopyN<CanGC>(cx, s, n);
}

JS_PUBLIC_API JSString* JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (!s) return cx->runtime()->emptyString;
  return NewStringCopyZ<CanGC>(cx, s);
}

JS_PUBLIC_API JSString* JS_AtomizeUCString(JSContext* cx, const char16_t* s) {
  return JS_AtomizeUCStringN(cx, s, js_strlen(s));
}

JS_PUBLIC_API JSString* JS_AtomizeUCStringN(JSContext* cx, const char16_t* s,
                                            size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return AtomizeChars(cx, s, length, DoNotPinAtom);
}

JS_PUBLIC_API JSString* JS_AtomizeAndPinUCStringN(JSContext* cx,
                                                  const char16_t* s,
                                                  size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  JSAtom* atom = AtomizeChars(cx, s, length, PinAtom);
  MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
  return atom;
}

JS_PUBLIC_API JSString* JS_AtomizeAndPinUCString(JSContext* cx,
                                                 const char16_t* s) {
  return JS_AtomizeAndPinUCStringN(cx, s, js_strlen(s));
}

JS_PUBLIC_API size_t JS_GetStringLength(JSString* str) { return str->length(); }

JS_PUBLIC_API bool JS_StringIsFlat(JSString* str) { return str->isFlat(); }

JS_PUBLIC_API bool JS_StringHasLatin1Chars(JSString* str) {
  return str->hasLatin1Chars();
}

JS_PUBLIC_API const JS::Latin1Char* JS_GetLatin1StringCharsAndLength(
    JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
    size_t* plength) {
  MOZ_ASSERT(plength);
  AssertHeapIsIdleOrStringIsFlat(str);
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, str);
  JSLinearString* linear = str->ensureLinear(cx);
  if (!linear) return nullptr;
  *plength = linear->length();
  return linear->latin1Chars(nogc);
}

JS_PUBLIC_API const char16_t* JS_GetTwoByteStringCharsAndLength(
    JSContext* cx, const JS::AutoRequireNoGC& nogc, JSString* str,
    size_t* plength) {
  MOZ_ASSERT(plength);
  AssertHeapIsIdleOrStringIsFlat(str);
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, str);
  JSLinearString* linear = str->ensureLinear(cx);
  if (!linear) return nullptr;
  *plength = linear->length();
  return linear->twoByteChars(nogc);
}

JS_PUBLIC_API const char16_t* JS_GetTwoByteExternalStringChars(JSString* str) {
  return str->asExternal().twoByteChars();
}

JS_PUBLIC_API bool JS_GetStringCharAt(JSContext* cx, JSString* str,
                                      size_t index, char16_t* res) {
  AssertHeapIsIdleOrStringIsFlat(str);
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, str);

  JSLinearString* linear = str->ensureLinear(cx);
  if (!linear) return false;

  *res = linear->latin1OrTwoByteChar(index);
  return true;
}

JS_PUBLIC_API char16_t JS_GetFlatStringCharAt(JSFlatString* str, size_t index) {
  return str->latin1OrTwoByteChar(index);
}

JS_PUBLIC_API bool JS_CopyStringChars(JSContext* cx,
                                      mozilla::Range<char16_t> dest,
                                      JSString* str) {
  AssertHeapIsIdleOrStringIsFlat(str);
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, str);

  JSLinearString* linear = str->ensureLinear(cx);
  if (!linear) return false;

  MOZ_ASSERT(linear->length() <= dest.length());
  CopyChars(dest.begin().get(), *linear);
  return true;
}

JS_PUBLIC_API const Latin1Char* JS_GetLatin1InternedStringChars(
    const JS::AutoRequireNoGC& nogc, JSString* str) {
  MOZ_ASSERT(str->isAtom());
  JSFlatString* flat = str->ensureFlat(nullptr);
  if (!flat) return nullptr;
  return flat->latin1Chars(nogc);
}

JS_PUBLIC_API const char16_t* JS_GetTwoByteInternedStringChars(
    const JS::AutoRequireNoGC& nogc, JSString* str) {
  MOZ_ASSERT(str->isAtom());
  JSFlatString* flat = str->ensureFlat(nullptr);
  if (!flat) return nullptr;
  return flat->twoByteChars(nogc);
}

extern JS_PUBLIC_API JSFlatString* JS_FlattenString(JSContext* cx,
                                                    JSString* str) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, str);
  JSFlatString* flat = str->ensureFlat(cx);
  if (!flat) return nullptr;
  return flat;
}

extern JS_PUBLIC_API const Latin1Char* JS_GetLatin1FlatStringChars(
    const JS::AutoRequireNoGC& nogc, JSFlatString* str) {
  return str->latin1Chars(nogc);
}

extern JS_PUBLIC_API const char16_t* JS_GetTwoByteFlatStringChars(
    const JS::AutoRequireNoGC& nogc, JSFlatString* str) {
  return str->twoByteChars(nogc);
}

JS_PUBLIC_API bool JS_CompareStrings(JSContext* cx, JSString* str1,
                                     JSString* str2, int32_t* result) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return CompareStrings(cx, str1, str2, result);
}

JS_PUBLIC_API bool JS_StringEqualsAscii(JSContext* cx, JSString* str,
                                        const char* asciiBytes, bool* match) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  JSLinearString* linearStr = str->ensureLinear(cx);
  if (!linearStr) return false;
  *match = StringEqualsAscii(linearStr, asciiBytes);
  return true;
}

JS_PUBLIC_API bool JS_FlatStringEqualsAscii(JSFlatString* str,
                                            const char* asciiBytes) {
  return StringEqualsAscii(str, asciiBytes);
}

JS_PUBLIC_API size_t JS_PutEscapedFlatString(char* buffer, size_t size,
                                             JSFlatString* str, char quote) {
  return PutEscapedString(buffer, size, str, quote);
}

JS_PUBLIC_API size_t JS_PutEscapedString(JSContext* cx, char* buffer,
                                         size_t size, JSString* str,
                                         char quote) {
  AssertHeapIsIdle();
  JSLinearString* linearStr = str->ensureLinear(cx);
  if (!linearStr) return size_t(-1);
  return PutEscapedString(buffer, size, linearStr, quote);
}

JS_PUBLIC_API bool JS_FileEscapedString(FILE* fp, JSString* str, char quote) {
  JSLinearString* linearStr = str->ensureLinear(nullptr);
  return linearStr && FileEscapedString(fp, linearStr, quote);
}

JS_PUBLIC_API JSString* JS_NewDependentString(JSContext* cx, HandleString str,
                                              size_t start, size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewDependentString(cx, str, start, length);
}

JS_PUBLIC_API JSString* JS_ConcatStrings(JSContext* cx, HandleString left,
                                         HandleString right) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return ConcatStrings<CanGC>(cx, left, right);
}

JS_PUBLIC_API bool JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen,
                                  char16_t* dst, size_t* dstlenp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  if (!dst) {
    *dstlenp = srclen;
    return true;
  }

  size_t dstlen = *dstlenp;

  if (srclen > dstlen) {
    CopyAndInflateChars(dst, src, dstlen);

    AutoSuppressGC suppress(cx);
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BUFFER_TOO_SMALL);
    return false;
  }

  CopyAndInflateChars(dst, src, srclen);
  *dstlenp = srclen;
  return true;
}

static char* EncodeLatin1(JSContext* cx, JSString* str) {
  JSLinearString* linear = str->ensureLinear(cx);
  if (!linear) return nullptr;

  JS::AutoCheckCannotGC nogc;
  if (linear->hasTwoByteChars())
    return JS::LossyTwoByteCharsToNewLatin1CharsZ(cx,
                                                  linear->twoByteRange(nogc))
        .c_str();

  size_t len = str->length();
  Latin1Char* buf = cx->pod_malloc<Latin1Char>(len + 1);
  if (!buf) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  mozilla::PodCopy(buf, linear->latin1Chars(nogc), len);
  buf[len] = '\0';
  return reinterpret_cast<char*>(buf);
}

JS_PUBLIC_API char* JS_EncodeString(JSContext* cx, JSString* str) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return EncodeLatin1(cx, str);
}

JS_PUBLIC_API char* JS_EncodeStringToUTF8(JSContext* cx, HandleString str) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return StringToNewUTF8CharsZ(cx, *str).release();
}

JS_PUBLIC_API size_t JS_GetStringEncodingLength(JSContext* cx, JSString* str) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  if (!str->ensureLinear(cx)) return size_t(-1);
  return str->length();
}

JS_PUBLIC_API size_t JS_EncodeStringToBuffer(JSContext* cx, JSString* str,
                                             char* buffer, size_t length) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  /*
   * FIXME bug 612141 - fix DeflateStringToBuffer interface so the result
   * would allow to distinguish between insufficient buffer and encoding
   * error.
   */
  size_t writtenLength = length;
  JSLinearString* linear = str->ensureLinear(cx);
  if (!linear) return size_t(-1);

  bool res;
  if (linear->hasLatin1Chars()) {
    JS::AutoCheckCannotGC nogc;
    res = DeflateStringToBuffer(nullptr, linear->latin1Chars(nogc),
                                linear->length(), buffer, &writtenLength);
  } else {
    JS::AutoCheckCannotGC nogc;
    res = DeflateStringToBuffer(nullptr, linear->twoByteChars(nogc),
                                linear->length(), buffer, &writtenLength);
  }
  if (res) {
    MOZ_ASSERT(writtenLength <= length);
    return writtenLength;
  }
  MOZ_ASSERT(writtenLength <= length);
  size_t necessaryLength = str->length();
  if (necessaryLength == size_t(-1)) return size_t(-1);
  MOZ_ASSERT(writtenLength == length);  // C strings are NOT encoded.
  return necessaryLength;
}

JS_PUBLIC_API JS::Symbol* JS::NewSymbol(JSContext* cx,
                                        HandleString description) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (description) assertSameCompartment(cx, description);

  return Symbol::new_(cx, SymbolCode::UniqueSymbol, description);
}

JS_PUBLIC_API JS::Symbol* JS::GetSymbolFor(JSContext* cx, HandleString key) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, key);

  return Symbol::for_(cx, key);
}

JS_PUBLIC_API JSString* JS::GetSymbolDescription(HandleSymbol symbol) {
  return symbol->description();
}

JS_PUBLIC_API JS::SymbolCode JS::GetSymbolCode(Handle<Symbol*> symbol) {
  return symbol->code();
}

JS_PUBLIC_API JS::Symbol* JS::GetWellKnownSymbol(JSContext* cx,
                                                 JS::SymbolCode which) {
  return cx->wellKnownSymbols().get(uint32_t(which));
}

#ifdef DEBUG
static bool PropertySpecNameIsDigits(const char* s) {
  if (JS::PropertySpecNameIsSymbol(s)) return false;
  if (!*s) return false;
  for (; *s; s++) {
    if (*s < '0' || *s > '9') return false;
  }
  return true;
}
#endif  // DEBUG

JS_PUBLIC_API bool JS::PropertySpecNameEqualsId(const char* name, HandleId id) {
  if (JS::PropertySpecNameIsSymbol(name)) {
    if (!JSID_IS_SYMBOL(id)) return false;
    Symbol* sym = JSID_TO_SYMBOL(id);
    return sym->isWellKnownSymbol() &&
           sym->code() == PropertySpecNameToSymbolCode(name);
  }

  MOZ_ASSERT(!PropertySpecNameIsDigits(name));
  return JSID_IS_ATOM(id) && JS_FlatStringEqualsAscii(JSID_TO_ATOM(id), name);
}

JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp,
                                HandleObject replacer, HandleValue space,
                                JSONWriteCallback callback, void* data) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, replacer, space);
  StringBuffer sb(cx);
  if (!sb.ensureTwoByteChars()) return false;
  if (!Stringify(cx, vp, replacer, space, sb, StringifyBehavior::Normal))
    return false;
  if (sb.empty() && !sb.append(cx->names().null)) return false;
  return callback(sb.rawTwoByteBegin(), sb.length(), data);
}

JS_PUBLIC_API bool JS::ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input,
                                         JSONWriteCallback callback,
                                         void* data) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, input);

  StringBuffer sb(cx);
  if (!sb.ensureTwoByteChars()) return false;

  RootedValue inputValue(cx, ObjectValue(*input));
  if (!Stringify(cx, &inputValue, nullptr, NullHandleValue, sb,
                 StringifyBehavior::RestrictedSafe))
    return false;

  if (sb.empty() && !sb.append(cx->names().null)) return false;

  return callback(sb.rawTwoByteBegin(), sb.length(), data);
}

JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, const char16_t* chars,
                                uint32_t len, MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
                              NullHandleValue, vp);
}

JS_PUBLIC_API bool JS_ParseJSON(JSContext* cx, HandleString str,
                                MutableHandleValue vp) {
  return JS_ParseJSONWithReviver(cx, str, NullHandleValue, vp);
}

JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars,
                                           uint32_t len, HandleValue reviver,
                                           MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len),
                              reviver, vp);
}

JS_PUBLIC_API bool JS_ParseJSONWithReviver(JSContext* cx, HandleString str,
                                           HandleValue reviver,
                                           MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, str);

  AutoStableStringChars stableChars(cx);
  if (!stableChars.init(cx, str)) return false;

  return stableChars.isLatin1()
             ? ParseJSONWithReviver(cx, stableChars.latin1Range(), reviver, vp)
             : ParseJSONWithReviver(cx, stableChars.twoByteRange(), reviver,
                                    vp);
}

/************************************************************************/

JS_PUBLIC_API void JS_ReportErrorASCII(JSContext* cx, const char* format, ...) {
  va_list ap;

  AssertHeapIsIdle();
  va_start(ap, format);
  ReportErrorVA(cx, JSREPORT_ERROR, format, ArgumentsAreASCII, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorLatin1(JSContext* cx, const char* format,
                                        ...) {
  va_list ap;

  AssertHeapIsIdle();
  va_start(ap, format);
  ReportErrorVA(cx, JSREPORT_ERROR, format, ArgumentsAreLatin1, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) {
  va_list ap;

  AssertHeapIsIdle();
  va_start(ap, format);
  ReportErrorVA(cx, JSREPORT_ERROR, format, ArgumentsAreUTF8, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberASCII(JSContext* cx,
                                             JSErrorCallback errorCallback,
                                             void* userRef,
                                             const unsigned errorNumber, ...) {
  va_list ap;
  va_start(ap, errorNumber);
  JS_ReportErrorNumberASCIIVA(cx, errorCallback, userRef, errorNumber, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberASCIIVA(JSContext* cx,
                                               JSErrorCallback errorCallback,
                                               void* userRef,
                                               const unsigned errorNumber,
                                               va_list ap) {
  AssertHeapIsIdle();
  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
                      ArgumentsAreASCII, ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberLatin1(JSContext* cx,
                                              JSErrorCallback errorCallback,
                                              void* userRef,
                                              const unsigned errorNumber, ...) {
  va_list ap;
  va_start(ap, errorNumber);
  JS_ReportErrorNumberLatin1VA(cx, errorCallback, userRef, errorNumber, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberLatin1VA(JSContext* cx,
                                                JSErrorCallback errorCallback,
                                                void* userRef,
                                                const unsigned errorNumber,
                                                va_list ap) {
  AssertHeapIsIdle();
  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
                      ArgumentsAreLatin1, ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberUTF8(JSContext* cx,
                                            JSErrorCallback errorCallback,
                                            void* userRef,
                                            const unsigned errorNumber, ...) {
  va_list ap;
  va_start(ap, errorNumber);
  JS_ReportErrorNumberUTF8VA(cx, errorCallback, userRef, errorNumber, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberUTF8VA(JSContext* cx,
                                              JSErrorCallback errorCallback,
                                              void* userRef,
                                              const unsigned errorNumber,
                                              va_list ap) {
  AssertHeapIsIdle();
  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
                      ArgumentsAreUTF8, ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberUC(JSContext* cx,
                                          JSErrorCallback errorCallback,
                                          void* userRef,
                                          const unsigned errorNumber, ...) {
  va_list ap;

  AssertHeapIsIdle();
  va_start(ap, errorNumber);
  ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, errorNumber,
                      ArgumentsAreUnicode, ap);
  va_end(ap);
}

JS_PUBLIC_API void JS_ReportErrorNumberUCArray(JSContext* cx,
                                               JSErrorCallback errorCallback,
                                               void* userRef,
                                               const unsigned errorNumber,
                                               const char16_t** args) {
  AssertHeapIsIdle();
  ReportErrorNumberUCArray(cx, JSREPORT_ERROR, errorCallback, userRef,
                           errorNumber, args);
}

JS_PUBLIC_API bool JS_ReportWarningASCII(JSContext* cx, const char* format,
                                         ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, format);
  ok = ReportErrorVA(cx, JSREPORT_WARNING, format, ArgumentsAreASCII, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API bool JS_ReportWarningLatin1(JSContext* cx, const char* format,
                                          ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, format);
  ok = ReportErrorVA(cx, JSREPORT_WARNING, format, ArgumentsAreLatin1, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API bool JS_ReportWarningUTF8(JSContext* cx, const char* format,
                                        ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, format);
  ok = ReportErrorVA(cx, JSREPORT_WARNING, format, ArgumentsAreUTF8, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberASCII(
    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
    const unsigned errorNumber, ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, errorNumber);
  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
                           ArgumentsAreASCII, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberLatin1(
    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
    const unsigned errorNumber, ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, errorNumber);
  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
                           ArgumentsAreLatin1, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberUTF8(
    JSContext* cx, unsigned flags, JSErrorCallback errorCallback, void* userRef,
    const unsigned errorNumber, ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, errorNumber);
  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
                           ArgumentsAreUTF8, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API bool JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags,
                                                  JSErrorCallback errorCallback,
                                                  void* userRef,
                                                  const unsigned errorNumber,
                                                  ...) {
  va_list ap;
  bool ok;

  AssertHeapIsIdle();
  va_start(ap, errorNumber);
  ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef, errorNumber,
                           ArgumentsAreUnicode, ap);
  va_end(ap);
  return ok;
}

JS_PUBLIC_API void JS_ReportOutOfMemory(JSContext* cx) {
  ReportOutOfMemory(cx);
}

JS_PUBLIC_API void JS_ReportAllocationOverflow(JSContext* cx) {
  ReportAllocationOverflow(cx);
}

JS_PUBLIC_API JS::WarningReporter JS::GetWarningReporter(JSContext* cx) {
  return cx->runtime()->warningReporter;
}

JS_PUBLIC_API JS::WarningReporter JS::SetWarningReporter(
    JSContext* cx, JS::WarningReporter reporter) {
  WarningReporter older = cx->runtime()->warningReporter;
  cx->runtime()->warningReporter = reporter;
  return older;
}

/************************************************************************/

/*
 * Dates.
 */
JS_PUBLIC_API JSObject* JS_NewDateObject(JSContext* cx, int year, int mon,
                                         int mday, int hour, int min, int sec) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewDateObject(cx, year, mon, mday, hour, min, sec);
}

JS_PUBLIC_API JSObject* JS::NewDateObject(JSContext* cx, JS::ClippedTime time) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  return NewDateObjectMsec(cx, time);
}

JS_PUBLIC_API bool JS_ObjectIsDate(JSContext* cx, HandleObject obj,
                                   bool* isDate) {
  assertSameCompartment(cx, obj);

  ESClass cls;
  if (!GetBuiltinClass(cx, obj, &cls)) return false;

  *isDate = cls == ESClass::Date;
  return true;
}

/************************************************************************/

/*
 * Regular Expressions.
 */
JS_PUBLIC_API JSObject* JS_NewRegExpObject(JSContext* cx, const char* bytes,
                                           size_t length, unsigned flags) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  ScopedJSFreePtr<char16_t> chars(InflateString(cx, bytes, length));
  if (!chars) return nullptr;

  return RegExpObject::create(cx, chars.get(), length, RegExpFlag(flags),
                              cx->tempLifoAlloc(), GenericObject);
}

JS_PUBLIC_API JSObject* JS_NewUCRegExpObject(JSContext* cx,
                                             const char16_t* chars,
                                             size_t length, unsigned flags) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  return RegExpObject::create(cx, chars, length, RegExpFlag(flags),
                              cx->tempLifoAlloc(), GenericObject);
}

JS_PUBLIC_API bool JS_SetRegExpInput(JSContext* cx, HandleObject obj,
                                     HandleString input) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, input);

  Handle<GlobalObject*> global = obj.as<GlobalObject>();
  RegExpStatics* res = GlobalObject::getRegExpStatics(cx, global);
  if (!res) return false;

  res->reset(input);
  return true;
}

JS_PUBLIC_API bool JS_ClearRegExpStatics(JSContext* cx, HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  MOZ_ASSERT(obj);

  Handle<GlobalObject*> global = obj.as<GlobalObject>();
  RegExpStatics* res = GlobalObject::getRegExpStatics(cx, global);
  if (!res) return false;

  res->clear();
  return true;
}

JS_PUBLIC_API bool JS_ExecuteRegExp(JSContext* cx, HandleObject obj,
                                    HandleObject reobj, char16_t* chars,
                                    size_t length, size_t* indexp, bool test,
                                    MutableHandleValue rval) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  Handle<GlobalObject*> global = obj.as<GlobalObject>();
  RegExpStatics* res = GlobalObject::getRegExpStatics(cx, global);
  if (!res) return false;

  RootedLinearString input(cx, NewStringCopyN<CanGC>(cx, chars, length));
  if (!input) return false;

  return ExecuteRegExpLegacy(cx, res, reobj.as<RegExpObject>(), input, indexp,
                             test, rval);
}

JS_PUBLIC_API bool JS_ExecuteRegExpNoStatics(JSContext* cx, HandleObject obj,
                                             char16_t* chars, size_t length,
                                             size_t* indexp, bool test,
                                             MutableHandleValue rval) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  RootedLinearString input(cx, NewStringCopyN<CanGC>(cx, chars, length));
  if (!input) return false;

  return ExecuteRegExpLegacy(cx, nullptr, obj.as<RegExpObject>(), input, indexp,
                             test, rval);
}

JS_PUBLIC_API bool JS_ObjectIsRegExp(JSContext* cx, HandleObject obj,
                                     bool* isRegExp) {
  assertSameCompartment(cx, obj);

  ESClass cls;
  if (!GetBuiltinClass(cx, obj, &cls)) return false;

  *isRegExp = cls == ESClass::RegExp;
  return true;
}

JS_PUBLIC_API unsigned JS_GetRegExpFlags(JSContext* cx, HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  RegExpShared* shared = RegExpToShared(cx, obj);
  if (!shared) return false;
  return shared->getFlags();
}

JS_PUBLIC_API JSString* JS_GetRegExpSource(JSContext* cx, HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);

  RegExpShared* shared = RegExpToShared(cx, obj);
  if (!shared) return nullptr;
  return shared->getSource();
}

/************************************************************************/

JS_PUBLIC_API bool JS_SetDefaultLocale(JSRuntime* rt, const char* locale) {
  AssertHeapIsIdle();
  return rt->setDefaultLocale(locale);
}

JS_PUBLIC_API UniqueChars JS_GetDefaultLocale(JSContext* cx) {
  AssertHeapIsIdle();
  if (const char* locale = cx->runtime()->getDefaultLocale())
    return UniqueChars(JS_strdup(cx, locale));

  return nullptr;
}

JS_PUBLIC_API void JS_ResetDefaultLocale(JSRuntime* rt) {
  AssertHeapIsIdle();
  rt->resetDefaultLocale();
}

JS_PUBLIC_API void JS_SetLocaleCallbacks(JSRuntime* rt,
                                         const JSLocaleCallbacks* callbacks) {
  AssertHeapIsIdle();
  rt->localeCallbacks = callbacks;
}

JS_PUBLIC_API const JSLocaleCallbacks* JS_GetLocaleCallbacks(JSRuntime* rt) {
  /* This function can be called by a finalizer. */
  return rt->localeCallbacks;
}

/************************************************************************/

JS_PUBLIC_API bool JS_IsExceptionPending(JSContext* cx) {
  /* This function can be called by a finalizer. */
  return (bool)cx->isExceptionPending();
}

JS_PUBLIC_API bool JS_GetPendingException(JSContext* cx,
                                          MutableHandleValue vp) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (!cx->isExceptionPending()) return false;
  return cx->getPendingException(vp);
}

JS_PUBLIC_API void JS_SetPendingException(JSContext* cx, HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  releaseAssertSameCompartment(cx, value);
  cx->setPendingException(value);
}

JS_PUBLIC_API void JS_ClearPendingException(JSContext* cx) {
  AssertHeapIsIdle();
  cx->clearPendingException();
}

JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext* cx)
    : context(cx),
      wasPropagatingForcedReturn(cx->propagatingForcedReturn_),
      wasOverRecursed(cx->overRecursed_),
      wasThrowing(cx->throwing),
      exceptionValue(cx) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (wasPropagatingForcedReturn) cx->clearPropagatingForcedReturn();
  if (wasOverRecursed) cx->overRecursed_ = false;
  if (wasThrowing) {
    exceptionValue = cx->unwrappedException();
    cx->clearPendingException();
  }
}

void JS::AutoSaveExceptionState::restore() {
  context->propagatingForcedReturn_ = wasPropagatingForcedReturn;
  context->overRecursed_ = wasOverRecursed;
  context->throwing = wasThrowing;
  context->unwrappedException() = exceptionValue;
  drop();
}

JS::AutoSaveExceptionState::~AutoSaveExceptionState() {
  if (!context->isExceptionPending()) {
    if (wasPropagatingForcedReturn) context->setPropagatingForcedReturn();
    if (wasThrowing) {
      context->overRecursed_ = wasOverRecursed;
      context->throwing = true;
      context->unwrappedException() = exceptionValue;
    }
  }
}

struct JSExceptionState {
  explicit JSExceptionState(JSContext* cx) : exception(cx) {}
  bool throwing;
  PersistentRootedValue exception;
};

JS_PUBLIC_API JSExceptionState* JS_SaveExceptionState(JSContext* cx) {
  JSExceptionState* state;

  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  state = cx->new_<JSExceptionState>(cx);
  if (state) state->throwing = JS_GetPendingException(cx, &state->exception);
  return state;
}

JS_PUBLIC_API void JS_RestoreExceptionState(JSContext* cx,
                                            JSExceptionState* state) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  if (state) {
    if (state->throwing)
      JS_SetPendingException(cx, state->exception);
    else
      JS_ClearPendingException(cx);
    JS_DropExceptionState(cx, state);
  }
}

JS_PUBLIC_API void JS_DropExceptionState(JSContext* cx,
                                         JSExceptionState* state) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  js_delete(state);
}

JS_PUBLIC_API JSErrorReport* JS_ErrorFromException(JSContext* cx,
                                                   HandleObject obj) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, obj);
  return ErrorFromException(cx, obj);
}

void JSErrorReport::initBorrowedLinebuf(const char16_t* linebufArg,
                                        size_t linebufLengthArg,
                                        size_t tokenOffsetArg) {
  MOZ_ASSERT(linebufArg);
  MOZ_ASSERT(tokenOffsetArg <= linebufLengthArg);
  MOZ_ASSERT(linebufArg[linebufLengthArg] == '\0');

  linebuf_ = linebufArg;
  linebufLength_ = linebufLengthArg;
  tokenOffset_ = tokenOffsetArg;
}

void JSErrorReport::freeLinebuf() {
  if (ownsLinebuf_ && linebuf_) {
    js_free((void*)linebuf_);
    ownsLinebuf_ = false;
  }
  linebuf_ = nullptr;
}

JSString* JSErrorBase::newMessageString(JSContext* cx) {
  if (!message_) return cx->runtime()->emptyString;

  return JS_NewStringCopyUTF8Z(cx, message_);
}

void JSErrorBase::freeMessage() {
  if (ownsMessage_) {
    js_free((void*)message_.get());
    ownsMessage_ = false;
  }
  message_ = JS::ConstUTF8CharsZ();
}

JSErrorNotes::JSErrorNotes() : notes_() {}

JSErrorNotes::~JSErrorNotes() {}

static UniquePtr<JSErrorNotes::Note> CreateErrorNoteVA(
    JSContext* cx, const char* filename, unsigned lineno, unsigned column,
    JSErrorCallback errorCallback, void* userRef, const unsigned errorNumber,
    ErrorArgumentsType argumentsType, va_list ap) {
  auto note = MakeUnique<JSErrorNotes::Note>();
  if (!note) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  note->errorNumber = errorNumber;
  note->filename = filename;
  note->lineno = lineno;
  note->column = column;

  if (!ExpandErrorArgumentsVA(cx, errorCallback, userRef, errorNumber, nullptr,
                              argumentsType, note.get(), ap)) {
    return nullptr;
  }

  return note;
}

bool JSErrorNotes::addNoteASCII(JSContext* cx, const char* filename,
                                unsigned lineno, unsigned column,
                                JSErrorCallback errorCallback, void* userRef,
                                const unsigned errorNumber, ...) {
  va_list ap;
  va_start(ap, errorNumber);
  auto note = CreateErrorNoteVA(cx, filename, lineno, column, errorCallback,
                                userRef, errorNumber, ArgumentsAreASCII, ap);
  va_end(ap);

  if (!note) return false;
  if (!notes_.append(Move(note))) return false;
  return true;
}

bool JSErrorNotes::addNoteLatin1(JSContext* cx, const char* filename,
                                 unsigned lineno, unsigned column,
                                 JSErrorCallback errorCallback, void* userRef,
                                 const unsigned errorNumber, ...) {
  va_list ap;
  va_start(ap, errorNumber);
  auto note = CreateErrorNoteVA(cx, filename, lineno, column, errorCallback,
                                userRef, errorNumber, ArgumentsAreLatin1, ap);
  va_end(ap);

  if (!note) return false;
  if (!notes_.append(Move(note))) return false;
  return true;
}

bool JSErrorNotes::addNoteUTF8(JSContext* cx, const char* filename,
                               unsigned lineno, unsigned column,
                               JSErrorCallback errorCallback, void* userRef,
                               const unsigned errorNumber, ...) {
  va_list ap;
  va_start(ap, errorNumber);
  auto note = CreateErrorNoteVA(cx, filename, lineno, column, errorCallback,
                                userRef, errorNumber, ArgumentsAreUTF8, ap);
  va_end(ap);

  if (!note) return false;
  if (!notes_.append(Move(note))) return false;
  return true;
}

JS_PUBLIC_API size_t JSErrorNotes::length() { return notes_.length(); }

UniquePtr<JSErrorNotes> JSErrorNotes::copy(JSContext* cx) {
  auto copiedNotes = MakeUnique<JSErrorNotes>();
  if (!copiedNotes) {
    ReportOutOfMemory(cx);
    return nullptr;
  }

  for (auto&& note : *this) {
    js::UniquePtr<JSErrorNotes::Note> copied(CopyErrorNote(cx, note.get()));
    if (!copied) return nullptr;

    if (!copiedNotes->notes_.append(Move(copied))) return nullptr;
  }

  return copiedNotes;
}

JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::begin() {
  return iterator(notes_.begin());
}

JS_PUBLIC_API JSErrorNotes::iterator JSErrorNotes::end() {
  return iterator(notes_.end());
}

extern MOZ_NEVER_INLINE JS_PUBLIC_API void JS_AbortIfWrongThread(
    JSContext* cx) {
  if (!CurrentThreadCanAccessRuntime(cx->runtime())) MOZ_CRASH();
  if (TlsContext.get() != cx) MOZ_CRASH();
}

#ifdef JS_GC_ZEAL
JS_PUBLIC_API void JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits,
                                    uint32_t* frequency,
                                    uint32_t* nextScheduled) {
  cx->runtime()->gc.getZealBits(zealBits, frequency, nextScheduled);
}

JS_PUBLIC_API void JS_SetGCZeal(JSContext* cx, uint8_t zeal,
                                uint32_t frequency) {
  cx->runtime()->gc.setZeal(zeal, frequency);
}

JS_PUBLIC_API void JS_ScheduleGC(JSContext* cx, uint32_t count) {
  cx->runtime()->gc.setNextScheduled(count);
}
#endif

JS_PUBLIC_API void JS_SetParallelParsingEnabled(JSContext* cx, bool enabled) {
  cx->runtime()->setParallelParsingEnabled(enabled);
}

JS_PUBLIC_API void JS_SetOffthreadIonCompilationEnabled(JSContext* cx,
                                                        bool enabled) {
  cx->runtime()->setOffthreadIonCompilationEnabled(enabled);
}

JS_PUBLIC_API void JS_SetGlobalJitCompilerOption(JSContext* cx,
                                                 JSJitCompilerOption opt,
                                                 uint32_t value) {
  JSRuntime* rt = cx->runtime();
  switch (opt) {
    case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
      if (value == uint32_t(-1)) {
        jit::DefaultJitOptions defaultValues;
        value = defaultValues.baselineWarmUpThreshold;
      }
      jit::JitOptions.baselineWarmUpThreshold = value;
      break;
    case JSJITCOMPILER_ION_WARMUP_TRIGGER:
      if (value == uint32_t(-1)) {
        jit::JitOptions.resetCompilerWarmUpThreshold();
        break;
      }
      jit::JitOptions.setCompilerWarmUpThreshold(value);
      if (value == 0) jit::JitOptions.setEagerCompilation();
      break;
    case JSJITCOMPILER_ION_GVN_ENABLE:
      if (value == 0) {
        jit::JitOptions.enableGvn(false);
        JitSpew(js::jit::JitSpew_IonScripts, "Disable ion's GVN");
      } else {
        jit::JitOptions.enableGvn(true);
        JitSpew(js::jit::JitSpew_IonScripts, "Enable ion's GVN");
      }
      break;
    case JSJITCOMPILER_ION_FORCE_IC:
      if (value == 0) {
        jit::JitOptions.forceInlineCaches = false;
        JitSpew(js::jit::JitSpew_IonScripts,
                "IonBuilder: Enable non-IC optimizations.");
      } else {
        jit::JitOptions.forceInlineCaches = true;
        JitSpew(js::jit::JitSpew_IonScripts,
                "IonBuilder: Disable non-IC optimizations.");
      }
      break;
    case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
      if (value == 0) {
        jit::JitOptions.checkRangeAnalysis = false;
        JitSpew(js::jit::JitSpew_IonScripts,
                "IonBuilder: Enable range analysis checks.");
      } else {
        jit::JitOptions.checkRangeAnalysis = true;
        JitSpew(js::jit::JitSpew_IonScripts,
                "IonBuilder: Disable range analysis checks.");
      }
      break;
    case JSJITCOMPILER_ION_ENABLE:
      if (value == 1) {
        JS::ContextOptionsRef(cx).setIon(true);
        JitSpew(js::jit::JitSpew_IonScripts, "Enable ion");
      } else if (value == 0) {
        JS::ContextOptionsRef(cx).setIon(false);
        JitSpew(js::jit::JitSpew_IonScripts, "Disable ion");
      }
      break;
    case JSJITCOMPILER_BASELINE_ENABLE:
      if (value == 1) {
        JS::ContextOptionsRef(cx).setBaseline(true);
        ReleaseAllJITCode(rt->defaultFreeOp());
        JitSpew(js::jit::JitSpew_BaselineScripts, "Enable baseline");
      } else if (value == 0) {
        JS::ContextOptionsRef(cx).setBaseline(false);
        ReleaseAllJITCode(rt->defaultFreeOp());
        JitSpew(js::jit::JitSpew_BaselineScripts, "Disable baseline");
      }
      break;
    case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
      if (value == 1) {
        rt->setOffthreadIonCompilationEnabled(true);
        JitSpew(js::jit::JitSpew_IonScripts, "Enable offthread compilation");
      } else if (value == 0) {
        rt->setOffthreadIonCompilationEnabled(false);
        JitSpew(js::jit::JitSpew_IonScripts, "Disable offthread compilation");
      }
      break;
    case JSJITCOMPILER_JUMP_THRESHOLD:
      if (value == uint32_t(-1)) {
        jit::DefaultJitOptions defaultValues;
        value = defaultValues.jumpThreshold;
      }
      jit::JitOptions.jumpThreshold = value;
      break;
    case JSJITCOMPILER_UNBOXED_OBJECTS:
      jit::JitOptions.disableUnboxedObjects = !value;
      break;
    case JSJITCOMPILER_SIMULATOR_ALWAYS_INTERRUPT:
      jit::JitOptions.simulatorAlwaysInterrupt = !!value;
      break;
    case JSJITCOMPILER_SPECTRE_INDEX_MASKING:
      jit::JitOptions.spectreIndexMasking = !!value;
      break;
    case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS_BARRIERS:
      jit::JitOptions.spectreObjectMitigationsBarriers = !!value;
      break;
    case JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS_MISC:
      jit::JitOptions.spectreObjectMitigationsMisc = !!value;
      break;
    case JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS:
      jit::JitOptions.spectreStringMitigations = !!value;
      break;
    case JSJITCOMPILER_SPECTRE_VALUE_MASKING:
      jit::JitOptions.spectreValueMasking = !!value;
      break;
    case JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS:
      jit::JitOptions.spectreJitToCxxCalls = !!value;
      break;
    case JSJITCOMPILER_ASMJS_ATOMICS_ENABLE:
      jit::JitOptions.asmJSAtomicsEnable = !!value;
      break;
    case JSJITCOMPILER_WASM_FOLD_OFFSETS:
      jit::JitOptions.wasmFoldOffsets = !!value;
      break;
    case JSJITCOMPILER_WASM_DELAY_TIER2:
      jit::JitOptions.wasmDelayTier2 = !!value;
      break;
    case JSJITCOMPILER_ION_INTERRUPT_WITHOUT_SIGNAL:
      jit::JitOptions.ionInterruptWithoutSignals = !!value;
      break;
#ifdef DEBUG
    case JSJITCOMPILER_FULL_DEBUG_CHECKS:
      jit::JitOptions.fullDebugChecks = !!value;
      break;
#endif
    default:
      break;
  }
}

JS_PUBLIC_API bool JS_GetGlobalJitCompilerOption(JSContext* cx,
                                                 JSJitCompilerOption opt,
                                                 uint32_t* valueOut) {
  MOZ_ASSERT(valueOut);
#ifndef JS_CODEGEN_NONE
  JSRuntime* rt = cx->runtime();
  switch (opt) {
    case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
      *valueOut = jit::JitOptions.baselineWarmUpThreshold;
      break;
    case JSJITCOMPILER_ION_WARMUP_TRIGGER:
      *valueOut = jit::JitOptions.forcedDefaultIonWarmUpThreshold.valueOr(
          jit::OptimizationInfo::CompilerWarmupThreshold);
      break;
    case JSJITCOMPILER_ION_FORCE_IC:
      *valueOut = jit::JitOptions.forceInlineCaches;
      break;
    case JSJITCOMPILER_ION_CHECK_RANGE_ANALYSIS:
      *valueOut = jit::JitOptions.checkRangeAnalysis;
      break;
    case JSJITCOMPILER_ION_ENABLE:
      *valueOut = JS::ContextOptionsRef(cx).ion();
      break;
    case JSJITCOMPILER_BASELINE_ENABLE:
      *valueOut = JS::ContextOptionsRef(cx).baseline();
      break;
    case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
      *valueOut = rt->canUseOffthreadIonCompilation();
      break;
    case JSJITCOMPILER_ASMJS_ATOMICS_ENABLE:
      *valueOut = jit::JitOptions.asmJSAtomicsEnable ? 1 : 0;
      break;
    case JSJITCOMPILER_WASM_FOLD_OFFSETS:
      *valueOut = jit::JitOptions.wasmFoldOffsets ? 1 : 0;
      break;
    case JSJITCOMPILER_ION_INTERRUPT_WITHOUT_SIGNAL:
      *valueOut = jit::JitOptions.ionInterruptWithoutSignals ? 1 : 0;
      break;
#ifdef DEBUG
    case JSJITCOMPILER_FULL_DEBUG_CHECKS:
      *valueOut = jit::JitOptions.fullDebugChecks ? 1 : 0;
      break;
#endif
    default:
      return false;
  }
#else
  *valueOut = 0;
#endif
  return true;
}

  /************************************************************************/

#if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && \
    defined(XP_WIN)

#include "util/Windows.h"

/*
 * Initialization routine for the JS DLL.
 */
BOOL WINAPI DllMain(HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved) {
  return TRUE;
}

#endif

JS_PUBLIC_API bool JS_IndexToId(JSContext* cx, uint32_t index,
                                MutableHandleId id) {
  return IndexToId(cx, index, id);
}

JS_PUBLIC_API bool JS_CharsToId(JSContext* cx, JS::TwoByteChars chars,
                                MutableHandleId idp) {
  RootedAtom atom(cx, AtomizeChars(cx, chars.begin().get(), chars.length()));
  if (!atom) return false;
#ifdef DEBUG
  uint32_t dummy;
  MOZ_ASSERT(!atom->isIndex(&dummy),
             "API misuse: |chars| must not encode an index");
#endif
  idp.set(AtomToId(atom));
  return true;
}

JS_PUBLIC_API bool JS_IsIdentifier(JSContext* cx, HandleString str,
                                   bool* isIdentifier) {
  assertSameCompartment(cx, str);

  JSLinearString* linearStr = str->ensureLinear(cx);
  if (!linearStr) return false;

  *isIdentifier = js::frontend::IsIdentifier(linearStr);
  return true;
}

JS_PUBLIC_API bool JS_IsIdentifier(const char16_t* chars, size_t length) {
  return js::frontend::IsIdentifier(chars, length);
}

namespace JS {

void AutoFilename::reset() {
  if (ss_) {
    ss_->decref();
    ss_ = nullptr;
  }
  if (filename_.is<const char*>())
    filename_.as<const char*>() = nullptr;
  else
    filename_.as<UniqueChars>().reset();
}

void AutoFilename::setScriptSource(js::ScriptSource* p) {
  MOZ_ASSERT(!ss_);
  MOZ_ASSERT(!get());
  ss_ = p;
  if (p) {
    p->incref();
    setUnowned(p->filename());
  }
}

void AutoFilename::setUnowned(const char* filename) {
  MOZ_ASSERT(!get());
  filename_.as<const char*>() = filename ? filename : "";
}

void AutoFilename::setOwned(UniqueChars&& filename) {
  MOZ_ASSERT(!get());
  filename_ = AsVariant(Move(filename));
}

const char* AutoFilename::get() const {
  if (filename_.is<const char*>()) return filename_.as<const char*>();
  return filename_.as<UniqueChars>().get();
}

JS_PUBLIC_API bool DescribeScriptedCaller(JSContext* cx, AutoFilename* filename,
                                          unsigned* lineno, unsigned* column) {
  if (filename) filename->reset();
  if (lineno) *lineno = 0;
  if (column) *column = 0;

  if (!cx->compartment()) return false;

  NonBuiltinFrameIter i(cx, cx->compartment()->principals());
  if (i.done()) return false;

  // If the caller is hidden, the embedding wants us to return false here so
  // that it can check its own stack (see HideScriptedCaller).
  if (i.activation()->scriptedCallerIsHidden()) return false;

  if (filename) {
    if (i.isWasm()) {
      // For Wasm, copy out the filename, there is no script source.
      UniqueChars copy = DuplicateString(i.filename() ? i.filename() : "");
      if (!copy)
        filename->setUnowned("out of memory");
      else
        filename->setOwned(Move(copy));
    } else {
      // All other frames have a script source to read the filename from.
      filename->setScriptSource(i.scriptSource());
    }
  }

  if (lineno)
    *lineno = i.computeLine(column);
  else if (column)
    i.computeLine(column);

  return true;
}

// Fast path to get the activation to use for GetScriptedCallerGlobal. If this
// returns false, the fast path didn't work out and the caller has to use the
// (much slower) NonBuiltinFrameIter path.
//
// The optimization here is that we skip Ion-inlined frames and only look at
// 'outer' frames. That's fine: each activation is tied to a single compartment,
// so if an activation contains at least one non-self-hosted frame, we can use
// the activation's global for GetScriptedCallerGlobal. If, however, all 'outer'
// frames are self-hosted, it's possible Ion inlined a non-self-hosted script,
// so we must return false and use the slower path.
static bool GetScriptedCallerActivationFast(JSContext* cx,
                                            Activation** activation) {
  ActivationIterator activationIter(cx);

  if (activationIter.done()) {
    *activation = nullptr;
    return true;
  }

  *activation = activationIter.activation();

  if (activationIter->isJit()) {
    for (OnlyJSJitFrameIter iter(activationIter); !iter.done(); ++iter) {
      if (iter.frame().isScripted() && !iter.frame().script()->selfHosted())
        return true;
    }
  } else if (activationIter->isInterpreter()) {
    for (InterpreterFrameIterator iter((*activation)->asInterpreter());
         !iter.done(); ++iter) {
      if (!iter.frame()->script()->selfHosted()) return true;
    }
  }

  return false;
}

JS_PUBLIC_API JSObject* GetScriptedCallerGlobal(JSContext* cx) {
  Activation* activation;

  if (GetScriptedCallerActivationFast(cx, &activation)) {
    if (!activation) return nullptr;
  } else {
    NonBuiltinFrameIter i(cx);
    if (i.done()) return nullptr;
    activation = i.activation();
  }

  // If the caller is hidden, the embedding wants us to return null here so
  // that it can check its own stack (see HideScriptedCaller).
  if (activation->scriptedCallerIsHidden()) return nullptr;

  GlobalObject* global = activation->compartment()->maybeGlobal();

  // Noone should be running code in the atoms compartment or running code in
  // a compartment without any live objects, so there should definitely be a
  // live global.
  MOZ_ASSERT(global);

  return global;
}

JS_PUBLIC_API void HideScriptedCaller(JSContext* cx) {
  MOZ_ASSERT(cx);

  // If there's no accessible activation on the stack, we'll return null from
  // DescribeScriptedCaller anyway, so there's no need to annotate anything.
  Activation* act = cx->activation();
  if (!act) return;
  act->hideScriptedCaller();
}

JS_PUBLIC_API void UnhideScriptedCaller(JSContext* cx) {
  Activation* act = cx->activation();
  if (!act) return;
  act->unhideScriptedCaller();
}

} /* namespace JS */

#ifdef JS_DEBUG
JS_PUBLIC_API void JS::detail::AssertArgumentsAreSane(JSContext* cx,
                                                      HandleValue value) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  assertSameCompartment(cx, value);
}
#endif /* JS_DEBUG */

JS_PUBLIC_API JS::TranscodeResult JS::EncodeScript(JSContext* cx,
                                                   TranscodeBuffer& buffer,
                                                   HandleScript scriptArg) {
  XDREncoder encoder(cx, buffer, buffer.length());
  RootedScript script(cx, scriptArg);
  if (!encoder.codeScript(&script)) buffer.clearAndFree();
  MOZ_ASSERT(!buffer.empty() == (encoder.resultCode() == TranscodeResult_Ok));
  return encoder.resultCode();
}

JS_PUBLIC_API JS::TranscodeResult JS::EncodeInterpretedFunction(
    JSContext* cx, TranscodeBuffer& buffer, HandleObject funobjArg) {
  XDREncoder encoder(cx, buffer, buffer.length());
  RootedFunction funobj(cx, &funobjArg->as<JSFunction>());
  if (!encoder.codeFunction(&funobj)) buffer.clearAndFree();
  MOZ_ASSERT(!buffer.empty() == (encoder.resultCode() == TranscodeResult_Ok));
  return encoder.resultCode();
}

JS_PUBLIC_API JS::TranscodeResult JS::DecodeScript(
    JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleScript scriptp,
    size_t cursorIndex) {
  XDRDecoder decoder(cx, buffer, cursorIndex);
  decoder.codeScript(scriptp);
  MOZ_ASSERT(bool(scriptp) == (decoder.resultCode() == TranscodeResult_Ok));
  return decoder.resultCode();
}

JS_PUBLIC_API JS::TranscodeResult JS::DecodeScript(
    JSContext* cx, const TranscodeRange& range,
    JS::MutableHandleScript scriptp) {
  XDRDecoder decoder(cx, range);
  decoder.codeScript(scriptp);
  MOZ_ASSERT(bool(scriptp) == (decoder.resultCode() == TranscodeResult_Ok));
  return decoder.resultCode();
}

JS_PUBLIC_API JS::TranscodeResult JS::DecodeInterpretedFunction(
    JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleFunction funp,
    size_t cursorIndex) {
  XDRDecoder decoder(cx, buffer, cursorIndex);
  decoder.codeFunction(funp);
  MOZ_ASSERT(bool(funp) == (decoder.resultCode() == TranscodeResult_Ok));
  return decoder.resultCode();
}

JS_PUBLIC_API bool JS::StartIncrementalEncoding(JSContext* cx,
                                                JS::HandleScript script) {
  if (!script) return false;
  if (!script->scriptSource()->xdrEncodeTopLevel(cx, script)) return false;
  return true;
}

JS_PUBLIC_API bool JS::FinishIncrementalEncoding(JSContext* cx,
                                                 JS::HandleScript script,
                                                 TranscodeBuffer& buffer) {
  if (!script) return false;
  if (!script->scriptSource()->xdrFinalizeEncoder(buffer)) return false;
  return true;
}

JS_PUBLIC_API void JS::SetBuildIdOp(JSContext* cx, JS::BuildIdOp buildIdOp) {
  cx->runtime()->buildIdOp = buildIdOp;
}

JS_PUBLIC_API void JS::SetAsmJSCacheOps(JSContext* cx,
                                        const JS::AsmJSCacheOps* ops) {
  cx->runtime()->asmJSCacheOps = *ops;
}

bool JS::IsWasmModuleObject(HandleObject obj) {
  JSObject* unwrapped = CheckedUnwrap(obj);
  if (!unwrapped) return false;
  return unwrapped->is<WasmModuleObject>();
}

JS_PUBLIC_API RefPtr<JS::WasmModule> JS::GetWasmModule(HandleObject obj) {
  MOZ_ASSERT(JS::IsWasmModuleObject(obj));
  return &CheckedUnwrap(obj)->as<WasmModuleObject>().module();
}

JS_PUBLIC_API bool JS::CompiledWasmModuleAssumptionsMatch(
    PRFileDesc* compiled, JS::BuildIdCharVector&& buildId) {
  return wasm::CompiledModuleAssumptionsMatch(compiled, Move(buildId));
}

JS_PUBLIC_API RefPtr<JS::WasmModule> JS::DeserializeWasmModule(
    PRFileDesc* bytecode, PRFileDesc* maybeCompiled,
    JS::BuildIdCharVector&& buildId, UniqueChars file, unsigned line,
    unsigned column) {
  return wasm::DeserializeModule(bytecode, maybeCompiled, Move(buildId),
                                 Move(file), line, column);
}

JS_PUBLIC_API void JS::SetProcessLargeAllocationFailureCallback(
    JS::LargeAllocationFailureCallback lafc) {
  MOZ_ASSERT(!OnLargeAllocationFailure);
  OnLargeAllocationFailure = lafc;
}

JS_PUBLIC_API void JS::SetOutOfMemoryCallback(JSContext* cx,
                                              OutOfMemoryCallback cb,
                                              void* data) {
  cx->runtime()->oomCallback = cb;
  cx->runtime()->oomCallbackData = data;
}

JS::FirstSubsumedFrame::FirstSubsumedFrame(
    JSContext* cx, bool ignoreSelfHostedFrames /* = true */)
    : JS::FirstSubsumedFrame(cx, cx->compartment()->principals(),
                             ignoreSelfHostedFrames) {}

JS_PUBLIC_API bool JS::CaptureCurrentStack(
    JSContext* cx, JS::MutableHandleObject stackp,
    JS::StackCapture&& capture /* = JS::StackCapture(JS::AllFrames()) */) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  MOZ_RELEASE_ASSERT(cx->compartment());

  JSCompartment* compartment = cx->compartment();
  Rooted<SavedFrame*> frame(cx);
  if (!compartment->savedStacks().saveCurrentStack(cx, &frame,
                                                   mozilla::Move(capture)))
    return false;
  stackp.set(frame.get());
  return true;
}

JS_PUBLIC_API bool JS::CopyAsyncStack(JSContext* cx,
                                      JS::HandleObject asyncStack,
                                      JS::HandleString asyncCause,
                                      JS::MutableHandleObject stackp,
                                      const Maybe<size_t>& maxFrameCount) {
  AssertHeapIsIdle();
  CHECK_REQUEST(cx);
  MOZ_RELEASE_ASSERT(cx->compartment());

  js::AssertObjectIsSavedFrameOrWrapper(cx, asyncStack);
  JSCompartment* compartment = cx->compartment();
  Rooted<SavedFrame*> frame(cx);
  if (!compartment->savedStacks().copyAsyncStack(cx, asyncStack, asyncCause,
                                                 &frame, maxFrameCount))
    return false;
  stackp.set(frame.get());
  return true;
}

JS_PUBLIC_API Zone* JS::GetObjectZone(JSObject* obj) { return obj->zone(); }

JS_PUBLIC_API Zone* JS::GetNurseryStringZone(JSString* str) {
  MOZ_ASSERT(!str->isTenured());
  return str->zone();
}

JS_PUBLIC_API JS::TraceKind JS::GCThingTraceKind(void* thing) {
  MOZ_ASSERT(thing);
  return static_cast<js::gc::Cell*>(thing)->getTraceKind();
}

JS_PUBLIC_API void js::SetStackFormat(JSContext* cx, js::StackFormat format) {
  cx->runtime()->setStackFormat(format);
}

JS_PUBLIC_API js::StackFormat js::GetStackFormat(JSContext* cx) {
  return cx->runtime()->stackFormat();
}

namespace js {

JS_PUBLIC_API void NoteIntentionalCrash() {
#ifdef __linux__
  static bool* addr =
      reinterpret_cast<bool*>(dlsym(RTLD_DEFAULT, "gBreakpadInjectorEnabled"));
  if (addr) *addr = false;
#endif
}

}  // namespace js