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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* 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/. */
#include "jsstr.h"
#include "mozilla/Attributes.h"
#include "mozilla/Casting.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Range.h"
#include "mozilla/TypeTraits.h"
#include "mozilla/Unused.h"
#include <ctype.h>
#include <limits>
#include <string.h>
#include "jsapi.h"
#include "jsarray.h"
#include "jsatom.h"
#include "jsbool.h"
#include "jscntxt.h"
#include "jsgc.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jsopcode.h"
#include "jstypes.h"
#include "jsutil.h"
#include "builtin/intl/ICUHeader.h"
#include "builtin/intl/CommonFunctions.h"
#include "builtin/RegExp.h"
#include "jit/InlinableNatives.h"
#include "js/Conversions.h"
#include "js/UniquePtr.h"
#include "unicode/uchar.h"
#include "unicode/unorm2.h"
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
#include "vm/Opcodes.h"
#include "vm/Printer.h"
#include "vm/RegExpObject.h"
#include "vm/RegExpStatics.h"
#include "vm/StringBuffer.h"
#include "vm/Unicode.h"
#include "vm/Interpreter-inl.h"
#include "vm/String-inl.h"
#include "vm/StringObject-inl.h"
#include "vm/TypeInference-inl.h"
using namespace js;
using namespace js::gc;
using JS::Symbol;
using JS::SymbolCode;
using JS::ToInt32;
using JS::ToUint32;
using mozilla::AssertedCast;
using mozilla::CheckedInt;
using mozilla::IsNaN;
using mozilla::IsNegativeZero;
using mozilla::IsSame;
using mozilla::Move;
using mozilla::PodCopy;
using mozilla::PodEqual;
using mozilla::RangedPtr;
using JS::AutoCheckCannotGC;
static JSLinearString*
ArgToRootedString(JSContext* cx, const CallArgs& args, unsigned argno)
{
if (argno >= args.length())
return cx->names().undefined;
JSString* str = ToString<CanGC>(cx, args[argno]);
if (!str)
return nullptr;
args[argno].setString(str);
return str->ensureLinear(cx);
}
/*
* Forward declarations for URI encode/decode and helper routines
*/
static bool
str_decodeURI(JSContext* cx, unsigned argc, Value* vp);
static bool
str_decodeURI_Component(JSContext* cx, unsigned argc, Value* vp);
static bool
str_encodeURI(JSContext* cx, unsigned argc, Value* vp);
static bool
str_encodeURI_Component(JSContext* cx, unsigned argc, Value* vp);
/*
* Global string methods
*/
/* ES5 B.2.1 */
template <typename CharT>
static Latin1Char*
Escape(JSContext* cx, const CharT* chars, uint32_t length, uint32_t* newLengthOut)
{
static const uint8_t shouldPassThrough[128] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1, /* !"#$%&'()*+,-./ */
1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0, /* 0123456789:;<=>? */
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* @ABCDEFGHIJKLMNO */
1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1, /* PQRSTUVWXYZ[\]^_ */
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* `abcdefghijklmno */
1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0, /* pqrstuvwxyz{\}~ DEL */
};
/* Take a first pass and see how big the result string will need to be. */
uint32_t newLength = length;
for (size_t i = 0; i < length; i++) {
char16_t ch = chars[i];
if (ch < 128 && shouldPassThrough[ch])
continue;
/* The character will be encoded as %XX or %uXXXX. */
newLength += (ch < 256) ? 2 : 5;
/*
* newlength is incremented by at most 5 on each iteration, so worst
* case newlength == length * 6. This can't overflow.
*/
static_assert(JSString::MAX_LENGTH < UINT32_MAX / 6,
"newlength must not overflow");
}
Latin1Char* newChars = cx->pod_malloc<Latin1Char>(newLength + 1);
if (!newChars)
return nullptr;
static const char digits[] = "0123456789ABCDEF";
size_t i, ni;
for (i = 0, ni = 0; i < length; i++) {
char16_t ch = chars[i];
if (ch < 128 && shouldPassThrough[ch]) {
newChars[ni++] = ch;
} else if (ch < 256) {
newChars[ni++] = '%';
newChars[ni++] = digits[ch >> 4];
newChars[ni++] = digits[ch & 0xF];
} else {
newChars[ni++] = '%';
newChars[ni++] = 'u';
newChars[ni++] = digits[ch >> 12];
newChars[ni++] = digits[(ch & 0xF00) >> 8];
newChars[ni++] = digits[(ch & 0xF0) >> 4];
newChars[ni++] = digits[ch & 0xF];
}
}
MOZ_ASSERT(ni == newLength);
newChars[newLength] = 0;
*newLengthOut = newLength;
return newChars;
}
static bool
str_escape(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSLinearString* str = ArgToRootedString(cx, args, 0);
if (!str)
return false;
ScopedJSFreePtr<Latin1Char> newChars;
uint32_t newLength = 0; // initialize to silence GCC warning
if (str->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
newChars = Escape(cx, str->latin1Chars(nogc), str->length(), &newLength);
} else {
AutoCheckCannotGC nogc;
newChars = Escape(cx, str->twoByteChars(nogc), str->length(), &newLength);
}
if (!newChars)
return false;
JSString* res = NewString<CanGC>(cx, newChars.get(), newLength);
if (!res)
return false;
newChars.forget();
args.rval().setString(res);
return true;
}
template <typename CharT>
static inline bool
Unhex4(const RangedPtr<const CharT> chars, char16_t* result)
{
char16_t a = chars[0],
b = chars[1],
c = chars[2],
d = chars[3];
if (!(JS7_ISHEX(a) && JS7_ISHEX(b) && JS7_ISHEX(c) && JS7_ISHEX(d)))
return false;
*result = (((((JS7_UNHEX(a) << 4) + JS7_UNHEX(b)) << 4) + JS7_UNHEX(c)) << 4) + JS7_UNHEX(d);
return true;
}
template <typename CharT>
static inline bool
Unhex2(const RangedPtr<const CharT> chars, char16_t* result)
{
char16_t a = chars[0],
b = chars[1];
if (!(JS7_ISHEX(a) && JS7_ISHEX(b)))
return false;
*result = (JS7_UNHEX(a) << 4) + JS7_UNHEX(b);
return true;
}
template <typename CharT>
static bool
Unescape(StringBuffer& sb, const mozilla::Range<const CharT> chars)
{
/*
* NB: use signed integers for length/index to allow simple length
* comparisons without unsigned-underflow hazards.
*/
static_assert(JSString::MAX_LENGTH <= INT_MAX, "String length must fit in a signed integer");
int length = AssertedCast<int>(chars.length());
/*
* Note that the spec algorithm has been optimized to avoid building
* a string in the case where no escapes are present.
*/
/* Step 4. */
int k = 0;
bool building = false;
/* Step 5. */
while (k < length) {
/* Step 6. */
char16_t c = chars[k];
/* Step 7. */
if (c != '%')
goto step_18;
/* Step 8. */
if (k > length - 6)
goto step_14;
/* Step 9. */
if (chars[k + 1] != 'u')
goto step_14;
#define ENSURE_BUILDING \
do { \
if (!building) { \
building = true; \
if (!sb.reserve(length)) \
return false; \
sb.infallibleAppend(chars.begin().get(), k); \
} \
} while(false);
/* Step 10-13. */
if (Unhex4(chars.begin() + k + 2, &c)) {
ENSURE_BUILDING;
k += 5;
goto step_18;
}
step_14:
/* Step 14. */
if (k > length - 3)
goto step_18;
/* Step 15-17. */
if (Unhex2(chars.begin() + k + 1, &c)) {
ENSURE_BUILDING;
k += 2;
}
step_18:
if (building && !sb.append(c))
return false;
/* Step 19. */
k += 1;
}
return true;
#undef ENSURE_BUILDING
}
/* ES5 B.2.2 */
static bool
str_unescape(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
/* Step 1. */
RootedLinearString str(cx, ArgToRootedString(cx, args, 0));
if (!str)
return false;
/* Step 3. */
StringBuffer sb(cx);
if (str->hasTwoByteChars() && !sb.ensureTwoByteChars())
return false;
if (str->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
if (!Unescape(sb, str->latin1Range(nogc)))
return false;
} else {
AutoCheckCannotGC nogc;
if (!Unescape(sb, str->twoByteRange(nogc)))
return false;
}
JSLinearString* result;
if (!sb.empty()) {
result = sb.finishString();
if (!result)
return false;
} else {
result = str;
}
args.rval().setString(result);
return true;
}
#if JS_HAS_UNEVAL
static bool
str_uneval(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSString* str = ValueToSource(cx, args.get(0));
if (!str)
return false;
args.rval().setString(str);
return true;
}
#endif
static const JSFunctionSpec string_functions[] = {
JS_FN(js_escape_str, str_escape, 1, JSPROP_RESOLVING),
JS_FN(js_unescape_str, str_unescape, 1, JSPROP_RESOLVING),
#if JS_HAS_UNEVAL
JS_FN(js_uneval_str, str_uneval, 1, JSPROP_RESOLVING),
#endif
JS_FN(js_decodeURI_str, str_decodeURI, 1, JSPROP_RESOLVING),
JS_FN(js_encodeURI_str, str_encodeURI, 1, JSPROP_RESOLVING),
JS_FN(js_decodeURIComponent_str, str_decodeURI_Component, 1, JSPROP_RESOLVING),
JS_FN(js_encodeURIComponent_str, str_encodeURI_Component, 1, JSPROP_RESOLVING),
JS_FS_END
};
static const unsigned STRING_ELEMENT_ATTRS = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT;
static bool
str_enumerate(JSContext* cx, HandleObject obj)
{
RootedString str(cx, obj->as<StringObject>().unbox());
RootedValue value(cx);
for (size_t i = 0, length = str->length(); i < length; i++) {
JSString* str1 = NewDependentString(cx, str, i, 1);
if (!str1)
return false;
value.setString(str1);
if (!DefineElement(cx, obj, i, value, nullptr, nullptr,
STRING_ELEMENT_ATTRS | JSPROP_RESOLVING))
{
return false;
}
}
return true;
}
static bool
str_mayResolve(const JSAtomState&, jsid id, JSObject*)
{
// str_resolve ignores non-integer ids.
return JSID_IS_INT(id);
}
static bool
str_resolve(JSContext* cx, HandleObject obj, HandleId id, bool* resolvedp)
{
if (!JSID_IS_INT(id))
return true;
RootedString str(cx, obj->as<StringObject>().unbox());
int32_t slot = JSID_TO_INT(id);
if ((size_t)slot < str->length()) {
JSString* str1 = cx->staticStrings().getUnitStringForElement(cx, str, size_t(slot));
if (!str1)
return false;
RootedValue value(cx, StringValue(str1));
if (!DefineElement(cx, obj, uint32_t(slot), value, nullptr, nullptr,
STRING_ELEMENT_ATTRS | JSPROP_RESOLVING))
{
return false;
}
*resolvedp = true;
}
return true;
}
static const ClassOps StringObjectClassOps = {
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* getProperty */
nullptr, /* setProperty */
str_enumerate,
str_resolve,
str_mayResolve
};
const Class StringObject::class_ = {
js_String_str,
JSCLASS_HAS_RESERVED_SLOTS(StringObject::RESERVED_SLOTS) |
JSCLASS_HAS_CACHED_PROTO(JSProto_String),
&StringObjectClassOps
};
/*
* Perform the initial |RequireObjectCoercible(thisv)| and |ToString(thisv)|
* from nearly all String.prototype.* functions.
*/
static MOZ_ALWAYS_INLINE JSString*
ToStringForStringFunction(JSContext* cx, HandleValue thisv)
{
JS_CHECK_RECURSION(cx, return nullptr);
if (thisv.isString())
return thisv.toString();
if (thisv.isObject()) {
RootedObject obj(cx, &thisv.toObject());
if (obj->is<StringObject>()) {
StringObject* nobj = &obj->as<StringObject>();
// We have to make sure that the ToPrimitive call from ToString
// would be unobservable.
if (HasNoToPrimitiveMethodPure(nobj, cx) &&
HasNativeMethodPure(nobj, cx->names().toString, str_toString, cx))
{
return nobj->unbox();
}
}
} else if (thisv.isNullOrUndefined()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO,
thisv.isNull() ? "null" : "undefined", "object");
return nullptr;
}
return ToStringSlow<CanGC>(cx, thisv);
}
MOZ_ALWAYS_INLINE bool
IsString(HandleValue v)
{
return v.isString() || (v.isObject() && v.toObject().is<StringObject>());
}
#if JS_HAS_TOSOURCE
MOZ_ALWAYS_INLINE bool
str_toSource_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsString(args.thisv()));
Rooted<JSString*> str(cx, ToString<CanGC>(cx, args.thisv()));
if (!str)
return false;
str = QuoteString(cx, str, '"');
if (!str)
return false;
StringBuffer sb(cx);
if (!sb.append("(new String(") || !sb.append(str) || !sb.append("))"))
return false;
str = sb.finishString();
if (!str)
return false;
args.rval().setString(str);
return true;
}
static bool
str_toSource(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsString, str_toSource_impl>(cx, args);
}
#endif /* JS_HAS_TOSOURCE */
MOZ_ALWAYS_INLINE bool
str_toString_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsString(args.thisv()));
args.rval().setString(args.thisv().isString()
? args.thisv().toString()
: args.thisv().toObject().as<StringObject>().unbox());
return true;
}
bool
js::str_toString(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return CallNonGenericMethod<IsString, str_toString_impl>(cx, args);
}
/*
* Java-like string native methods.
*/
JSString*
js::SubstringKernel(JSContext* cx, HandleString str, int32_t beginInt, int32_t lengthInt)
{
MOZ_ASSERT(0 <= beginInt);
MOZ_ASSERT(0 <= lengthInt);
MOZ_ASSERT(uint32_t(beginInt) <= str->length());
MOZ_ASSERT(uint32_t(lengthInt) <= str->length() - beginInt);
uint32_t begin = beginInt;
uint32_t len = lengthInt;
/*
* Optimization for one level deep ropes.
* This is common for the following pattern:
*
* while() {
* text = text.substr(0, x) + "bla" + text.substr(x)
* test.charCodeAt(x + 1)
* }
*/
if (str->isRope()) {
JSRope* rope = &str->asRope();
/* Substring is totally in leftChild of rope. */
if (begin + len <= rope->leftChild()->length())
return NewDependentString(cx, rope->leftChild(), begin, len);
/* Substring is totally in rightChild of rope. */
if (begin >= rope->leftChild()->length()) {
begin -= rope->leftChild()->length();
return NewDependentString(cx, rope->rightChild(), begin, len);
}
/*
* Requested substring is partly in the left and partly in right child.
* Create a rope of substrings for both childs.
*/
MOZ_ASSERT(begin < rope->leftChild()->length() &&
begin + len > rope->leftChild()->length());
size_t lhsLength = rope->leftChild()->length() - begin;
size_t rhsLength = begin + len - rope->leftChild()->length();
Rooted<JSRope*> ropeRoot(cx, rope);
RootedString lhs(cx, NewDependentString(cx, ropeRoot->leftChild(), begin, lhsLength));
if (!lhs)
return nullptr;
RootedString rhs(cx, NewDependentString(cx, ropeRoot->rightChild(), 0, rhsLength));
if (!rhs)
return nullptr;
return JSRope::new_<CanGC>(cx, lhs, rhs, len);
}
return NewDependentString(cx, str, begin, len);
}
template <typename CharT>
static auto
ReallocChars(JSContext* cx, UniquePtr<CharT[], JS::FreePolicy> chars, size_t oldLength,
size_t newLength)
-> decltype(chars)
{
using AnyCharPtr = decltype(chars);
CharT* oldChars = chars.release();
CharT* newChars = cx->pod_realloc<CharT>(oldChars, oldLength, newLength);
if (!newChars) {
js_free(oldChars);
return AnyCharPtr();
}
return AnyCharPtr(newChars);
}
/**
* U+03A3 GREEK CAPITAL LETTER SIGMA has two different lower case mappings
* depending on its context:
* When it's preceded by a cased character and not followed by another cased
* character, its lower case form is U+03C2 GREEK SMALL LETTER FINAL SIGMA.
* Otherwise its lower case mapping is U+03C3 GREEK SMALL LETTER SIGMA.
*
* Unicode 9.0, §3.13 Default Case Algorithms
*/
static char16_t
Final_Sigma(const char16_t* chars, size_t length, size_t index)
{
MOZ_ASSERT(index < length);
MOZ_ASSERT(chars[index] == unicode::GREEK_CAPITAL_LETTER_SIGMA);
MOZ_ASSERT(unicode::ToLowerCase(unicode::GREEK_CAPITAL_LETTER_SIGMA) ==
unicode::GREEK_SMALL_LETTER_SIGMA);
// Tell the analysis the BinaryProperty.contains function pointer called by
// u_hasBinaryProperty cannot GC.
JS::AutoSuppressGCAnalysis nogc;
bool precededByCased = false;
for (size_t i = index; i > 0; ) {
char16_t c = chars[--i];
uint32_t codePoint = c;
if (unicode::IsTrailSurrogate(c) && i > 0) {
char16_t lead = chars[i - 1];
if (unicode::IsLeadSurrogate(lead)) {
codePoint = unicode::UTF16Decode(lead, c);
i--;
}
}
// Ignore any characters with the property Case_Ignorable.
// NB: We need to skip over all Case_Ignorable characters, even when
// they also have the Cased binary property.
if (u_hasBinaryProperty(codePoint, UCHAR_CASE_IGNORABLE))
continue;
precededByCased = u_hasBinaryProperty(codePoint, UCHAR_CASED);
break;
}
if (!precededByCased)
return unicode::GREEK_SMALL_LETTER_SIGMA;
bool followedByCased = false;
for (size_t i = index + 1; i < length; ) {
char16_t c = chars[i++];
uint32_t codePoint = c;
if (unicode::IsLeadSurrogate(c) && i < length) {
char16_t trail = chars[i];
if (unicode::IsTrailSurrogate(trail)) {
codePoint = unicode::UTF16Decode(c, trail);
i++;
}
}
// Ignore any characters with the property Case_Ignorable.
// NB: We need to skip over all Case_Ignorable characters, even when
// they also have the Cased binary property.
if (u_hasBinaryProperty(codePoint, UCHAR_CASE_IGNORABLE))
continue;
followedByCased = u_hasBinaryProperty(codePoint, UCHAR_CASED);
break;
}
if (!followedByCased)
return unicode::GREEK_SMALL_LETTER_FINAL_SIGMA;
return unicode::GREEK_SMALL_LETTER_SIGMA;
}
static Latin1Char
Final_Sigma(const Latin1Char* chars, size_t length, size_t index)
{
MOZ_ASSERT_UNREACHABLE("U+03A3 is not a Latin-1 character");
return 0;
}
// If |srcLength == destLength| is true, the destination buffer was allocated
// with the same size as the source buffer. When we append characters which
// have special casing mappings, we test |srcLength == destLength| to decide
// if we need to back out and reallocate a sufficiently large destination
// buffer. Otherwise the destination buffer was allocated with the correct
// size to hold all lower case mapped characters, i.e.
// |destLength == ToLowerCaseLength(srcChars, 0, srcLength)| is true.
template <typename CharT>
static size_t
ToLowerCaseImpl(CharT* destChars, const CharT* srcChars, size_t startIndex, size_t srcLength,
size_t destLength)
{
MOZ_ASSERT(startIndex < srcLength);
MOZ_ASSERT(srcLength <= destLength);
MOZ_ASSERT_IF((IsSame<CharT, Latin1Char>::value), srcLength == destLength);
size_t j = startIndex;
for (size_t i = startIndex; i < srcLength; i++) {
char16_t c = srcChars[i];
if (!IsSame<CharT, Latin1Char>::value) {
if (unicode::IsLeadSurrogate(c) && i + 1 < srcLength) {
char16_t trail = srcChars[i + 1];
if (unicode::IsTrailSurrogate(trail)) {
trail = unicode::ToLowerCaseNonBMPTrail(c, trail);
destChars[j++] = c;
destChars[j++] = trail;
i++;
continue;
}
}
// Special case: U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// lowercases to <U+0069 U+0307>.
if (c == unicode::LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
// Return if the output buffer is too small.
if (srcLength == destLength)
return i;
destChars[j++] = CharT('i');
destChars[j++] = CharT(unicode::COMBINING_DOT_ABOVE);
continue;
}
// Special case: U+03A3 GREEK CAPITAL LETTER SIGMA lowercases to
// one of two codepoints depending on context.
if (c == unicode::GREEK_CAPITAL_LETTER_SIGMA) {
destChars[j++] = Final_Sigma(srcChars, srcLength, i);
continue;
}
}
c = unicode::ToLowerCase(c);
MOZ_ASSERT_IF((IsSame<CharT, Latin1Char>::value), c <= JSString::MAX_LATIN1_CHAR);
destChars[j++] = c;
}
MOZ_ASSERT(j == destLength);
destChars[destLength] = '\0';
return srcLength;
}
static size_t
ToLowerCaseLength(const char16_t* chars, size_t startIndex, size_t length)
{
size_t lowerLength = length;
for (size_t i = startIndex; i < length; i++) {
char16_t c = chars[i];
// U+0130 is lowercased to the two-element sequence <U+0069 U+0307>.
if (c == unicode::LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
lowerLength += 1;
}
return lowerLength;
}
static size_t
ToLowerCaseLength(const Latin1Char* chars, size_t startIndex, size_t length)
{
MOZ_ASSERT_UNREACHABLE("never called for Latin-1 strings");
return 0;
}
template <typename CharT>
static JSString*
ToLowerCase(JSContext* cx, JSLinearString* str)
{
// Unlike toUpperCase, toLowerCase has the nice invariant that if the
// input is a Latin-1 string, the output is also a Latin-1 string.
using AnyCharPtr = UniquePtr<CharT[], JS::FreePolicy>;
AnyCharPtr newChars;
const size_t length = str->length();
size_t resultLength;
{
AutoCheckCannotGC nogc;
const CharT* chars = str->chars<CharT>(nogc);
// We don't need extra special casing checks in the loop below,
// because U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE and U+03A3
// GREEK CAPITAL LETTER SIGMA already have simple lower case mappings.
MOZ_ASSERT(unicode::CanLowerCase(unicode::LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE),
"U+0130 has a simple lower case mapping");
MOZ_ASSERT(unicode::CanLowerCase(unicode::GREEK_CAPITAL_LETTER_SIGMA),
"U+03A3 has a simple lower case mapping");
// Look for the first character that changes when lowercased.
size_t i = 0;
for (; i < length; i++) {
char16_t c = chars[i];
if (!IsSame<CharT, Latin1Char>::value) {
if (unicode::IsLeadSurrogate(c) && i + 1 < length) {
char16_t trail = chars[i + 1];
if (unicode::IsTrailSurrogate(trail)) {
if (unicode::CanLowerCaseNonBMP(c, trail))
break;
i++;
continue;
}
}
}
if (unicode::CanLowerCase(c))
break;
}
// If no character needs to change, return the input string.
if (i == length)
return str;
resultLength = length;
newChars = cx->make_pod_array<CharT>(resultLength + 1);
if (!newChars)
return nullptr;
PodCopy(newChars.get(), chars, i);
size_t readChars = ToLowerCaseImpl(newChars.get(), chars, i, length, resultLength);
if (readChars < length) {
MOZ_ASSERT((!IsSame<CharT, Latin1Char>::value),
"Latin-1 strings don't have special lower case mappings");
resultLength = ToLowerCaseLength(chars, readChars, length);
AnyCharPtr buf = ReallocChars(cx, Move(newChars), length + 1, resultLength + 1);
if (!buf)
return nullptr;
newChars = Move(buf);
MOZ_ALWAYS_TRUE(length ==
ToLowerCaseImpl(newChars.get(), chars, readChars, length, resultLength));
}
}
JSString* res = NewStringDontDeflate<CanGC>(cx, newChars.get(), resultLength);
if (!res)
return nullptr;
mozilla::Unused << newChars.release();
return res;
}
JSString*
js::StringToLowerCase(JSContext* cx, HandleLinearString string)
{
if (string->hasLatin1Chars())
return ToLowerCase<Latin1Char>(cx, string);
return ToLowerCase<char16_t>(cx, string);
}
bool
js::str_toLowerCase(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
RootedLinearString linear(cx, str->ensureLinear(cx));
if (!linear)
return false;
JSString* result = StringToLowerCase(cx, linear);
if (!result)
return false;
args.rval().setString(result);
return true;
}
static const char*
CaseMappingLocale(JSContext* cx, JSString* str)
{
JSLinearString* locale = str->ensureLinear(cx);
if (!locale)
return nullptr;
MOZ_ASSERT(locale->length() >= 2, "locale is a valid language tag");
// Lithuanian, Turkish, and Azeri have language dependent case mappings.
static const char languagesWithSpecialCasing[][3] = { "lt", "tr", "az" };
// All strings in |languagesWithSpecialCasing| are of length two, so we
// only need to compare the first two characters to find a matching locale.
// ES2017 Intl, §9.2.2 BestAvailableLocale
if (locale->length() == 2 || locale->latin1OrTwoByteChar(2) == '-') {
for (const auto& language : languagesWithSpecialCasing) {
if (locale->latin1OrTwoByteChar(0) == language[0] &&
locale->latin1OrTwoByteChar(1) == language[1])
{
return language;
}
}
}
return ""; // ICU root locale
}
bool
js::intl_toLocaleLowerCase(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(args[0].isString());
MOZ_ASSERT(args[1].isString());
RootedLinearString linear(cx, args[0].toString()->ensureLinear(cx));
if (!linear)
return false;
const char* locale = CaseMappingLocale(cx, args[1].toString());
if (!locale)
return false;
// Call String.prototype.toLowerCase() for language independent casing.
if (intl::StringsAreEqual(locale, "")) {
JSString* str = StringToLowerCase(cx, linear);
if (!str)
return false;
args.rval().setString(str);
return true;
}
AutoStableStringChars inputChars(cx);
if (!inputChars.initTwoByte(cx, linear))
return false;
mozilla::Range<const char16_t> input = inputChars.twoByteRange();
// Maximum case mapping length is three characters.
static_assert(JSString::MAX_LENGTH < INT32_MAX / 3,
"Case conversion doesn't overflow int32_t indices");
JSString* str = intl::CallICU(cx, [&input, locale](UChar* chars, int32_t size, UErrorCode* status) {
return u_strToLower(chars, size, Char16ToUChar(input.begin().get()), input.length(),
locale, status);
});
if (!str)
return false;
args.rval().setString(str);
return true;
}
static inline bool
CanUpperCaseSpecialCasing(Latin1Char charCode)
{
// Handle U+00DF LATIN SMALL LETTER SHARP S inline, all other Latin-1
// characters don't have special casing rules.
MOZ_ASSERT_IF(charCode != unicode::LATIN_SMALL_LETTER_SHARP_S,
!unicode::CanUpperCaseSpecialCasing(charCode));
return charCode == unicode::LATIN_SMALL_LETTER_SHARP_S;
}
static inline bool
CanUpperCaseSpecialCasing(char16_t charCode)
{
return unicode::CanUpperCaseSpecialCasing(charCode);
}
static inline size_t
LengthUpperCaseSpecialCasing(Latin1Char charCode)
{
// U+00DF LATIN SMALL LETTER SHARP S is uppercased to two 'S'.
MOZ_ASSERT(charCode == unicode::LATIN_SMALL_LETTER_SHARP_S);
return 2;
}
static inline size_t
LengthUpperCaseSpecialCasing(char16_t charCode)
{
MOZ_ASSERT(CanUpperCaseSpecialCasing(charCode));
return unicode::LengthUpperCaseSpecialCasing(charCode);
}
static inline void
AppendUpperCaseSpecialCasing(char16_t charCode, Latin1Char* elements, size_t* index)
{
// U+00DF LATIN SMALL LETTER SHARP S is uppercased to two 'S'.
MOZ_ASSERT(charCode == unicode::LATIN_SMALL_LETTER_SHARP_S);
static_assert('S' <= JSString::MAX_LATIN1_CHAR, "'S' is a Latin-1 character");
elements[(*index)++] = 'S';
elements[(*index)++] = 'S';
}
static inline void
AppendUpperCaseSpecialCasing(char16_t charCode, char16_t* elements, size_t* index)
{
unicode::AppendUpperCaseSpecialCasing(charCode, elements, index);
}
// See ToLowerCaseImpl for an explanation of the parameters.
template <typename DestChar, typename SrcChar>
static size_t
ToUpperCaseImpl(DestChar* destChars, const SrcChar* srcChars, size_t startIndex, size_t srcLength,
size_t destLength)
{
static_assert(IsSame<SrcChar, Latin1Char>::value || !IsSame<DestChar, Latin1Char>::value,
"cannot write non-Latin-1 characters into Latin-1 string");
MOZ_ASSERT(startIndex < srcLength);
MOZ_ASSERT(srcLength <= destLength);
size_t j = startIndex;
for (size_t i = startIndex; i < srcLength; i++) {
char16_t c = srcChars[i];
if (!IsSame<DestChar, Latin1Char>::value) {
if (unicode::IsLeadSurrogate(c) && i + 1 < srcLength) {
char16_t trail = srcChars[i + 1];
if (unicode::IsTrailSurrogate(trail)) {
trail = unicode::ToUpperCaseNonBMPTrail(c, trail);
destChars[j++] = c;
destChars[j++] = trail;
i++;
continue;
}
}
}
if (MOZ_UNLIKELY(c > 0x7f && CanUpperCaseSpecialCasing(static_cast<SrcChar>(c)))) {
// Return if the output buffer is too small.
if (srcLength == destLength)
return i;
AppendUpperCaseSpecialCasing(c, destChars, &j);
continue;
}
c = unicode::ToUpperCase(c);
MOZ_ASSERT_IF((IsSame<DestChar, Latin1Char>::value), c <= JSString::MAX_LATIN1_CHAR);
destChars[j++] = c;
}
MOZ_ASSERT(j == destLength);
destChars[destLength] = '\0';
return srcLength;
}
// Explicit instantiation so we don't hit the static_assert from above.
static bool
ToUpperCaseImpl(Latin1Char* destChars, const char16_t* srcChars, size_t startIndex,
size_t srcLength, size_t destLength)
{
MOZ_ASSERT_UNREACHABLE("cannot write non-Latin-1 characters into Latin-1 string");
return false;
}
template <typename CharT>
static size_t
ToUpperCaseLength(const CharT* chars, size_t startIndex, size_t length)
{
size_t upperLength = length;
for (size_t i = startIndex; i < length; i++) {
char16_t c = chars[i];
if (c > 0x7f && CanUpperCaseSpecialCasing(static_cast<CharT>(c)))
upperLength += LengthUpperCaseSpecialCasing(static_cast<CharT>(c)) - 1;
}
return upperLength;
}
template <typename DestChar, typename SrcChar>
static inline void
CopyChars(DestChar* destChars, const SrcChar* srcChars, size_t length)
{
static_assert(!IsSame<DestChar, SrcChar>::value, "PodCopy is used for the same type case");
for (size_t i = 0; i < length; i++)
destChars[i] = srcChars[i];
}
template <typename CharT>
static inline void
CopyChars(CharT* destChars, const CharT* srcChars, size_t length)
{
PodCopy(destChars, srcChars, length);
}
template <typename DestChar, typename SrcChar>
static inline UniquePtr<DestChar[], JS::FreePolicy>
ToUpperCase(JSContext* cx, const SrcChar* chars, size_t startIndex, size_t length,
size_t* resultLength)
{
MOZ_ASSERT(startIndex < length);
using DestCharPtr = UniquePtr<DestChar[], JS::FreePolicy>;
*resultLength = length;
DestCharPtr buf = cx->make_pod_array<DestChar>(length + 1);
if (!buf)
return buf;
CopyChars(buf.get(), chars, startIndex);
size_t readChars = ToUpperCaseImpl(buf.get(), chars, startIndex, length, length);
if (readChars < length) {
size_t actualLength = ToUpperCaseLength(chars, readChars, length);
*resultLength = actualLength;
DestCharPtr buf2 = ReallocChars(cx, Move(buf), length + 1, actualLength + 1);
if (!buf2)
return buf2;
buf = Move(buf2);
MOZ_ALWAYS_TRUE(length ==
ToUpperCaseImpl(buf.get(), chars, readChars, length, actualLength));
}
return buf;
}
template <typename CharT>
static JSString*
ToUpperCase(JSContext* cx, JSLinearString* str)
{
using Latin1CharPtr = UniquePtr<Latin1Char[], JS::FreePolicy>;
using TwoByteCharPtr = UniquePtr<char16_t[], JS::FreePolicy>;
mozilla::MaybeOneOf<Latin1CharPtr, TwoByteCharPtr> newChars;
const size_t length = str->length();
size_t resultLength;
{
AutoCheckCannotGC nogc;
const CharT* chars = str->chars<CharT>(nogc);
// Look for the first character that changes when uppercased.
size_t i = 0;
for (; i < length; i++) {
char16_t c = chars[i];
if (!IsSame<CharT, Latin1Char>::value) {
if (unicode::IsLeadSurrogate(c) && i + 1 < length) {
char16_t trail = chars[i + 1];
if (unicode::IsTrailSurrogate(trail)) {
if (unicode::CanUpperCaseNonBMP(c, trail))
break;
i++;
continue;
}
}
}
if (unicode::CanUpperCase(c))
break;
if (MOZ_UNLIKELY(c > 0x7f && CanUpperCaseSpecialCasing(static_cast<CharT>(c))))
break;
}
// If no character needs to change, return the input string.
if (i == length)
return str;
// The string changes when uppercased, so we must create a new string.
// Can it be Latin-1?
//
// If the original string is Latin-1, it can -- unless the string
// contains U+00B5 MICRO SIGN or U+00FF SMALL LETTER Y WITH DIAERESIS,
// the only Latin-1 codepoints that don't uppercase within Latin-1.
// Search for those codepoints to decide whether the new string can be
// Latin-1.
// If the original string is a two-byte string, its uppercase form is
// so rarely Latin-1 that we don't even consider creating a new
// Latin-1 string.
bool resultIsLatin1;
if (IsSame<CharT, Latin1Char>::value) {
resultIsLatin1 = true;
for (size_t j = i; j < length; j++) {
Latin1Char c = chars[j];
if (c == unicode::MICRO_SIGN ||
c == unicode::LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)
{
MOZ_ASSERT(unicode::ToUpperCase(c) > JSString::MAX_LATIN1_CHAR);
resultIsLatin1 = false;
break;
} else {
MOZ_ASSERT(unicode::ToUpperCase(c) <= JSString::MAX_LATIN1_CHAR);
}
}
} else {
resultIsLatin1 = false;
}
if (resultIsLatin1) {
Latin1CharPtr buf = ToUpperCase<Latin1Char>(cx, chars, i, length, &resultLength);
if (!buf)
return nullptr;
newChars.construct<Latin1CharPtr>(Move(buf));
} else {
TwoByteCharPtr buf = ToUpperCase<char16_t>(cx, chars, i, length, &resultLength);
if (!buf)
return nullptr;
newChars.construct<TwoByteCharPtr>(Move(buf));
}
}
JSString* res;
if (newChars.constructed<Latin1CharPtr>()) {
res = NewStringDontDeflate<CanGC>(cx, newChars.ref<Latin1CharPtr>().get(), resultLength);
if (!res)
return nullptr;
mozilla::Unused << newChars.ref<Latin1CharPtr>().release();
} else {
res = NewStringDontDeflate<CanGC>(cx, newChars.ref<TwoByteCharPtr>().get(), resultLength);
if (!res)
return nullptr;
mozilla::Unused << newChars.ref<TwoByteCharPtr>().release();
}
return res;
}
JSString*
js::StringToUpperCase(JSContext* cx, HandleLinearString string)
{
if (string->hasLatin1Chars())
return ToUpperCase<Latin1Char>(cx, string);
return ToUpperCase<char16_t>(cx, string);
}
bool
js::str_toUpperCase(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
RootedLinearString linear(cx, str->ensureLinear(cx));
if (!linear)
return false;
JSString* result = StringToUpperCase(cx, linear);
if (!result)
return false;
args.rval().setString(result);
return true;
}
bool
js::intl_toLocaleUpperCase(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(args[0].isString());
MOZ_ASSERT(args[1].isString());
RootedLinearString linear(cx, args[0].toString()->ensureLinear(cx));
if (!linear)
return false;
const char* locale = CaseMappingLocale(cx, args[1].toString());
if (!locale)
return false;
// Call String.prototype.toUpperCase() for language independent casing.
if (intl::StringsAreEqual(locale, "")) {
JSString* str = StringToUpperCase(cx, linear);
if (!str)
return false;
args.rval().setString(str);
return true;
}
AutoStableStringChars inputChars(cx);
if (!inputChars.initTwoByte(cx, linear))
return false;
mozilla::Range<const char16_t> input = inputChars.twoByteRange();
// Maximum case mapping length is three characters.
static_assert(JSString::MAX_LENGTH < INT32_MAX / 3,
"Case conversion doesn't overflow int32_t indices");
JSString* str = intl::CallICU(cx, [&input, locale](UChar* chars, int32_t size, UErrorCode* status) {
return u_strToUpper(chars, size, Char16ToUChar(input.begin().get()), input.length(),
locale, status);
});
if (!str)
return false;
args.rval().setString(str);
return true;
}
/* ES2017 21.1.3.12. */
bool
js::str_normalize(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1-2.
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
enum NormalizationForm {
NFC, NFD, NFKC, NFKD
};
NormalizationForm form;
if (!args.hasDefined(0)) {
// Step 3.
form = NFC;
} else {
// Step 4.
RootedLinearString formStr(cx, ArgToRootedString(cx, args, 0));
if (!formStr)
return false;
// Step 5.
if (EqualStrings(formStr, cx->names().NFC)) {
form = NFC;
} else if (EqualStrings(formStr, cx->names().NFD)) {
form = NFD;
} else if (EqualStrings(formStr, cx->names().NFKC)) {
form = NFKC;
} else if (EqualStrings(formStr, cx->names().NFKD)) {
form = NFKD;
} else {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_NORMALIZE_FORM);
return false;
}
}
JSLinearString* linear = str->ensureLinear(cx);
if (!linear)
return false;
// Latin-1 strings are already in Normalization Form C.
if (form == NFC && linear->hasLatin1Chars()) {
// Step 7.
args.rval().setString(str);
return true;
}
// Step 6.
AutoStableStringChars stableChars(cx);
if (!stableChars.initTwoByte(cx, linear))
return false;
mozilla::Range<const char16_t> srcChars = stableChars.twoByteRange();
// The unorm2_getXXXInstance() methods return a shared instance which must
// not be deleted.
UErrorCode status = U_ZERO_ERROR;
const UNormalizer2* normalizer;
if (form == NFC) {
normalizer = unorm2_getNFCInstance(&status);
} else if (form == NFD) {
normalizer = unorm2_getNFDInstance(&status);
} else if (form == NFKC) {
normalizer = unorm2_getNFKCInstance(&status);
} else {
MOZ_ASSERT(form == NFKD);
normalizer = unorm2_getNFKDInstance(&status);
}
if (U_FAILURE(status)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
return false;
}
int32_t spanLength = unorm2_spanQuickCheckYes(normalizer,
Char16ToUChar(srcChars.begin().get()),
srcChars.length(), &status);
if (U_FAILURE(status)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
return false;
}
MOZ_ASSERT(0 <= spanLength && size_t(spanLength) <= srcChars.length());
// Return if the input string is already normalized.
if (size_t(spanLength) == srcChars.length()) {
// Step 7.
args.rval().setString(str);
return true;
}
static const size_t INLINE_CAPACITY = 32;
Vector<char16_t, INLINE_CAPACITY> chars(cx);
if (!chars.resize(Max(INLINE_CAPACITY, srcChars.length())))
return false;
// Copy the already normalized prefix.
if (spanLength > 0)
PodCopy(chars.begin(), srcChars.begin().get(), size_t(spanLength));
mozilla::RangedPtr<const char16_t> remainingStart = srcChars.begin() + spanLength;
size_t remainingLength = srcChars.length() - size_t(spanLength);
int32_t size = unorm2_normalizeSecondAndAppend(normalizer, Char16ToUChar(chars.begin()),
spanLength, chars.length(),
Char16ToUChar(remainingStart.get()),
remainingLength, &status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
MOZ_ASSERT(size >= 0);
if (!chars.resize(size))
return false;
status = U_ZERO_ERROR;
#ifdef DEBUG
int32_t finalSize =
#endif
unorm2_normalizeSecondAndAppend(normalizer, Char16ToUChar(chars.begin()), spanLength,
chars.length(), Char16ToUChar(remainingStart.get()),
remainingLength, &status);
MOZ_ASSERT_IF(!U_FAILURE(status), size == finalSize);
}
if (U_FAILURE(status)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INTERNAL_INTL_ERROR);
return false;
}
MOZ_ASSERT(size >= 0);
JSString* ns = NewStringCopyN<CanGC>(cx, chars.begin(), size);
if (!ns)
return false;
// Step 7.
args.rval().setString(ns);
return true;
}
bool
js::str_charAt(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedString str(cx);
size_t i;
if (args.thisv().isString() && args.length() != 0 && args[0].isInt32()) {
str = args.thisv().toString();
i = size_t(args[0].toInt32());
if (i >= str->length())
goto out_of_range;
} else {
str = ToStringForStringFunction(cx, args.thisv());
if (!str)
return false;
double d = 0.0;
if (args.length() > 0 && !ToInteger(cx, args[0], &d))
return false;
if (d < 0 || str->length() <= d)
goto out_of_range;
i = size_t(d);
}
str = cx->staticStrings().getUnitStringForElement(cx, str, i);
if (!str)
return false;
args.rval().setString(str);
return true;
out_of_range:
args.rval().setString(cx->runtime()->emptyString);
return true;
}
bool
js::str_charCodeAt_impl(JSContext* cx, HandleString string, HandleValue index, MutableHandleValue res)
{
RootedString str(cx);
size_t i;
if (index.isInt32()) {
i = index.toInt32();
if (i >= string->length())
goto out_of_range;
} else {
double d = 0.0;
if (!ToInteger(cx, index, &d))
return false;
// check whether d is negative as size_t is unsigned
if (d < 0 || string->length() <= d )
goto out_of_range;
i = size_t(d);
}
char16_t c;
if (!string->getChar(cx, i , &c))
return false;
res.setInt32(c);
return true;
out_of_range:
res.setNaN();
return true;
}
bool
js::str_charCodeAt(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedString str(cx);
RootedValue index(cx);
if (args.thisv().isString()) {
str = args.thisv().toString();
} else {
str = ToStringForStringFunction(cx, args.thisv());
if (!str)
return false;
}
if (args.length() != 0)
index = args[0];
else
index.setInt32(0);
return js::str_charCodeAt_impl(cx, str, index, args.rval());
}
/*
* Boyer-Moore-Horspool superlinear search for pat:patlen in text:textlen.
* The patlen argument must be positive and no greater than sBMHPatLenMax.
*
* Return the index of pat in text, or -1 if not found.
*/
static const uint32_t sBMHCharSetSize = 256; /* ISO-Latin-1 */
static const uint32_t sBMHPatLenMax = 255; /* skip table element is uint8_t */
static const int sBMHBadPattern = -2; /* return value if pat is not ISO-Latin-1 */
template <typename TextChar, typename PatChar>
static int
BoyerMooreHorspool(const TextChar* text, uint32_t textLen, const PatChar* pat, uint32_t patLen)
{
MOZ_ASSERT(0 < patLen && patLen <= sBMHPatLenMax);
uint8_t skip[sBMHCharSetSize];
for (uint32_t i = 0; i < sBMHCharSetSize; i++)
skip[i] = uint8_t(patLen);
uint32_t patLast = patLen - 1;
for (uint32_t i = 0; i < patLast; i++) {
char16_t c = pat[i];
if (c >= sBMHCharSetSize)
return sBMHBadPattern;
skip[c] = uint8_t(patLast - i);
}
for (uint32_t k = patLast; k < textLen; ) {
for (uint32_t i = k, j = patLast; ; i--, j--) {
if (text[i] != pat[j])
break;
if (j == 0)
return static_cast<int>(i); /* safe: max string size */
}
char16_t c = text[k];
k += (c >= sBMHCharSetSize) ? patLen : skip[c];
}
return -1;
}
template <typename TextChar, typename PatChar>
struct MemCmp {
typedef uint32_t Extent;
static MOZ_ALWAYS_INLINE Extent computeExtent(const PatChar*, uint32_t patLen) {
return (patLen - 1) * sizeof(PatChar);
}
static MOZ_ALWAYS_INLINE bool match(const PatChar* p, const TextChar* t, Extent extent) {
MOZ_ASSERT(sizeof(TextChar) == sizeof(PatChar));
return memcmp(p, t, extent) == 0;
}
};
template <typename TextChar, typename PatChar>
struct ManualCmp {
typedef const PatChar* Extent;
static MOZ_ALWAYS_INLINE Extent computeExtent(const PatChar* pat, uint32_t patLen) {
return pat + patLen;
}
static MOZ_ALWAYS_INLINE bool match(const PatChar* p, const TextChar* t, Extent extent) {
for (; p != extent; ++p, ++t) {
if (*p != *t)
return false;
}
return true;
}
};
template <typename TextChar, typename PatChar>
static const TextChar*
FirstCharMatcherUnrolled(const TextChar* text, uint32_t n, const PatChar pat)
{
const TextChar* textend = text + n;
const TextChar* t = text;
switch ((textend - t) & 7) {
case 0: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 7: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 6: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 5: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 4: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 3: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 2: if (*t++ == pat) return t - 1; MOZ_FALLTHROUGH;
case 1: if (*t++ == pat) return t - 1;
}
while (textend != t) {
if (t[0] == pat) return t;
if (t[1] == pat) return t + 1;
if (t[2] == pat) return t + 2;
if (t[3] == pat) return t + 3;
if (t[4] == pat) return t + 4;
if (t[5] == pat) return t + 5;
if (t[6] == pat) return t + 6;
if (t[7] == pat) return t + 7;
t += 8;
}
return nullptr;
}
static const char*
FirstCharMatcher8bit(const char* text, uint32_t n, const char pat)
{
#if defined(__clang__)
return FirstCharMatcherUnrolled<char, char>(text, n, pat);
#else
return reinterpret_cast<const char*>(memchr(text, pat, n));
#endif
}
static const char16_t*
FirstCharMatcher16bit(const char16_t* text, uint32_t n, const char16_t pat)
{
#if defined(XP_DARWIN) || defined(XP_WIN)
/*
* Performance of memchr is horrible in OSX. Windows is better,
* but it is still better to use UnrolledMatcher.
*/
return FirstCharMatcherUnrolled<char16_t, char16_t>(text, n, pat);
#else
/*
* For linux the best performance is obtained by slightly hacking memchr.
* memchr works only on 8bit char but char16_t is 16bit. So we treat char16_t
* in blocks of 8bit and use memchr.
*/
const char* text8 = (const char*) text;
const char* pat8 = reinterpret_cast<const char*>(&pat);
MOZ_ASSERT(n < UINT32_MAX/2);
n *= 2;
uint32_t i = 0;
while (i < n) {
/* Find the first 8 bits of 16bit character in text. */
const char* pos8 = FirstCharMatcher8bit(text8 + i, n - i, pat8[0]);
if (pos8 == nullptr)
return nullptr;
i = static_cast<uint32_t>(pos8 - text8);
/* Incorrect match if it matches the last 8 bits of 16bit char. */
if (i % 2 != 0) {
i++;
continue;
}
/* Test if last 8 bits match last 8 bits of 16bit char. */
if (pat8[1] == text8[i + 1])
return (text + (i/2));
i += 2;
}
return nullptr;
#endif
}
template <class InnerMatch, typename TextChar, typename PatChar>
static int
Matcher(const TextChar* text, uint32_t textlen, const PatChar* pat, uint32_t patlen)
{
const typename InnerMatch::Extent extent = InnerMatch::computeExtent(pat, patlen);
uint32_t i = 0;
uint32_t n = textlen - patlen + 1;
while (i < n) {
const TextChar* pos;
if (sizeof(TextChar) == 2 && sizeof(PatChar) == 2)
pos = (TextChar*) FirstCharMatcher16bit((char16_t*)text + i, n - i, pat[0]);
else if (sizeof(TextChar) == 1 && sizeof(PatChar) == 1)
pos = (TextChar*) FirstCharMatcher8bit((char*) text + i, n - i, pat[0]);
else
pos = (TextChar*) FirstCharMatcherUnrolled<TextChar, PatChar>(text + i, n - i, pat[0]);
if (pos == nullptr)
return -1;
i = static_cast<uint32_t>(pos - text);
if (InnerMatch::match(pat + 1, text + i + 1, extent))
return i;
i += 1;
}
return -1;
}
template <typename TextChar, typename PatChar>
static MOZ_ALWAYS_INLINE int
StringMatch(const TextChar* text, uint32_t textLen, const PatChar* pat, uint32_t patLen)
{
if (patLen == 0)
return 0;
if (textLen < patLen)
return -1;
#if defined(__i386__) || defined(_M_IX86) || defined(__i386)
/*
* Given enough registers, the unrolled loop below is faster than the
* following loop. 32-bit x86 does not have enough registers.
*/
if (patLen == 1) {
const PatChar p0 = *pat;
const TextChar* end = text + textLen;
for (const TextChar* c = text; c != end; ++c) {
if (*c == p0)
return c - text;
}
return -1;
}
#endif
/*
* If the text or pattern string is short, BMH will be more expensive than
* the basic linear scan due to initialization cost and a more complex loop
* body. While the correct threshold is input-dependent, we can make a few
* conservative observations:
* - When |textLen| is "big enough", the initialization time will be
* proportionally small, so the worst-case slowdown is minimized.
* - When |patLen| is "too small", even the best case for BMH will be
* slower than a simple scan for large |textLen| due to the more complex
* loop body of BMH.
* From this, the values for "big enough" and "too small" are determined
* empirically. See bug 526348.
*/
if (textLen >= 512 && patLen >= 11 && patLen <= sBMHPatLenMax) {
int index = BoyerMooreHorspool(text, textLen, pat, patLen);
if (index != sBMHBadPattern)
return index;
}
/*
* For big patterns with large potential overlap we want the SIMD-optimized
* speed of memcmp. For small patterns, a simple loop is faster. We also can't
* use memcmp if one of the strings is TwoByte and the other is Latin-1.
*
* FIXME: Linux memcmp performance is sad and the manual loop is faster.
*/
return
#if !defined(__linux__)
(patLen > 128 && IsSame<TextChar, PatChar>::value)
? Matcher<MemCmp<TextChar, PatChar>, TextChar, PatChar>(text, textLen, pat, patLen)
:
#endif
Matcher<ManualCmp<TextChar, PatChar>, TextChar, PatChar>(text, textLen, pat, patLen);
}
static int32_t
StringMatch(JSLinearString* text, JSLinearString* pat, uint32_t start = 0)
{
MOZ_ASSERT(start <= text->length());
uint32_t textLen = text->length() - start;
uint32_t patLen = pat->length();
int match;
AutoCheckCannotGC nogc;
if (text->hasLatin1Chars()) {
const Latin1Char* textChars = text->latin1Chars(nogc) + start;
if (pat->hasLatin1Chars())
match = StringMatch(textChars, textLen, pat->latin1Chars(nogc), patLen);
else
match = StringMatch(textChars, textLen, pat->twoByteChars(nogc), patLen);
} else {
const char16_t* textChars = text->twoByteChars(nogc) + start;
if (pat->hasLatin1Chars())
match = StringMatch(textChars, textLen, pat->latin1Chars(nogc), patLen);
else
match = StringMatch(textChars, textLen, pat->twoByteChars(nogc), patLen);
}
return (match == -1) ? -1 : start + match;
}
static const size_t sRopeMatchThresholdRatioLog2 = 5;
bool
js::StringHasPattern(JSLinearString* text, const char16_t* pat, uint32_t patLen)
{
AutoCheckCannotGC nogc;
return text->hasLatin1Chars()
? StringMatch(text->latin1Chars(nogc), text->length(), pat, patLen) != -1
: StringMatch(text->twoByteChars(nogc), text->length(), pat, patLen) != -1;
}
int
js::StringFindPattern(JSLinearString* text, JSLinearString* pat, size_t start)
{
return StringMatch(text, pat, start);
}
// When an algorithm does not need a string represented as a single linear
// array of characters, this range utility may be used to traverse the string a
// sequence of linear arrays of characters. This avoids flattening ropes.
class StringSegmentRange
{
// If malloc() shows up in any profiles from this vector, we can add a new
// StackAllocPolicy which stashes a reusable freed-at-gc buffer in the cx.
Rooted<StringVector> stack;
RootedLinearString cur;
bool settle(JSString* str) {
while (str->isRope()) {
JSRope& rope = str->asRope();
if (!stack.append(rope.rightChild()))
return false;
str = rope.leftChild();
}
cur = &str->asLinear();
return true;
}
public:
explicit StringSegmentRange(JSContext* cx)
: stack(cx, StringVector(cx)), cur(cx)
{}
MOZ_MUST_USE bool init(JSString* str) {
MOZ_ASSERT(stack.empty());
return settle(str);
}
bool empty() const {
return cur == nullptr;
}
JSLinearString* front() const {
MOZ_ASSERT(!cur->isRope());
return cur;
}
MOZ_MUST_USE bool popFront() {
MOZ_ASSERT(!empty());
if (stack.empty()) {
cur = nullptr;
return true;
}
return settle(stack.popCopy());
}
};
typedef Vector<JSLinearString*, 16, SystemAllocPolicy> LinearStringVector;
template <typename TextChar, typename PatChar>
static int
RopeMatchImpl(const AutoCheckCannotGC& nogc, LinearStringVector& strings,
const PatChar* pat, size_t patLen)
{
/* Absolute offset from the beginning of the logical text string. */
int pos = 0;
for (JSLinearString** outerp = strings.begin(); outerp != strings.end(); ++outerp) {
/* Try to find a match within 'outer'. */
JSLinearString* outer = *outerp;
const TextChar* chars = outer->chars<TextChar>(nogc);
size_t len = outer->length();
int matchResult = StringMatch(chars, len, pat, patLen);
if (matchResult != -1) {
/* Matched! */
return pos + matchResult;
}
/* Try to find a match starting in 'outer' and running into other nodes. */
const TextChar* const text = chars + (patLen > len ? 0 : len - patLen + 1);
const TextChar* const textend = chars + len;
const PatChar p0 = *pat;
const PatChar* const p1 = pat + 1;
const PatChar* const patend = pat + patLen;
for (const TextChar* t = text; t != textend; ) {
if (*t++ != p0)
continue;
JSLinearString** innerp = outerp;
const TextChar* ttend = textend;
const TextChar* tt = t;
for (const PatChar* pp = p1; pp != patend; ++pp, ++tt) {
while (tt == ttend) {
if (++innerp == strings.end())
return -1;
JSLinearString* inner = *innerp;
tt = inner->chars<TextChar>(nogc);
ttend = tt + inner->length();
}
if (*pp != *tt)
goto break_continue;
}
/* Matched! */
return pos + (t - chars) - 1; /* -1 because of *t++ above */
break_continue:;
}
pos += len;
}
return -1;
}
/*
* RopeMatch takes the text to search and the pattern to search for in the text.
* RopeMatch returns false on OOM and otherwise returns the match index through
* the 'match' outparam (-1 for not found).
*/
static bool
RopeMatch(JSContext* cx, JSRope* text, JSLinearString* pat, int* match)
{
uint32_t patLen = pat->length();
if (patLen == 0) {
*match = 0;
return true;
}
if (text->length() < patLen) {
*match = -1;
return true;
}
/*
* List of leaf nodes in the rope. If we run out of memory when trying to
* append to this list, we can still fall back to StringMatch, so use the
* system allocator so we don't report OOM in that case.
*/
LinearStringVector strings;
/*
* We don't want to do rope matching if there is a poor node-to-char ratio,
* since this means spending a lot of time in the match loop below. We also
* need to build the list of leaf nodes. Do both here: iterate over the
* nodes so long as there are not too many.
*
* We also don't use rope matching if the rope contains both Latin-1 and
* TwoByte nodes, to simplify the match algorithm.
*/
{
size_t threshold = text->length() >> sRopeMatchThresholdRatioLog2;
StringSegmentRange r(cx);
if (!r.init(text))
return false;
bool textIsLatin1 = text->hasLatin1Chars();
while (!r.empty()) {
if (threshold-- == 0 ||
r.front()->hasLatin1Chars() != textIsLatin1 ||
!strings.append(r.front()))
{
JSLinearString* linear = text->ensureLinear(cx);
if (!linear)
return false;
*match = StringMatch(linear, pat);
return true;
}
if (!r.popFront())
return false;
}
}
AutoCheckCannotGC nogc;
if (text->hasLatin1Chars()) {
if (pat->hasLatin1Chars())
*match = RopeMatchImpl<Latin1Char>(nogc, strings, pat->latin1Chars(nogc), patLen);
else
*match = RopeMatchImpl<Latin1Char>(nogc, strings, pat->twoByteChars(nogc), patLen);
} else {
if (pat->hasLatin1Chars())
*match = RopeMatchImpl<char16_t>(nogc, strings, pat->latin1Chars(nogc), patLen);
else
*match = RopeMatchImpl<char16_t>(nogc, strings, pat->twoByteChars(nogc), patLen);
}
return true;
}
/* ES6 2015 ST 21.1.3.7 String.prototype.includes */
bool
js::str_includes(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1, 2, and 3
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
// Steps 4 and 5
bool isRegExp;
if (!IsRegExp(cx, args.get(0), &isRegExp))
return false;
// Step 6
if (isRegExp) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARG_TYPE,
"first", "", "Regular Expression");
return false;
}
// Steps 7 and 8
RootedLinearString searchStr(cx, ArgToRootedString(cx, args, 0));
if (!searchStr)
return false;
// Steps 9 and 10
uint32_t pos = 0;
if (args.hasDefined(1)) {
if (args[1].isInt32()) {
int i = args[1].toInt32();
pos = (i < 0) ? 0U : uint32_t(i);
} else {
double d;
if (!ToInteger(cx, args[1], &d))
return false;
pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
}
}
// Step 11
uint32_t textLen = str->length();
// Step 12
uint32_t start = Min(Max(pos, 0U), textLen);
// Steps 13 and 14
JSLinearString* text = str->ensureLinear(cx);
if (!text)
return false;
args.rval().setBoolean(StringMatch(text, searchStr, start) != -1);
return true;
}
/* ES6 draft <RC4 String.prototype.contains for compatibility */
bool
js::str_contains(JSContext* cx, unsigned argc, Value* vp)
{
return js::str_includes(cx, argc, vp);
}
/* ES6 20120927 draft 15.5.4.7. */
bool
js::str_indexOf(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1, 2, and 3
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
// Steps 4 and 5
RootedLinearString searchStr(cx, ArgToRootedString(cx, args, 0));
if (!searchStr)
return false;
// Steps 6 and 7
uint32_t pos = 0;
if (args.hasDefined(1)) {
if (args[1].isInt32()) {
int i = args[1].toInt32();
pos = (i < 0) ? 0U : uint32_t(i);
} else {
double d;
if (!ToInteger(cx, args[1], &d))
return false;
pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
}
}
// Step 8
uint32_t textLen = str->length();
// Step 9
uint32_t start = Min(Max(pos, 0U), textLen);
// Steps 10 and 11
JSLinearString* text = str->ensureLinear(cx);
if (!text)
return false;
args.rval().setInt32(StringMatch(text, searchStr, start));
return true;
}
template <typename TextChar, typename PatChar>
static int32_t
LastIndexOfImpl(const TextChar* text, size_t textLen, const PatChar* pat, size_t patLen,
size_t start)
{
MOZ_ASSERT(patLen > 0);
MOZ_ASSERT(patLen <= textLen);
MOZ_ASSERT(start <= textLen - patLen);
const PatChar p0 = *pat;
const PatChar* patNext = pat + 1;
const PatChar* patEnd = pat + patLen;
for (const TextChar* t = text + start; t >= text; --t) {
if (*t == p0) {
const TextChar* t1 = t + 1;
for (const PatChar* p1 = patNext; p1 < patEnd; ++p1, ++t1) {
if (*t1 != *p1)
goto break_continue;
}
return static_cast<int32_t>(t - text);
}
break_continue:;
}
return -1;
}
// ES2017 draft rev 6859bb9ccaea9c6ede81d71e5320e3833b92cb3e
// 21.1.3.9 String.prototype.lastIndexOf ( searchString [ , position ] )
bool
js::str_lastIndexOf(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1-2.
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
// Step 3.
RootedLinearString searchStr(cx, ArgToRootedString(cx, args, 0));
if (!searchStr)
return false;
// Step 6.
size_t len = str->length();
// Step 8.
size_t searchLen = searchStr->length();
// Steps 4-5, 7.
int start = len - searchLen; // Start searching here
if (args.hasDefined(1)) {
if (args[1].isInt32()) {
int i = args[1].toInt32();
if (i <= 0)
start = 0;
else if (i < start)
start = i;
} else {
double d;
if (!ToNumber(cx, args[1], &d))
return false;
if (!IsNaN(d)) {
d = JS::ToInteger(d);
if (d <= 0)
start = 0;
else if (d < start)
start = int(d);
}
}
}
if (searchLen > len) {
args.rval().setInt32(-1);
return true;
}
if (searchLen == 0) {
args.rval().setInt32(start);
return true;
}
MOZ_ASSERT(0 <= start && size_t(start) < len);
JSLinearString* text = str->ensureLinear(cx);
if (!text)
return false;
// Step 9.
int32_t res;
AutoCheckCannotGC nogc;
if (text->hasLatin1Chars()) {
const Latin1Char* textChars = text->latin1Chars(nogc);
if (searchStr->hasLatin1Chars())
res = LastIndexOfImpl(textChars, len, searchStr->latin1Chars(nogc), searchLen, start);
else
res = LastIndexOfImpl(textChars, len, searchStr->twoByteChars(nogc), searchLen, start);
} else {
const char16_t* textChars = text->twoByteChars(nogc);
if (searchStr->hasLatin1Chars())
res = LastIndexOfImpl(textChars, len, searchStr->latin1Chars(nogc), searchLen, start);
else
res = LastIndexOfImpl(textChars, len, searchStr->twoByteChars(nogc), searchLen, start);
}
args.rval().setInt32(res);
return true;
}
bool
js::HasSubstringAt(JSLinearString* text, JSLinearString* pat, size_t start)
{
MOZ_ASSERT(start + pat->length() <= text->length());
size_t patLen = pat->length();
AutoCheckCannotGC nogc;
if (text->hasLatin1Chars()) {
const Latin1Char* textChars = text->latin1Chars(nogc) + start;
if (pat->hasLatin1Chars())
return PodEqual(textChars, pat->latin1Chars(nogc), patLen);
return EqualChars(textChars, pat->twoByteChars(nogc), patLen);
}
const char16_t* textChars = text->twoByteChars(nogc) + start;
if (pat->hasTwoByteChars())
return PodEqual(textChars, pat->twoByteChars(nogc), patLen);
return EqualChars(pat->latin1Chars(nogc), textChars, patLen);
}
/* ES6 draft rc3 21.1.3.18. */
bool
js::str_startsWith(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1, 2, and 3
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
// Steps 4 and 5
bool isRegExp;
if (!IsRegExp(cx, args.get(0), &isRegExp))
return false;
// Step 6
if (isRegExp) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARG_TYPE,
"first", "", "Regular Expression");
return false;
}
// Steps 7 and 8
RootedLinearString searchStr(cx, ArgToRootedString(cx, args, 0));
if (!searchStr)
return false;
// Steps 9 and 10
uint32_t pos = 0;
if (args.hasDefined(1)) {
if (args[1].isInt32()) {
int i = args[1].toInt32();
pos = (i < 0) ? 0U : uint32_t(i);
} else {
double d;
if (!ToInteger(cx, args[1], &d))
return false;
pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
}
}
// Step 11
uint32_t textLen = str->length();
// Step 12
uint32_t start = Min(Max(pos, 0U), textLen);
// Step 13
uint32_t searchLen = searchStr->length();
// Step 14
if (searchLen + start < searchLen || searchLen + start > textLen) {
args.rval().setBoolean(false);
return true;
}
// Steps 15 and 16
JSLinearString* text = str->ensureLinear(cx);
if (!text)
return false;
args.rval().setBoolean(HasSubstringAt(text, searchStr, start));
return true;
}
/* ES6 draft rc3 21.1.3.6. */
bool
js::str_endsWith(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1, 2, and 3
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
// Steps 4 and 5
bool isRegExp;
if (!IsRegExp(cx, args.get(0), &isRegExp))
return false;
// Step 6
if (isRegExp) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARG_TYPE,
"first", "", "Regular Expression");
return false;
}
// Steps 7 and 8
RootedLinearString searchStr(cx, ArgToRootedString(cx, args, 0));
if (!searchStr)
return false;
// Step 9
uint32_t textLen = str->length();
// Steps 10 and 11
uint32_t pos = textLen;
if (args.hasDefined(1)) {
if (args[1].isInt32()) {
int i = args[1].toInt32();
pos = (i < 0) ? 0U : uint32_t(i);
} else {
double d;
if (!ToInteger(cx, args[1], &d))
return false;
pos = uint32_t(Min(Max(d, 0.0), double(UINT32_MAX)));
}
}
// Step 12
uint32_t end = Min(Max(pos, 0U), textLen);
// Step 13
uint32_t searchLen = searchStr->length();
// Step 15 (reordered)
if (searchLen > end) {
args.rval().setBoolean(false);
return true;
}
// Step 14
uint32_t start = end - searchLen;
// Steps 16 and 17
JSLinearString* text = str->ensureLinear(cx);
if (!text)
return false;
args.rval().setBoolean(HasSubstringAt(text, searchStr, start));
return true;
}
template <typename CharT>
static void
TrimString(const CharT* chars, bool trimLeft, bool trimRight, size_t length,
size_t* pBegin, size_t* pEnd)
{
size_t begin = 0, end = length;
if (trimLeft) {
while (begin < length && unicode::IsSpace(chars[begin]))
++begin;
}
if (trimRight) {
while (end > begin && unicode::IsSpace(chars[end - 1]))
--end;
}
*pBegin = begin;
*pEnd = end;
}
static bool
TrimString(JSContext* cx, const CallArgs& args, bool trimLeft, bool trimRight)
{
RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
if (!str)
return false;
JSLinearString* linear = str->ensureLinear(cx);
if (!linear)
return false;
size_t length = linear->length();
size_t begin, end;
if (linear->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
TrimString(linear->latin1Chars(nogc), trimLeft, trimRight, length, &begin, &end);
} else {
AutoCheckCannotGC nogc;
TrimString(linear->twoByteChars(nogc), trimLeft, trimRight, length, &begin, &end);
}
str = NewDependentString(cx, str, begin, end - begin);
if (!str)
return false;
args.rval().setString(str);
return true;
}
bool
js::str_trim(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return TrimString(cx, args, true, true);
}
bool
js::str_trimStart(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return TrimString(cx, args, true, false);
}
bool
js::str_trimEnd(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
return TrimString(cx, args, false, true);
}
// Utility for building a rope (lazy concatenation) of strings.
class RopeBuilder {
JSContext* cx;
RootedString res;
RopeBuilder(const RopeBuilder& other) = delete;
void operator=(const RopeBuilder& other) = delete;
public:
explicit RopeBuilder(JSContext* cx)
: cx(cx), res(cx, cx->runtime()->emptyString)
{}
inline bool append(HandleString str) {
res = ConcatStrings<CanGC>(cx, res, str);
return !!res;
}
inline JSString* result() {
return res;
}
};
namespace {
template <typename CharT>
static uint32_t
FindDollarIndex(const CharT* chars, size_t length)
{
if (const CharT* p = js_strchr_limit(chars, '$', chars + length)) {
uint32_t dollarIndex = p - chars;
MOZ_ASSERT(dollarIndex < length);
return dollarIndex;
}
return UINT32_MAX;
}
} /* anonymous namespace */
static JSString*
BuildFlatReplacement(JSContext* cx, HandleString textstr, HandleString repstr,
size_t match, size_t patternLength)
{
RopeBuilder builder(cx);
size_t matchEnd = match + patternLength;
if (textstr->isRope()) {
/*
* If we are replacing over a rope, avoid flattening it by iterating
* through it, building a new rope.
*/
StringSegmentRange r(cx);
if (!r.init(textstr))
return nullptr;
size_t pos = 0;
while (!r.empty()) {
RootedString str(cx, r.front());
size_t len = str->length();
size_t strEnd = pos + len;
if (pos < matchEnd && strEnd > match) {
/*
* We need to special-case any part of the rope that overlaps
* with the replacement string.
*/
if (match >= pos) {
/*
* If this part of the rope overlaps with the left side of
* the pattern, then it must be the only one to overlap with
* the first character in the pattern, so we include the
* replacement string here.
*/
RootedString leftSide(cx, NewDependentString(cx, str, 0, match - pos));
if (!leftSide ||
!builder.append(leftSide) ||
!builder.append(repstr))
{
return nullptr;
}
}
/*
* If str runs off the end of the matched string, append the
* last part of str.
*/
if (strEnd > matchEnd) {
RootedString rightSide(cx, NewDependentString(cx, str, matchEnd - pos,
strEnd - matchEnd));
if (!rightSide || !builder.append(rightSide))
return nullptr;
}
} else {
if (!builder.append(str))
return nullptr;
}
pos += str->length();
if (!r.popFront())
return nullptr;
}
} else {
RootedString leftSide(cx, NewDependentString(cx, textstr, 0, match));
if (!leftSide)
return nullptr;
RootedString rightSide(cx);
rightSide = NewDependentString(cx, textstr, match + patternLength,
textstr->length() - match - patternLength);
if (!rightSide ||
!builder.append(leftSide) ||
!builder.append(repstr) ||
!builder.append(rightSide))
{
return nullptr;
}
}
return builder.result();
}
template <typename CharT>
static bool
AppendDollarReplacement(StringBuffer& newReplaceChars, size_t firstDollarIndex,
size_t matchStart, size_t matchLimit, JSLinearString* text,
const CharT* repChars, size_t repLength)
{
MOZ_ASSERT(firstDollarIndex < repLength);
MOZ_ASSERT(matchStart <= matchLimit);
MOZ_ASSERT(matchLimit <= text->length());
/* Move the pre-dollar chunk in bulk. */
if (!newReplaceChars.append(repChars, firstDollarIndex)) {
return false;
}
/* Move the rest char-by-char, interpreting dollars as we encounter them. */
const CharT* repLimit = repChars + repLength;
for (const CharT* it = repChars + firstDollarIndex; it < repLimit; ++it) {
if (*it != '$' || it == repLimit - 1) {
if (!newReplaceChars.append(*it))
return false;
continue;
}
switch (*(it + 1)) {
case '$': /* Eat one of the dollars. */
if (!newReplaceChars.append(*it))
return false;
break;
case '&':
if (!newReplaceChars.appendSubstring(text, matchStart, matchLimit - matchStart))
return false;
break;
case '`':
if (!newReplaceChars.appendSubstring(text, 0, matchStart))
return false;
break;
case '\'':
if (!newReplaceChars.appendSubstring(text, matchLimit, text->length() - matchLimit))
return false;
break;
default: /* The dollar we saw was not special (no matter what its mother told it). */
if (!newReplaceChars.append(*it))
return false;
continue;
}
++it; /* We always eat an extra char in the above switch. */
}
return true;
}
/*
* Perform a linear-scan dollar substitution on the replacement text,
* constructing a result string that looks like:
*
* newstring = string[:matchStart] + dollarSub(replaceValue) + string[matchLimit:]
*/
static JSString*
BuildDollarReplacement(JSContext* cx, JSString* textstrArg, JSLinearString* repstr,
uint32_t firstDollarIndex, size_t matchStart, size_t patternLength)
{
RootedLinearString textstr(cx, textstrArg->ensureLinear(cx));
if (!textstr)
return nullptr;
size_t matchLimit = matchStart + patternLength;
/*
* Most probably:
*
* len(newstr) >= len(orig) - len(match) + len(replacement)
*
* Note that dollar vars _could_ make the resulting text smaller than this.
*/
StringBuffer newReplaceChars(cx);
if (repstr->hasTwoByteChars() && !newReplaceChars.ensureTwoByteChars())
return nullptr;
if (!newReplaceChars.reserve(textstr->length() - patternLength + repstr->length()))
return nullptr;
bool res;
if (repstr->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
res = AppendDollarReplacement(newReplaceChars, firstDollarIndex, matchStart, matchLimit,
textstr, repstr->latin1Chars(nogc), repstr->length());
} else {
AutoCheckCannotGC nogc;
res = AppendDollarReplacement(newReplaceChars, firstDollarIndex, matchStart, matchLimit,
textstr, repstr->twoByteChars(nogc), repstr->length());
}
if (!res)
return nullptr;
RootedString leftSide(cx, NewDependentString(cx, textstr, 0, matchStart));
if (!leftSide)
return nullptr;
RootedString newReplace(cx, newReplaceChars.finishString());
if (!newReplace)
return nullptr;
MOZ_ASSERT(textstr->length() >= matchLimit);
RootedString rightSide(cx, NewDependentString(cx, textstr, matchLimit,
textstr->length() - matchLimit));
if (!rightSide)
return nullptr;
RopeBuilder builder(cx);
if (!builder.append(leftSide) || !builder.append(newReplace) || !builder.append(rightSide))
return nullptr;
return builder.result();
}
template <typename StrChar, typename RepChar>
static bool
StrFlatReplaceGlobal(JSContext *cx, JSLinearString *str, JSLinearString *pat, JSLinearString *rep,
StringBuffer &sb)
{
MOZ_ASSERT(str->length() > 0);
AutoCheckCannotGC nogc;
const StrChar *strChars = str->chars<StrChar>(nogc);
const RepChar *repChars = rep->chars<RepChar>(nogc);
// The pattern is empty, so we interleave the replacement string in-between
// each character.
if (!pat->length()) {
CheckedInt<uint32_t> strLength(str->length());
CheckedInt<uint32_t> repLength(rep->length());
CheckedInt<uint32_t> length = repLength * (strLength - 1) + strLength;
if (!length.isValid()) {
ReportAllocationOverflow(cx);
return false;
}
if (!sb.reserve(length.value()))
return false;
for (unsigned i = 0; i < str->length() - 1; ++i, ++strChars) {
sb.infallibleAppend(*strChars);
sb.infallibleAppend(repChars, rep->length());
}
sb.infallibleAppend(*strChars);
return true;
}
// If it's true, we are sure that the result's length is, at least, the same
// length as |str->length()|.
if (rep->length() >= pat->length()) {
if (!sb.reserve(str->length()))
return false;
}
uint32_t start = 0;
for (;;) {
int match = StringMatch(str, pat, start);
if (match < 0)
break;
if (!sb.append(strChars + start, match - start))
return false;
if (!sb.append(repChars, rep->length()))
return false;
start = match + pat->length();
}
if (!sb.append(strChars + start, str->length() - start))
return false;
return true;
}
// This is identical to "str.split(pattern).join(replacement)" except that we
// do some deforestation optimization in Ion.
JSString *
js::str_flat_replace_string(JSContext *cx, HandleString string, HandleString pattern,
HandleString replacement)
{
MOZ_ASSERT(string);
MOZ_ASSERT(pattern);
MOZ_ASSERT(replacement);
if (!string->length())
return string;
RootedLinearString linearRepl(cx, replacement->ensureLinear(cx));
if (!linearRepl)
return nullptr;
RootedLinearString linearPat(cx, pattern->ensureLinear(cx));
if (!linearPat)
return nullptr;
RootedLinearString linearStr(cx, string->ensureLinear(cx));
if (!linearStr)
return nullptr;
StringBuffer sb(cx);
if (linearStr->hasTwoByteChars()) {
if (!sb.ensureTwoByteChars())
return nullptr;
if (linearRepl->hasTwoByteChars()) {
if (!StrFlatReplaceGlobal<char16_t, char16_t>(cx, linearStr, linearPat, linearRepl, sb))
return nullptr;
} else {
if (!StrFlatReplaceGlobal<char16_t, Latin1Char>(cx, linearStr, linearPat, linearRepl, sb))
return nullptr;
}
} else {
if (linearRepl->hasTwoByteChars()) {
if (!sb.ensureTwoByteChars())
return nullptr;
if (!StrFlatReplaceGlobal<Latin1Char, char16_t>(cx, linearStr, linearPat, linearRepl, sb))
return nullptr;
} else {
if (!StrFlatReplaceGlobal<Latin1Char, Latin1Char>(cx, linearStr, linearPat, linearRepl, sb))
return nullptr;
}
}
JSString *str = sb.finishString();
if (!str)
return nullptr;
return str;
}
// https://tc39.es/proposal-string-replaceall/#sec-string.prototype.replaceall
// Steps 7-16 when functionalReplace is false and searchString is not empty.
//
// The steps are quite different, for performance. Loops in steps 11 and 14
// are fused. GetSubstitution is optimized away when possible.
template <typename StrChar, typename RepChar>
static JSString* ReplaceAll(JSContext* cx, JSLinearString* str,
JSLinearString* pat,
JSLinearString* rep) {
// Step 7.
const size_t stringLength = str->length();
const size_t searchLength = pat->length();
const size_t replaceLength = rep->length();
MOZ_ASSERT(stringLength > 0);
MOZ_ASSERT(searchLength > 0);
MOZ_ASSERT(stringLength >= searchLength);
// Step 8 (advanceBy is equal to searchLength when searchLength > 0).
// Step 9 (not needed in this implementation).
// Step 10.
// Find the first match.
int32_t position = StringMatch(str, pat, 0);
// Nothing to replace, so return early.
if (position < 0) {
return str;
}
// Step 11 (moved below).
// Step 12.
uint32_t endOfLastMatch = 0;
// Step 13.
StringBuffer result(cx);
if (std::is_same<StrChar, char16_t>::value ||
std::is_same<RepChar, char16_t>::value) {
if (!result.ensureTwoByteChars()) {
return nullptr;
}
}
{
AutoCheckCannotGC nogc;
const StrChar* strChars = str->chars<StrChar>(nogc);
const RepChar* repChars = rep->chars<RepChar>(nogc);
uint32_t dollarIndex = FindDollarIndex(repChars, replaceLength);
// If it's true, we are sure that the result's length is, at least, the same
// length as |str->length()|.
if (replaceLength >= searchLength) {
if (!result.reserve(stringLength)) {
return nullptr;
}
}
do {
// Step 14.c.
// Append the substring before the current match.
if (!result.append(strChars + endOfLastMatch,
position - endOfLastMatch)) {
return nullptr;
}
// Steps 14.a-b and 14.d.
// Append the replacement.
if (dollarIndex != UINT32_MAX) {
size_t matchLimit = position + searchLength;
if (!AppendDollarReplacement(result, dollarIndex, position, matchLimit,
str, repChars, replaceLength)) {
return nullptr;
}
} else {
if (!result.append(repChars, replaceLength)) {
return nullptr;
}
}
// Step 14.e.
endOfLastMatch = position + searchLength;
// Step 11.
// Find the next match.
position = StringMatch(str, pat, endOfLastMatch);
} while (position >= 0);
// Step 15.
// Append the substring after the last match.
if (!result.append(strChars + endOfLastMatch,
stringLength - endOfLastMatch)) {
return nullptr;
}
}
// Step 16.
return result.finishString();
}
// https://tc39.es/proposal-string-replaceall/#sec-string.prototype.replaceall
// Steps 7-16 when functionalReplace is false and searchString is the empty
// string.
//
// The steps are quite different, for performance. Loops in steps 11 and 14
// are fused. GetSubstitution is optimized away when possible.
template <typename StrChar, typename RepChar>
static JSString* ReplaceAllInterleave(JSContext* cx, JSLinearString* str,
JSLinearString* rep) {
// Step 7.
const size_t stringLength = str->length();
const size_t replaceLength = rep->length();
// Step 8 (advanceBy is 1 when searchString is the empty string).
// Steps 9-12 (trivial when searchString is the empty string).
// Step 13.
StringBuffer result(cx);
if (std::is_same<StrChar, char16_t>::value ||
std::is_same<RepChar, char16_t>::value) {
if (!result.ensureTwoByteChars()) {
return nullptr;
}
}
{
AutoCheckCannotGC nogc;
const StrChar* strChars = str->chars<StrChar>(nogc);
const RepChar* repChars = rep->chars<RepChar>(nogc);
uint32_t dollarIndex = FindDollarIndex(repChars, replaceLength);
if (dollarIndex != UINT32_MAX) {
if (!result.reserve(stringLength)) {
return nullptr;
}
} else {
// Compute the exact result length when no substitutions take place.
CheckedInt<uint32_t> strLength(stringLength);
CheckedInt<uint32_t> repLength(replaceLength);
CheckedInt<uint32_t> length = strLength + (strLength + 1) * repLength;
if (!length.isValid()) {
ReportAllocationOverflow(cx);
return nullptr;
}
if (!result.reserve(length.value())) {
return nullptr;
}
}
auto appendReplacement = [&](size_t match) {
if (dollarIndex != UINT32_MAX) {
return AppendDollarReplacement(result, dollarIndex, match, match,
str, repChars, replaceLength);
}
return result.append(repChars, replaceLength);
};
for (size_t index = 0; index < stringLength; index++) {
// Steps 11, 14.a-b and 14.d.
// The empty string matches before each character.
if (!appendReplacement(index)) {
return nullptr;
}
// Step 14.c.
if (!result.append(strChars[index])) {
return nullptr;
}
}
// Steps 11, 14.a-b and 14.d.
// The empty string also matches at the end of the string.
if (!appendReplacement(stringLength)) {
return nullptr;
}
// Step 15 (not applicable when searchString is the empty string).
}
// Step 16.
return result.finishString();
}
// String.prototype.replaceAll (Stage 3 proposal)
// https://tc39.es/proposal-string-replaceall/
//
// String.prototype.replaceAll ( searchValue, replaceValue )
//
// Steps 7-16 when functionalReplace is false.o
JSString*
js::str_replace_string_raw(JSContext* cx, HandleString string, HandleString pattern,
HandleString replacement)
{
RootedLinearString repl(cx, replacement->ensureLinear(cx));
if (!repl)
return nullptr;
RootedAtom pat(cx, AtomizeString(cx, pattern));
if (!pat)
return nullptr;
size_t patternLength = pat->length();
int32_t match;
uint32_t dollarIndex;
{
AutoCheckCannotGC nogc;
dollarIndex = repl->hasLatin1Chars()
? FindDollarIndex(repl->latin1Chars(nogc), repl->length())
: FindDollarIndex(repl->twoByteChars(nogc), repl->length());
}
/*
* |string| could be a rope, so we want to avoid flattening it for as
* long as possible.
*/
if (string->isRope()) {
if (!RopeMatch(cx, &string->asRope(), pat, &match))
return nullptr;
} else {
match = StringMatch(&string->asLinear(), pat, 0);
}
if (match < 0)
return string;
if (dollarIndex != UINT32_MAX)
return BuildDollarReplacement(cx, string, repl, dollarIndex, match, patternLength);
return BuildFlatReplacement(cx, string, repl, match, patternLength);
}
JSString*
js::str_replaceAll_string_raw(JSContext* cx, HandleString string, HandleString pattern,
HandleString replacement)
{
const size_t stringLength = string->length();
const size_t searchLength = pattern->length();
// Directly return when we're guaranteed to find no match.
if (searchLength > stringLength) {
return string;
}
RootedLinearString str(cx, string->ensureLinear(cx));
if (!str) {
return nullptr;
}
RootedLinearString repl(cx, replacement->ensureLinear(cx));
if (!repl) {
return nullptr;
}
RootedLinearString search(cx, pattern->ensureLinear(cx));
if (!search) {
return nullptr;
}
// The pattern is empty, so we interleave the replacement string in-between
// each character.
if (searchLength == 0) {
if (str->hasTwoByteChars()) {
if (repl->hasTwoByteChars()) {
return ReplaceAllInterleave<char16_t, char16_t>(cx, str, repl);
}
return ReplaceAllInterleave<char16_t, Latin1Char>(cx, str, repl);
}
if (repl->hasTwoByteChars()) {
return ReplaceAllInterleave<Latin1Char, char16_t>(cx, str, repl);
}
return ReplaceAllInterleave<Latin1Char, Latin1Char>(cx, str, repl);
}
MOZ_ASSERT(stringLength > 0);
if (str->hasTwoByteChars()) {
if (repl->hasTwoByteChars()) {
return ReplaceAll<char16_t, char16_t>(cx, str, search, repl);
}
return ReplaceAll<char16_t, Latin1Char>(cx, str, search, repl);
}
if (repl->hasTwoByteChars()) {
return ReplaceAll<Latin1Char, char16_t>(cx, str, search, repl);
}
return ReplaceAll<Latin1Char, Latin1Char>(cx, str, search, repl);
}
// ES 2016 draft Mar 25, 2016 21.1.3.17 steps 4, 8, 12-18.
static JSObject*
SplitHelper(JSContext* cx, HandleLinearString str, uint32_t limit, HandleLinearString sep,
HandleObjectGroup group)
{
size_t strLength = str->length();
size_t sepLength = sep->length();
MOZ_ASSERT(sepLength != 0);
// Step 12.
if (strLength == 0) {
// Step 12.a.
int match = StringMatch(str, sep, 0);
// Step 12.b.
if (match != -1)
return NewFullyAllocatedArrayTryUseGroup(cx, group, 0);
// Steps 12.c-e.
RootedValue v(cx, StringValue(str));
return NewCopiedArrayTryUseGroup(cx, group, v.address(), 1);
}
// Step 3 (reordered).
AutoValueVector splits(cx);
// Step 8 (reordered).
size_t lastEndIndex = 0;
// Step 13.
size_t index = 0;
// Step 14.
while (index != strLength) {
// Step 14.a.
int match = StringMatch(str, sep, index);
// Step 14.b.
//
// Our match algorithm differs from the spec in that it returns the
// next index at which a match happens. If no match happens we're
// done.
//
// But what if the match is at the end of the string (and the string is
// not empty)? Per 14.c.i this shouldn't be a match, so we have to
// specially exclude it. Thus this case should hold:
//
// var a = "abc".split(/\b/);
// assertEq(a.length, 1);
// assertEq(a[0], "abc");
if (match == -1)
break;
// Step 14.c.
size_t endIndex = match + sepLength;
// Step 14.c.i.
if (endIndex == lastEndIndex) {
index++;
continue;
}
// Step 14.c.ii.
MOZ_ASSERT(lastEndIndex < endIndex);
MOZ_ASSERT(sepLength <= strLength);
MOZ_ASSERT(lastEndIndex + sepLength <= endIndex);
// Step 14.c.ii.1.
size_t subLength = size_t(endIndex - sepLength - lastEndIndex);
JSString* sub = NewDependentString(cx, str, lastEndIndex, subLength);
// Steps 14.c.ii.2-4.
if (!sub || !splits.append(StringValue(sub)))
return nullptr;
// Step 14.c.ii.5.
if (splits.length() == limit)
return NewCopiedArrayTryUseGroup(cx, group, splits.begin(), splits.length());
// Step 14.c.ii.6.
index = endIndex;
// Step 14.c.ii.7.
lastEndIndex = index;
}
// Step 15.
JSString* sub = NewDependentString(cx, str, lastEndIndex, strLength - lastEndIndex);
// Steps 16-17.
if (!sub || !splits.append(StringValue(sub)))
return nullptr;
// Step 18.
return NewCopiedArrayTryUseGroup(cx, group, splits.begin(), splits.length());
}
// Fast-path for splitting a string into a character array via split("").
static JSObject*
CharSplitHelper(JSContext* cx, HandleLinearString str, uint32_t limit, HandleObjectGroup group)
{
size_t strLength = str->length();
if (strLength == 0)
return NewFullyAllocatedArrayTryUseGroup(cx, group, 0);
js::StaticStrings& staticStrings = cx->staticStrings();
uint32_t resultlen = (limit < strLength ? limit : strLength);
AutoValueVector splits(cx);
if (!splits.reserve(resultlen))
return nullptr;
for (size_t i = 0; i < resultlen; ++i) {
JSString* sub = staticStrings.getUnitStringForElement(cx, str, i);
if (!sub)
return nullptr;
splits.infallibleAppend(StringValue(sub));
}
return NewCopiedArrayTryUseGroup(cx, group, splits.begin(), splits.length());
}
// ES 2016 draft Mar 25, 2016 21.1.3.17 steps 4, 8, 12-18.
JSObject*
js::str_split_string(JSContext* cx, HandleObjectGroup group, HandleString str, HandleString sep, uint32_t limit)
{
RootedLinearString linearStr(cx, str->ensureLinear(cx));
if (!linearStr)
return nullptr;
RootedLinearString linearSep(cx, sep->ensureLinear(cx));
if (!linearSep)
return nullptr;
if (linearSep->length() == 0)
return CharSplitHelper(cx, linearStr, limit, group);
return SplitHelper(cx, linearStr, limit, linearSep, group);
}
/*
* Python-esque sequence operations.
*/
bool
js::str_concat(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
JSString* str = ToStringForStringFunction(cx, args.thisv());
if (!str)
return false;
for (unsigned i = 0; i < args.length(); i++) {
JSString* argStr = ToString<NoGC>(cx, args[i]);
if (!argStr) {
RootedString strRoot(cx, str);
argStr = ToString<CanGC>(cx, args[i]);
if (!argStr)
return false;
str = strRoot;
}
JSString* next = ConcatStrings<NoGC>(cx, str, argStr);
if (next) {
str = next;
} else {
RootedString strRoot(cx, str), argStrRoot(cx, argStr);
str = ConcatStrings<CanGC>(cx, strRoot, argStrRoot);
if (!str)
return false;
}
}
args.rval().setString(str);
return true;
}
static const JSFunctionSpec string_methods[] = {
#if JS_HAS_TOSOURCE
JS_FN(js_toSource_str, str_toSource, 0,0),
#endif
/* Java-like methods. */
JS_FN(js_toString_str, str_toString, 0,0),
JS_FN(js_valueOf_str, str_toString, 0,0),
JS_FN("toLowerCase", str_toLowerCase, 0,0),
JS_FN("toUpperCase", str_toUpperCase, 0,0),
JS_INLINABLE_FN("charAt", str_charAt, 1,0, StringCharAt),
JS_INLINABLE_FN("charCodeAt", str_charCodeAt, 1,0, StringCharCodeAt),
JS_SELF_HOSTED_FN("substring", "String_substring", 2,0),
JS_SELF_HOSTED_FN("padStart", "String_pad_start", 2,0),
JS_SELF_HOSTED_FN("padEnd", "String_pad_end", 2,0),
JS_SELF_HOSTED_FN("codePointAt", "String_codePointAt", 1,0),
JS_FN("includes", str_includes, 1,0),
JS_FN("contains", str_contains, 1,0),
JS_FN("indexOf", str_indexOf, 1,0),
JS_FN("lastIndexOf", str_lastIndexOf, 1,0),
JS_FN("startsWith", str_startsWith, 1,0),
JS_FN("endsWith", str_endsWith, 1,0),
JS_FN("trim", str_trim, 0,0),
JS_FN("trimLeft", str_trimStart, 0,0),
JS_FN("trimStart", str_trimStart, 0,0),
JS_FN("trimRight", str_trimEnd, 0,0),
JS_FN("trimEnd", str_trimEnd, 0,0),
JS_SELF_HOSTED_FN("toLocaleLowerCase", "String_toLocaleLowerCase", 0,0),
JS_SELF_HOSTED_FN("toLocaleUpperCase", "String_toLocaleUpperCase", 0,0),
JS_SELF_HOSTED_FN("localeCompare", "String_localeCompare", 1,0),
JS_SELF_HOSTED_FN("repeat", "String_repeat", 1,0),
JS_FN("normalize", str_normalize, 0,0),
/* Perl-ish methods (search is actually Python-esque). */
JS_SELF_HOSTED_FN("match", "String_match", 1,0),
JS_SELF_HOSTED_FN("matchAll", "String_matchAll", 1,0),
JS_SELF_HOSTED_FN("search", "String_search", 1,0),
JS_SELF_HOSTED_FN("replace", "String_replace", 2,0),
JS_SELF_HOSTED_FN("replaceAll", "String_replaceAll", 2,0),
JS_SELF_HOSTED_FN("split", "String_split", 2,0),
JS_SELF_HOSTED_FN("substr", "String_substr", 2,0),
/* Python-esque sequence methods. */
JS_FN("concat", str_concat, 1,0),
JS_SELF_HOSTED_FN("slice", "String_slice", 2,0),
/* ES2022 additions */
JS_SELF_HOSTED_FN("at", "String_at", 1,0),
/* HTML string methods. */
JS_SELF_HOSTED_FN("bold", "String_bold", 0,0),
JS_SELF_HOSTED_FN("italics", "String_italics", 0,0),
JS_SELF_HOSTED_FN("fixed", "String_fixed", 0,0),
JS_SELF_HOSTED_FN("strike", "String_strike", 0,0),
JS_SELF_HOSTED_FN("small", "String_small", 0,0),
JS_SELF_HOSTED_FN("big", "String_big", 0,0),
JS_SELF_HOSTED_FN("blink", "String_blink", 0,0),
JS_SELF_HOSTED_FN("sup", "String_sup", 0,0),
JS_SELF_HOSTED_FN("sub", "String_sub", 0,0),
JS_SELF_HOSTED_FN("anchor", "String_anchor", 1,0),
JS_SELF_HOSTED_FN("link", "String_link", 1,0),
JS_SELF_HOSTED_FN("fontcolor","String_fontcolor", 1,0),
JS_SELF_HOSTED_FN("fontsize", "String_fontsize", 1,0),
JS_SELF_HOSTED_SYM_FN(iterator, "String_iterator", 0,0),
JS_FS_END
};
// ES6 rev 27 (2014 Aug 24) 21.1.1
bool
js::StringConstructor(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedString str(cx);
if (args.length() > 0) {
if (!args.isConstructing() && args[0].isSymbol())
return js::SymbolDescriptiveString(cx, args[0].toSymbol(), args.rval());
str = ToString<CanGC>(cx, args[0]);
if (!str)
return false;
} else {
str = cx->runtime()->emptyString;
}
if (args.isConstructing()) {
RootedObject proto(cx);
RootedObject newTarget(cx, &args.newTarget().toObject());
if (!GetPrototypeFromConstructor(cx, newTarget, &proto))
return false;
StringObject* strobj = StringObject::create(cx, str, proto);
if (!strobj)
return false;
args.rval().setObject(*strobj);
return true;
}
args.rval().setString(str);
return true;
}
static bool
str_fromCharCode_few_args(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(args.length() <= JSFatInlineString::MAX_LENGTH_TWO_BYTE);
char16_t chars[JSFatInlineString::MAX_LENGTH_TWO_BYTE];
for (unsigned i = 0; i < args.length(); i++) {
uint16_t code;
if (!ToUint16(cx, args[i], &code))
return false;
chars[i] = char16_t(code);
}
JSString* str = NewStringCopyN<CanGC>(cx, chars, args.length());
if (!str)
return false;
args.rval().setString(str);
return true;
}
bool
js::str_fromCharCode(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() <= ARGS_LENGTH_MAX);
// Optimize the single-char case.
if (args.length() == 1)
return str_fromCharCode_one_arg(cx, args[0], args.rval());
// Optimize the case where the result will definitely fit in an inline
// string (thin or fat) and so we don't need to malloc the chars. (We could
// cover some cases where args.length() goes up to
// JSFatInlineString::MAX_LENGTH_LATIN1 if we also checked if the chars are
// all Latin-1, but it doesn't seem worth the effort.)
if (args.length() <= JSFatInlineString::MAX_LENGTH_TWO_BYTE)
return str_fromCharCode_few_args(cx, args);
char16_t* chars = cx->pod_malloc<char16_t>(args.length() + 1);
if (!chars)
return false;
for (unsigned i = 0; i < args.length(); i++) {
uint16_t code;
if (!ToUint16(cx, args[i], &code)) {
js_free(chars);
return false;
}
chars[i] = char16_t(code);
}
chars[args.length()] = 0;
JSString* str = NewString<CanGC>(cx, chars, args.length());
if (!str) {
js_free(chars);
return false;
}
args.rval().setString(str);
return true;
}
static inline bool
CodeUnitToString(JSContext* cx, uint16_t ucode, MutableHandleValue rval)
{
if (StaticStrings::hasUnit(ucode)) {
rval.setString(cx->staticStrings().getUnit(ucode));
return true;
}
char16_t c = char16_t(ucode);
JSString* str = NewStringCopyN<CanGC>(cx, &c, 1);
if (!str)
return false;
rval.setString(str);
return true;
}
bool
js::str_fromCharCode_one_arg(JSContext* cx, HandleValue code, MutableHandleValue rval)
{
uint16_t ucode;
if (!ToUint16(cx, code, &ucode))
return false;
return CodeUnitToString(cx, ucode, rval);
}
static MOZ_ALWAYS_INLINE bool
ToCodePoint(JSContext* cx, HandleValue code, uint32_t* codePoint)
{
// String.fromCodePoint, Steps 5.a-b.
double nextCP;
if (!ToNumber(cx, code, &nextCP))
return false;
// String.fromCodePoint, Steps 5.c-d.
if (JS::ToInteger(nextCP) != nextCP || nextCP < 0 || nextCP > unicode::NonBMPMax) {
ToCStringBuf cbuf;
if (char* numStr = NumberToCString(cx, &cbuf, nextCP))
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NOT_A_CODEPOINT, numStr);
return false;
}
*codePoint = uint32_t(nextCP);
return true;
}
bool
js::str_fromCodePoint_one_arg(JSContext* cx, HandleValue code, MutableHandleValue rval)
{
// Steps 1-4 (omitted).
// Steps 5.a-d.
uint32_t codePoint;
if (!ToCodePoint(cx, code, &codePoint))
return false;
// Steps 5.e, 6.
if (!unicode::IsSupplementary(codePoint))
return CodeUnitToString(cx, uint16_t(codePoint), rval);
char16_t chars[] = { unicode::LeadSurrogate(codePoint), unicode::TrailSurrogate(codePoint) };
JSString* str = NewStringCopyNDontDeflate<CanGC>(cx, chars, 2);
if (!str)
return false;
rval.setString(str);
return true;
}
static bool
str_fromCodePoint_few_args(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(args.length() <= JSFatInlineString::MAX_LENGTH_TWO_BYTE / 2);
// Steps 1-2 (omitted).
// Step 3.
char16_t elements[JSFatInlineString::MAX_LENGTH_TWO_BYTE];
// Steps 4-5.
unsigned length = 0;
for (unsigned nextIndex = 0; nextIndex < args.length(); nextIndex++) {
// Steps 5.a-d.
uint32_t codePoint;
if (!ToCodePoint(cx, args[nextIndex], &codePoint))
return false;
// Step 5.e.
unicode::UTF16Encode(codePoint, elements, &length);
}
// Step 6.
JSString* str = NewStringCopyN<CanGC>(cx, elements, length);
if (!str)
return false;
args.rval().setString(str);
return true;
}
// ES2017 draft rev 40edb3a95a475c1b251141ac681b8793129d9a6d
// 21.1.2.2 String.fromCodePoint(...codePoints)
bool
js::str_fromCodePoint(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Optimize the single code-point case.
if (args.length() == 1)
return str_fromCodePoint_one_arg(cx, args[0], args.rval());
// Optimize the case where the result will definitely fit in an inline
// string (thin or fat) and so we don't need to malloc the chars. (We could
// cover some cases where |args.length()| goes up to
// JSFatInlineString::MAX_LENGTH_LATIN1 / 2 if we also checked if the chars
// are all Latin-1, but it doesn't seem worth the effort.)
if (args.length() <= JSFatInlineString::MAX_LENGTH_TWO_BYTE / 2)
return str_fromCodePoint_few_args(cx, args);
// Steps 1-2 (omitted).
// Step 3.
static_assert(ARGS_LENGTH_MAX < std::numeric_limits<size_t>::max() / 2,
"|args.length() * 2 + 1| does not overflow");
char16_t* elements = cx->pod_malloc<char16_t>(args.length() * 2 + 1);
if (!elements)
return false;
// Steps 4-5.
unsigned length = 0;
for (unsigned nextIndex = 0; nextIndex < args.length(); nextIndex++) {
// Steps 5.a-d.
uint32_t codePoint;
if (!ToCodePoint(cx, args[nextIndex], &codePoint)) {
js_free(elements);
return false;
}
// Step 5.e.
unicode::UTF16Encode(codePoint, elements, &length);
}
elements[length] = 0;
// Step 6.
JSString* str = NewString<CanGC>(cx, elements, length);
if (!str) {
js_free(elements);
return false;
}
args.rval().setString(str);
return true;
}
static const JSFunctionSpec string_static_methods[] = {
JS_INLINABLE_FN("fromCharCode", js::str_fromCharCode, 1, 0, StringFromCharCode),
JS_INLINABLE_FN("fromCodePoint", js::str_fromCodePoint, 1, 0, StringFromCodePoint),
JS_SELF_HOSTED_FN("raw", "String_static_raw", 2,0),
JS_SELF_HOSTED_FN("substring", "String_static_substring", 3,0),
JS_SELF_HOSTED_FN("substr", "String_static_substr", 3,0),
JS_SELF_HOSTED_FN("slice", "String_static_slice", 3,0),
JS_SELF_HOSTED_FN("match", "String_generic_match", 2,0),
JS_SELF_HOSTED_FN("replace", "String_generic_replace", 3,0),
JS_SELF_HOSTED_FN("search", "String_generic_search", 2,0),
JS_SELF_HOSTED_FN("split", "String_generic_split", 3,0),
JS_SELF_HOSTED_FN("toLowerCase", "String_static_toLowerCase", 1,0),
JS_SELF_HOSTED_FN("toUpperCase", "String_static_toUpperCase", 1,0),
JS_SELF_HOSTED_FN("charAt", "String_static_charAt", 2,0),
JS_SELF_HOSTED_FN("charCodeAt", "String_static_charCodeAt", 2,0),
JS_SELF_HOSTED_FN("includes", "String_static_includes", 2,0),
JS_SELF_HOSTED_FN("indexOf", "String_static_indexOf", 2,0),
JS_SELF_HOSTED_FN("lastIndexOf", "String_static_lastIndexOf", 2,0),
JS_SELF_HOSTED_FN("startsWith", "String_static_startsWith", 2,0),
JS_SELF_HOSTED_FN("endsWith", "String_static_endsWith", 2,0),
JS_SELF_HOSTED_FN("trim", "String_static_trim", 1,0),
JS_SELF_HOSTED_FN("trimLeft", "String_static_trimStart", 1,0),
JS_SELF_HOSTED_FN("trimStart", "String_static_trimStart", 1,0),
JS_SELF_HOSTED_FN("trimRight", "String_static_trimEnd", 1,0),
JS_SELF_HOSTED_FN("trimEnd", "String_static_trimEnd", 1,0),
JS_SELF_HOSTED_FN("toLocaleLowerCase","String_static_toLocaleLowerCase",1,0),
JS_SELF_HOSTED_FN("toLocaleUpperCase","String_static_toLocaleUpperCase",1,0),
JS_SELF_HOSTED_FN("normalize", "String_static_normalize", 1,0),
JS_SELF_HOSTED_FN("concat", "String_static_concat", 2,0),
JS_SELF_HOSTED_FN("localeCompare", "String_static_localeCompare", 2,0),
JS_FS_END
};
/* static */ Shape*
StringObject::assignInitialShape(ExclusiveContext* cx, Handle<StringObject*> obj)
{
MOZ_ASSERT(obj->empty());
return obj->addDataProperty(cx, cx->names().length, LENGTH_SLOT,
JSPROP_PERMANENT | JSPROP_READONLY);
}
JSObject*
js::InitStringClass(JSContext* cx, HandleObject obj)
{
MOZ_ASSERT(obj->isNative());
Handle<GlobalObject*> global = obj.as<GlobalObject>();
Rooted<JSString*> empty(cx, cx->runtime()->emptyString);
RootedObject proto(cx, GlobalObject::createBlankPrototype(cx, global, &StringObject::class_));
if (!proto)
return nullptr;
Handle<StringObject*> protoObj = proto.as<StringObject>();
if (!StringObject::init(cx, protoObj, empty))
return nullptr;
/* Now create the String function. */
RootedFunction ctor(cx);
ctor = GlobalObject::createConstructor(cx, StringConstructor, cx->names().String, 1,
AllocKind::FUNCTION, &jit::JitInfo_String);
if (!ctor)
return nullptr;
if (!LinkConstructorAndPrototype(cx, ctor, proto))
return nullptr;
if (!DefinePropertiesAndFunctions(cx, proto, nullptr, string_methods) ||
!DefinePropertiesAndFunctions(cx, ctor, nullptr, string_static_methods))
{
return nullptr;
}
/*
* Define escape/unescape, the URI encode/decode functions, and maybe
* uneval on the global object.
*/
if (!JS_DefineFunctions(cx, global, string_functions))
return nullptr;
if (!GlobalObject::initBuiltinConstructor(cx, global, JSProto_String, ctor, proto))
return nullptr;
return proto;
}
const char*
js::ValueToPrintable(JSContext* cx, const Value& vArg, JSAutoByteString* bytes, bool asSource)
{
RootedValue v(cx, vArg);
JSString* str;
if (asSource)
str = ValueToSource(cx, v);
else
str = ToString<CanGC>(cx, v);
if (!str)
return nullptr;
str = QuoteString(cx, str, 0);
if (!str)
return nullptr;
return bytes->encodeLatin1(cx, str);
}
template <AllowGC allowGC>
JSString*
js::ToStringSlow(ExclusiveContext* cx, typename MaybeRooted<Value, allowGC>::HandleType arg)
{
/* As with ToObjectSlow, callers must verify that |arg| isn't a string. */
MOZ_ASSERT(!arg.isString());
Value v = arg;
if (!v.isPrimitive()) {
if (!cx->shouldBeJSContext() || !allowGC)
return nullptr;
RootedValue v2(cx, v);
if (!ToPrimitive(cx->asJSContext(), JSTYPE_STRING, &v2))
return nullptr;
v = v2;
}
JSString* str;
if (v.isString()) {
str = v.toString();
} else if (v.isInt32()) {
str = Int32ToString<allowGC>(cx, v.toInt32());
} else if (v.isDouble()) {
str = NumberToString<allowGC>(cx, v.toDouble());
} else if (v.isBoolean()) {
str = BooleanToString(cx, v.toBoolean());
} else if (v.isNull()) {
str = cx->names().null;
} else if (v.isSymbol()) {
if (cx->shouldBeJSContext() && allowGC) {
JS_ReportErrorNumberASCII(cx->asJSContext(), GetErrorMessage, nullptr,
JSMSG_SYMBOL_TO_STRING);
}
return nullptr;
} else {
MOZ_ASSERT(v.isUndefined());
str = cx->names().undefined;
}
return str;
}
template JSString*
js::ToStringSlow<CanGC>(ExclusiveContext* cx, HandleValue arg);
template JSString*
js::ToStringSlow<NoGC>(ExclusiveContext* cx, const Value& arg);
JS_PUBLIC_API(JSString*)
js::ToStringSlow(JSContext* cx, HandleValue v)
{
return ToStringSlow<CanGC>(cx, v);
}
static JSString*
SymbolToSource(JSContext* cx, Symbol* symbol)
{
RootedString desc(cx, symbol->description());
SymbolCode code = symbol->code();
if (code != SymbolCode::InSymbolRegistry && code != SymbolCode::UniqueSymbol) {
// Well-known symbol.
MOZ_ASSERT(uint32_t(code) < JS::WellKnownSymbolLimit);
return desc;
}
StringBuffer buf(cx);
if (code == SymbolCode::InSymbolRegistry ? !buf.append("Symbol.for(") : !buf.append("Symbol("))
return nullptr;
if (desc) {
desc = StringToSource(cx, desc);
if (!desc || !buf.append(desc))
return nullptr;
}
if (!buf.append(')'))
return nullptr;
return buf.finishString();
}
JSString*
js::ValueToSource(JSContext* cx, HandleValue v)
{
JS_CHECK_RECURSION(cx, return nullptr);
assertSameCompartment(cx, v);
if (v.isUndefined())
return cx->names().void0;
if (v.isString())
return StringToSource(cx, v.toString());
if (v.isSymbol())
return SymbolToSource(cx, v.toSymbol());
if (v.isPrimitive()) {
/* Special case to preserve negative zero, _contra_ toString. */
if (v.isDouble() && IsNegativeZero(v.toDouble())) {
/* NB: _ucNstr rather than _ucstr to indicate non-terminated. */
static const char16_t js_negzero_ucNstr[] = {'-', '0'};
return NewStringCopyN<CanGC>(cx, js_negzero_ucNstr, 2);
}
return ToString<CanGC>(cx, v);
}
RootedValue fval(cx);
RootedObject obj(cx, &v.toObject());
if (!GetProperty(cx, obj, obj, cx->names().toSource, &fval))
return nullptr;
if (IsCallable(fval)) {
RootedValue v(cx);
if (!js::Call(cx, fval, obj, &v))
return nullptr;
return ToString<CanGC>(cx, v);
}
#if JS_HAS_TOSOURCE
return ObjectToSource(cx, obj);
#else
return ToString<CanGC>(cx, v);
#endif
}
JSString*
js::StringToSource(JSContext* cx, JSString* str)
{
return QuoteString(cx, str, '"');
}
bool
js::EqualChars(JSLinearString* str1, JSLinearString* str2)
{
MOZ_ASSERT(str1->length() == str2->length());
size_t len = str1->length();
AutoCheckCannotGC nogc;
if (str1->hasTwoByteChars()) {
if (str2->hasTwoByteChars())
return PodEqual(str1->twoByteChars(nogc), str2->twoByteChars(nogc), len);
return EqualChars(str2->latin1Chars(nogc), str1->twoByteChars(nogc), len);
}
if (str2->hasLatin1Chars())
return PodEqual(str1->latin1Chars(nogc), str2->latin1Chars(nogc), len);
return EqualChars(str1->latin1Chars(nogc), str2->twoByteChars(nogc), len);
}
bool
js::EqualStrings(JSContext* cx, JSString* str1, JSString* str2, bool* result)
{
if (str1 == str2) {
*result = true;
return true;
}
size_t length1 = str1->length();
if (length1 != str2->length()) {
*result = false;
return true;
}
JSLinearString* linear1 = str1->ensureLinear(cx);
if (!linear1)
return false;
JSLinearString* linear2 = str2->ensureLinear(cx);
if (!linear2)
return false;
*result = EqualChars(linear1, linear2);
return true;
}
bool
js::EqualStrings(JSLinearString* str1, JSLinearString* str2)
{
if (str1 == str2)
return true;
size_t length1 = str1->length();
if (length1 != str2->length())
return false;
return EqualChars(str1, str2);
}
static int32_t
CompareStringsImpl(JSLinearString* str1, JSLinearString* str2)
{
size_t len1 = str1->length();
size_t len2 = str2->length();
AutoCheckCannotGC nogc;
if (str1->hasLatin1Chars()) {
const Latin1Char* chars1 = str1->latin1Chars(nogc);
return str2->hasLatin1Chars()
? CompareChars(chars1, len1, str2->latin1Chars(nogc), len2)
: CompareChars(chars1, len1, str2->twoByteChars(nogc), len2);
}
const char16_t* chars1 = str1->twoByteChars(nogc);
return str2->hasLatin1Chars()
? CompareChars(chars1, len1, str2->latin1Chars(nogc), len2)
: CompareChars(chars1, len1, str2->twoByteChars(nogc), len2);
}
int32_t
js::CompareChars(const char16_t* s1, size_t len1, JSLinearString* s2)
{
AutoCheckCannotGC nogc;
return s2->hasLatin1Chars()
? CompareChars(s1, len1, s2->latin1Chars(nogc), s2->length())
: CompareChars(s1, len1, s2->twoByteChars(nogc), s2->length());
}
bool
js::CompareStrings(JSContext* cx, JSString* str1, JSString* str2, int32_t* result)
{
MOZ_ASSERT(str1);
MOZ_ASSERT(str2);
if (str1 == str2) {
*result = 0;
return true;
}
JSLinearString* linear1 = str1->ensureLinear(cx);
if (!linear1)
return false;
JSLinearString* linear2 = str2->ensureLinear(cx);
if (!linear2)
return false;
*result = CompareStringsImpl(linear1, linear2);
return true;
}
int32_t
js::CompareAtoms(JSAtom* atom1, JSAtom* atom2)
{
return CompareStringsImpl(atom1, atom2);
}
bool
js::StringEqualsAscii(JSLinearString* str, const char* asciiBytes)
{
size_t length = strlen(asciiBytes);
#ifdef DEBUG
for (size_t i = 0; i != length; ++i)
MOZ_ASSERT(unsigned(asciiBytes[i]) <= 127);
#endif
if (length != str->length())
return false;
const Latin1Char* latin1 = reinterpret_cast<const Latin1Char*>(asciiBytes);
AutoCheckCannotGC nogc;
return str->hasLatin1Chars()
? PodEqual(latin1, str->latin1Chars(nogc), length)
: EqualChars(latin1, str->twoByteChars(nogc), length);
}
size_t
js_strlen(const char16_t* s)
{
const char16_t* t;
for (t = s; *t != 0; t++)
continue;
return (size_t)(t - s);
}
int32_t
js_strcmp(const char16_t* lhs, const char16_t* rhs)
{
while (true) {
if (*lhs != *rhs)
return int32_t(*lhs) - int32_t(*rhs);
if (*lhs == 0)
return 0;
++lhs, ++rhs;
}
}
int32_t
js_fputs(const char16_t* s, FILE* f)
{
while (*s != 0) {
if (fputwc(wchar_t(*s), f) == WEOF)
return WEOF;
s++;
}
return 1;
}
UniqueChars
js::DuplicateString(js::ExclusiveContext* cx, const char* s)
{
size_t n = strlen(s) + 1;
auto ret = cx->make_pod_array<char>(n);
if (!ret)
return ret;
PodCopy(ret.get(), s, n);
return ret;
}
UniqueTwoByteChars
js::DuplicateString(js::ExclusiveContext* cx, const char16_t* s)
{
size_t n = js_strlen(s) + 1;
auto ret = cx->make_pod_array<char16_t>(n);
if (!ret)
return ret;
PodCopy(ret.get(), s, n);
return ret;
}
UniqueChars
js::DuplicateString(const char* s)
{
return UniqueChars(js_strdup(s));
}
UniqueChars
js::DuplicateString(const char* s, size_t n)
{
UniqueChars ret(js_pod_malloc<char>(n + 1));
if (!ret)
return nullptr;
PodCopy(ret.get(), s, n);
ret[n] = 0;
return ret;
}
UniqueTwoByteChars
js::DuplicateString(const char16_t* s)
{
return DuplicateString(s, js_strlen(s));
}
UniqueTwoByteChars
js::DuplicateString(const char16_t* s, size_t n)
{
UniqueTwoByteChars ret(js_pod_malloc<char16_t>(n + 1));
if (!ret)
return nullptr;
PodCopy(ret.get(), s, n);
ret[n] = 0;
return ret;
}
template <typename CharT>
const CharT*
js_strchr_limit(const CharT* s, char16_t c, const CharT* limit)
{
while (s < limit) {
if (*s == c)
return s;
s++;
}
return nullptr;
}
template const Latin1Char*
js_strchr_limit(const Latin1Char* s, char16_t c, const Latin1Char* limit);
template const char16_t*
js_strchr_limit(const char16_t* s, char16_t c, const char16_t* limit);
char16_t*
js::InflateString(ExclusiveContext* cx, const char* bytes, size_t* lengthp)
{
size_t nchars;
char16_t* chars;
size_t nbytes = *lengthp;
nchars = nbytes;
chars = cx->pod_malloc<char16_t>(nchars + 1);
if (!chars)
goto bad;
for (size_t i = 0; i < nchars; i++)
chars[i] = (unsigned char) bytes[i];
*lengthp = nchars;
chars[nchars] = 0;
return chars;
bad:
// For compatibility with callers of JS_DecodeBytes we must zero lengthp
// on errors.
*lengthp = 0;
return nullptr;
}
template <typename CharT>
bool
js::DeflateStringToBuffer(JSContext* maybecx, const CharT* src, size_t srclen,
char* dst, size_t* dstlenp)
{
size_t dstlen = *dstlenp;
if (srclen > dstlen) {
for (size_t i = 0; i < dstlen; i++)
dst[i] = char(src[i]);
if (maybecx) {
AutoSuppressGC suppress(maybecx);
JS_ReportErrorNumberASCII(maybecx, GetErrorMessage, nullptr,
JSMSG_BUFFER_TOO_SMALL);
}
return false;
}
for (size_t i = 0; i < srclen; i++)
dst[i] = char(src[i]);
*dstlenp = srclen;
return true;
}
template bool
js::DeflateStringToBuffer(JSContext* maybecx, const Latin1Char* src, size_t srclen,
char* dst, size_t* dstlenp);
template bool
js::DeflateStringToBuffer(JSContext* maybecx, const char16_t* src, size_t srclen,
char* dst, size_t* dstlenp);
#define ____ false
/*
* Identifier start chars:
* - 36: $
* - 65..90: A..Z
* - 95: _
* - 97..122: a..z
*/
const bool js_isidstart[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 1 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 3 */ ____, ____, ____, ____, ____, ____, true, ____, ____, ____,
/* 4 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 5 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 6 */ ____, ____, ____, ____, ____, true, true, true, true, true,
/* 7 */ true, true, true, true, true, true, true, true, true, true,
/* 8 */ true, true, true, true, true, true, true, true, true, true,
/* 9 */ true, ____, ____, ____, ____, true, ____, true, true, true,
/* 10 */ true, true, true, true, true, true, true, true, true, true,
/* 11 */ true, true, true, true, true, true, true, true, true, true,
/* 12 */ true, true, true, ____, ____, ____, ____, ____
};
/*
* Identifier chars:
* - 36: $
* - 48..57: 0..9
* - 65..90: A..Z
* - 95: _
* - 97..122: a..z
*/
const bool js_isident[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 1 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 3 */ ____, ____, ____, ____, ____, ____, true, ____, ____, ____,
/* 4 */ ____, ____, ____, ____, ____, ____, ____, ____, true, true,
/* 5 */ true, true, true, true, true, true, true, true, ____, ____,
/* 6 */ ____, ____, ____, ____, ____, true, true, true, true, true,
/* 7 */ true, true, true, true, true, true, true, true, true, true,
/* 8 */ true, true, true, true, true, true, true, true, true, true,
/* 9 */ true, ____, ____, ____, ____, true, ____, true, true, true,
/* 10 */ true, true, true, true, true, true, true, true, true, true,
/* 11 */ true, true, true, true, true, true, true, true, true, true,
/* 12 */ true, true, true, ____, ____, ____, ____, ____
};
/* Whitespace chars: '\t', '\n', '\v', '\f', '\r', ' '. */
const bool js_isspace[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, true,
/* 1 */ true, true, true, true, ____, ____, ____, ____, ____, ____,
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 3 */ ____, ____, true, ____, ____, ____, ____, ____, ____, ____,
/* 4 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 5 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 6 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 7 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 8 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 9 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 10 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 11 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 12 */ ____, ____, ____, ____, ____, ____, ____, ____
};
/*
* Uri reserved chars + #:
* - 35: #
* - 36: $
* - 38: &
* - 43: +
* - 44: ,
* - 47: /
* - 58: :
* - 59: ;
* - 61: =
* - 63: ?
* - 64: @
*/
static const bool js_isUriReservedPlusPound[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 1 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 3 */ ____, ____, ____, ____, ____, true, true, ____, true, ____,
/* 4 */ ____, ____, ____, true, true, ____, ____, true, ____, ____,
/* 5 */ ____, ____, ____, ____, ____, ____, ____, ____, true, true,
/* 6 */ ____, true, ____, true, true, ____, ____, ____, ____, ____,
/* 7 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 8 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 9 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 10 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 11 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 12 */ ____, ____, ____, ____, ____, ____, ____, ____
};
/*
* Uri unescaped chars:
* - 33: !
* - 39: '
* - 40: (
* - 41: )
* - 42: *
* - 45: -
* - 46: .
* - 48..57: 0-9
* - 65..90: A-Z
* - 95: _
* - 97..122: a-z
* - 126: ~
*/
static const bool js_isUriUnescaped[] = {
/* 0 1 2 3 4 5 6 7 8 9 */
/* 0 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 1 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 2 */ ____, ____, ____, ____, ____, ____, ____, ____, ____, ____,
/* 3 */ ____, ____, ____, true, ____, ____, ____, ____, ____, true,
/* 4 */ true, true, true, ____, ____, true, true, ____, true, true,
/* 5 */ true, true, true, true, true, true, true, true, ____, ____,
/* 6 */ ____, ____, ____, ____, ____, true, true, true, true, true,
/* 7 */ true, true, true, true, true, true, true, true, true, true,
/* 8 */ true, true, true, true, true, true, true, true, true, true,
/* 9 */ true, ____, ____, ____, ____, true, ____, true, true, true,
/* 10 */ true, true, true, true, true, true, true, true, true, true,
/* 11 */ true, true, true, true, true, true, true, true, true, true,
/* 12 */ true, true, true, ____, ____, ____, true, ____
};
#undef ____
#define URI_CHUNK 64U
static inline bool
TransferBufferToString(StringBuffer& sb, MutableHandleValue rval)
{
JSString* str = sb.finishString();
if (!str)
return false;
rval.setString(str);
return true;
}
/*
* ECMA 3, 15.1.3 URI Handling Function Properties
*
* The following are implementations of the algorithms
* given in the ECMA specification for the hidden functions
* 'Encode' and 'Decode'.
*/
enum EncodeResult { Encode_Failure, Encode_BadUri, Encode_Success };
template <typename CharT>
static EncodeResult
Encode(StringBuffer& sb, const CharT* chars, size_t length,
const bool* unescapedSet, const bool* unescapedSet2)
{
static const char HexDigits[] = "0123456789ABCDEF"; /* NB: uppercase */
char16_t hexBuf[4];
hexBuf[0] = '%';
hexBuf[3] = 0;
for (size_t k = 0; k < length; k++) {
char16_t c = chars[k];
if (c < 128 && (unescapedSet[c] || (unescapedSet2 && unescapedSet2[c]))) {
if (!sb.append(c))
return Encode_Failure;
} else {
if (unicode::IsTrailSurrogate(c))
return Encode_BadUri;
uint32_t v;
if (!unicode::IsLeadSurrogate(c)) {
v = c;
} else {
k++;
if (k == length)
return Encode_BadUri;
char16_t c2 = chars[k];
if (!unicode::IsTrailSurrogate(c2))
return Encode_BadUri;
v = unicode::UTF16Decode(c, c2);
}
uint8_t utf8buf[4];
size_t L = OneUcs4ToUtf8Char(utf8buf, v);
for (size_t j = 0; j < L; j++) {
hexBuf[1] = HexDigits[utf8buf[j] >> 4];
hexBuf[2] = HexDigits[utf8buf[j] & 0xf];
if (!sb.append(hexBuf, 3))
return Encode_Failure;
}
}
}
return Encode_Success;
}
static bool
Encode(JSContext* cx, HandleLinearString str, const bool* unescapedSet,
const bool* unescapedSet2, MutableHandleValue rval)
{
size_t length = str->length();
if (length == 0) {
rval.setString(cx->runtime()->emptyString);
return true;
}
StringBuffer sb(cx);
if (!sb.reserve(length))
return false;
EncodeResult res;
if (str->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
res = Encode(sb, str->latin1Chars(nogc), str->length(), unescapedSet, unescapedSet2);
} else {
AutoCheckCannotGC nogc;
res = Encode(sb, str->twoByteChars(nogc), str->length(), unescapedSet, unescapedSet2);
}
if (res == Encode_Failure)
return false;
if (res == Encode_BadUri) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_URI);
return false;
}
MOZ_ASSERT(res == Encode_Success);
return TransferBufferToString(sb, rval);
}
enum DecodeResult { Decode_Failure, Decode_BadUri, Decode_Success };
template <typename CharT>
static DecodeResult
Decode(StringBuffer& sb, const CharT* chars, size_t length, const bool* reservedSet)
{
for (size_t k = 0; k < length; k++) {
char16_t c = chars[k];
if (c == '%') {
size_t start = k;
if ((k + 2) >= length)
return Decode_BadUri;
if (!JS7_ISHEX(chars[k+1]) || !JS7_ISHEX(chars[k+2]))
return Decode_BadUri;
uint32_t B = JS7_UNHEX(chars[k+1]) * 16 + JS7_UNHEX(chars[k+2]);
k += 2;
if (!(B & 0x80)) {
c = char16_t(B);
} else {
int n = 1;
while (B & (0x80 >> n))
n++;
if (n == 1 || n > 4)
return Decode_BadUri;
uint8_t octets[4];
octets[0] = (uint8_t)B;
if (k + 3 * (n - 1) >= length)
return Decode_BadUri;
for (int j = 1; j < n; j++) {
k++;
if (chars[k] != '%')
return Decode_BadUri;
if (!JS7_ISHEX(chars[k+1]) || !JS7_ISHEX(chars[k+2]))
return Decode_BadUri;
B = JS7_UNHEX(chars[k+1]) * 16 + JS7_UNHEX(chars[k+2]);
if ((B & 0xC0) != 0x80)
return Decode_BadUri;
k += 2;
octets[j] = char(B);
}
uint32_t v = JS::Utf8ToOneUcs4Char(octets, n);
if (v >= unicode::NonBMPMin) {
if (v > unicode::NonBMPMax)
return Decode_BadUri;
char16_t H = unicode::LeadSurrogate(v);
if (!sb.append(H))
return Decode_Failure;
c = unicode::TrailSurrogate(v);
} else {
c = char16_t(v);
}
}
if (c < 128 && reservedSet && reservedSet[c]) {
if (!sb.append(chars + start, k - start + 1))
return Decode_Failure;
} else {
if (!sb.append(c))
return Decode_Failure;
}
} else {
if (!sb.append(c))
return Decode_Failure;
}
}
return Decode_Success;
}
static bool
Decode(JSContext* cx, HandleLinearString str, const bool* reservedSet, MutableHandleValue rval)
{
size_t length = str->length();
if (length == 0) {
rval.setString(cx->runtime()->emptyString);
return true;
}
StringBuffer sb(cx);
DecodeResult res;
if (str->hasLatin1Chars()) {
AutoCheckCannotGC nogc;
res = Decode(sb, str->latin1Chars(nogc), str->length(), reservedSet);
} else {
AutoCheckCannotGC nogc;
res = Decode(sb, str->twoByteChars(nogc), str->length(), reservedSet);
}
if (res == Decode_Failure)
return false;
if (res == Decode_BadUri) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_URI);
return false;
}
MOZ_ASSERT(res == Decode_Success);
return TransferBufferToString(sb, rval);
}
static bool
str_decodeURI(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedLinearString str(cx, ArgToRootedString(cx, args, 0));
if (!str)
return false;
return Decode(cx, str, js_isUriReservedPlusPound, args.rval());
}
static bool
str_decodeURI_Component(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedLinearString str(cx, ArgToRootedString(cx, args, 0));
if (!str)
return false;
return Decode(cx, str, nullptr, args.rval());
}
static bool
str_encodeURI(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedLinearString str(cx, ArgToRootedString(cx, args, 0));
if (!str)
return false;
return Encode(cx, str, js_isUriUnescaped, js_isUriReservedPlusPound, args.rval());
}
static bool
str_encodeURI_Component(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RootedLinearString str(cx, ArgToRootedString(cx, args, 0));
if (!str)
return false;
return Encode(cx, str, js_isUriUnescaped, nullptr, args.rval());
}
/*
* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be at
* least 4 bytes long. Return the number of UTF-8 bytes of data written.
*/
uint32_t
js::OneUcs4ToUtf8Char(uint8_t* utf8Buffer, uint32_t ucs4Char)
{
MOZ_ASSERT(ucs4Char <= unicode::NonBMPMax);
if (ucs4Char < 0x80) {
utf8Buffer[0] = uint8_t(ucs4Char);
return 1;
}
uint32_t a = ucs4Char >> 11;
uint32_t utf8Length = 2;
while (a) {
a >>= 5;
utf8Length++;
}
MOZ_ASSERT(utf8Length <= 4);
uint32_t i = utf8Length;
while (--i) {
utf8Buffer[i] = uint8_t((ucs4Char & 0x3F) | 0x80);
ucs4Char >>= 6;
}
utf8Buffer[0] = uint8_t(0x100 - (1 << (8 - utf8Length)) + ucs4Char);
return utf8Length;
}
size_t
js::PutEscapedStringImpl(char* buffer, size_t bufferSize, GenericPrinter* out, JSLinearString* str,
uint32_t quote)
{
size_t len = str->length();
AutoCheckCannotGC nogc;
return str->hasLatin1Chars()
? PutEscapedStringImpl(buffer, bufferSize, out, str->latin1Chars(nogc), len, quote)
: PutEscapedStringImpl(buffer, bufferSize, out, str->twoByteChars(nogc), len, quote);
}
template <typename CharT>
size_t
js::PutEscapedStringImpl(char* buffer, size_t bufferSize, GenericPrinter* out, const CharT* chars,
size_t length, uint32_t quote)
{
enum {
STOP, FIRST_QUOTE, LAST_QUOTE, CHARS, ESCAPE_START, ESCAPE_MORE
} state;
MOZ_ASSERT(quote == 0 || quote == '\'' || quote == '"');
MOZ_ASSERT_IF(!buffer, bufferSize == 0);
MOZ_ASSERT_IF(out, !buffer);
if (bufferSize == 0)
buffer = nullptr;
else
bufferSize--;
const CharT* charsEnd = chars + length;
size_t n = 0;
state = FIRST_QUOTE;
unsigned shift = 0;
unsigned hex = 0;
unsigned u = 0;
char c = 0; /* to quell GCC warnings */
for (;;) {
switch (state) {
case STOP:
goto stop;
case FIRST_QUOTE:
state = CHARS;
goto do_quote;
case LAST_QUOTE:
state = STOP;
do_quote:
if (quote == 0)
continue;
c = (char)quote;
break;
case CHARS:
if (chars == charsEnd) {
state = LAST_QUOTE;
continue;
}
u = *chars++;
if (u < ' ') {
if (u != 0) {
const char* escape = strchr(js_EscapeMap, (int)u);
if (escape) {
u = escape[1];
goto do_escape;
}
}
goto do_hex_escape;
}
if (u < 127) {
if (u == quote || u == '\\')
goto do_escape;
c = (char)u;
} else if (u < 0x100) {
goto do_hex_escape;
} else {
shift = 16;
hex = u;
u = 'u';
goto do_escape;
}
break;
do_hex_escape:
shift = 8;
hex = u;
u = 'x';
do_escape:
c = '\\';
state = ESCAPE_START;
break;
case ESCAPE_START:
MOZ_ASSERT(' ' <= u && u < 127);
c = (char)u;
state = ESCAPE_MORE;
break;
case ESCAPE_MORE:
if (shift == 0) {
state = CHARS;
continue;
}
shift -= 4;
u = 0xF & (hex >> shift);
c = (char)(u + (u < 10 ? '0' : 'A' - 10));
break;
}
if (buffer) {
MOZ_ASSERT(n <= bufferSize);
if (n != bufferSize) {
buffer[n] = c;
} else {
buffer[n] = '\0';
buffer = nullptr;
}
} else if (out) {
if (out->put(&c, 1) < 0)
return size_t(-1);
}
n++;
}
stop:
if (buffer)
buffer[n] = '\0';
return n;
}
template size_t
js::PutEscapedStringImpl(char* buffer, size_t bufferSize, GenericPrinter* out, const Latin1Char* chars,
size_t length, uint32_t quote);
template size_t
js::PutEscapedStringImpl(char* buffer, size_t bufferSize, GenericPrinter* out, const char* chars,
size_t length, uint32_t quote);
template size_t
js::PutEscapedStringImpl(char* buffer, size_t bufferSize, GenericPrinter* out, const char16_t* chars,
size_t length, uint32_t quote);
template size_t
js::PutEscapedString(char* buffer, size_t bufferSize, const Latin1Char* chars, size_t length,
uint32_t quote);
template size_t
js::PutEscapedString(char* buffer, size_t bufferSize, const char16_t* chars, size_t length,
uint32_t quote);
static bool
FlatStringMatchHelper(JSContext* cx, HandleString str, HandleString pattern, bool* isFlat, int32_t* match)
{
RootedLinearString linearPattern(cx, pattern->ensureLinear(cx));
if (!linearPattern)
return false;
static const size_t MAX_FLAT_PAT_LEN = 256;
if (linearPattern->length() > MAX_FLAT_PAT_LEN || StringHasRegExpMetaChars(linearPattern)) {
*isFlat = false;
return true;
}
*isFlat = true;
if (str->isRope()) {
if (!RopeMatch(cx, &str->asRope(), linearPattern, match))
return false;
} else {
*match = StringMatch(&str->asLinear(), linearPattern);
}
return true;
}
static bool
BuildFlatMatchArray(JSContext* cx, HandleString str, HandleString pattern, int32_t match,
MutableHandleValue rval)
{
if (match < 0) {
rval.setNull();
return true;
}
/* Get the templateObject that defines the shape and type of the output object */
JSObject* templateObject = cx->compartment()->regExps.getOrCreateMatchResultTemplateObject(cx);
if (!templateObject)
return false;
RootedArrayObject arr(cx, NewDenseFullyAllocatedArrayWithTemplate(cx, 1, templateObject));
if (!arr)
return false;
/* Store a Value for each pair. */
arr->setDenseInitializedLength(1);
arr->initDenseElement(0, StringValue(pattern));
/* Set the |index| property. (TemplateObject positions it in slot 0) */
arr->setSlot(0, Int32Value(match));
/* Set the |input| property. (TemplateObject positions it in slot 1) */
arr->setSlot(1, StringValue(str));
#ifdef DEBUG
RootedValue test(cx);
RootedId id(cx, NameToId(cx->names().index));
if (!NativeGetProperty(cx, arr, id, &test))
return false;
MOZ_ASSERT(test == arr->getSlot(0));
id = NameToId(cx->names().input);
if (!NativeGetProperty(cx, arr, id, &test))
return false;
MOZ_ASSERT(test == arr->getSlot(1));
#endif
rval.setObject(*arr);
return true;
}
#ifdef DEBUG
static bool
CallIsStringOptimizable(JSContext* cx, const char* name, bool* result)
{
JSAtom* atom = Atomize(cx, name, strlen(name));
if (!atom)
return false;
RootedPropertyName propName(cx, atom->asPropertyName());
RootedValue funcVal(cx);
if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), propName, propName, 0, &funcVal))
return false;
FixedInvokeArgs<0> args(cx);
RootedValue rval(cx);
if (!Call(cx, funcVal, UndefinedHandleValue, args, &rval))
return false;
*result = rval.toBoolean();
return true;
}
#endif
bool
js::FlatStringMatch(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(args[0].isString());
MOZ_ASSERT(args[1].isString());
#ifdef DEBUG
bool isOptimizable = false;
if (!CallIsStringOptimizable(cx, "IsStringMatchOptimizable", &isOptimizable))
return false;
MOZ_ASSERT(isOptimizable);
#endif
RootedString str(cx,args[0].toString());
RootedString pattern(cx, args[1].toString());
bool isFlat = false;
int32_t match = 0;
if (!FlatStringMatchHelper(cx, str, pattern, &isFlat, &match))
return false;
if (!isFlat) {
args.rval().setUndefined();
return true;
}
return BuildFlatMatchArray(cx, str, pattern, match, args.rval());
}
bool
js::FlatStringSearch(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(args[0].isString());
MOZ_ASSERT(args[1].isString());
#ifdef DEBUG
bool isOptimizable = false;
if (!CallIsStringOptimizable(cx, "IsStringSearchOptimizable", &isOptimizable))
return false;
MOZ_ASSERT(isOptimizable);
#endif
RootedString str(cx,args[0].toString());
RootedString pattern(cx, args[1].toString());
bool isFlat = false;
int32_t match = 0;
if (!FlatStringMatchHelper(cx, str, pattern, &isFlat, &match))
return false;
if (!isFlat) {
args.rval().setInt32(-2);
return true;
}
args.rval().setInt32(match);
return true;
}
|