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
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cstdlib>
#include <memory>
#include <sstream>
#include "include/v8.h"
#include "src/api/api-inl.h"
#include "src/ast/ast.h"
#include "src/codegen/assembler-arch.h"
#include "src/codegen/macro-assembler.h"
#include "src/init/v8.h"
#include "src/objects/js-regexp-inl.h"
#include "src/objects/objects-inl.h"
#include "src/regexp/regexp-bytecode-generator.h"
#include "src/regexp/regexp-bytecodes.h"
#include "src/regexp/regexp-compiler.h"
#include "src/regexp/regexp-interpreter.h"
#include "src/regexp/regexp-macro-assembler-arch.h"
#include "src/regexp/regexp-parser.h"
#include "src/regexp/regexp.h"
#include "src/strings/char-predicates-inl.h"
#include "src/strings/string-stream.h"
#include "src/strings/unicode-inl.h"
#include "src/utils/ostreams.h"
#include "src/zone/zone-list-inl.h"
#include "test/cctest/cctest.h"
#include "test/common/flag-utils.h"
namespace v8 {
namespace internal {
namespace test_regexp {
static bool CheckParse(const char* input) {
Isolate* isolate = CcTest::i_isolate();
v8::HandleScope scope(CcTest::isolate());
Zone zone(isolate->allocator(), ZONE_NAME);
Handle<String> str = isolate->factory()->NewStringFromAsciiChecked(input);
FlatStringReader reader(isolate, str);
RegExpCompileData result;
return v8::internal::RegExpParser::ParseRegExp(isolate, &zone, &reader,
JSRegExp::kNone, &result);
}
static void CheckParseEq(const char* input, const char* expected,
bool unicode = false) {
Isolate* isolate = CcTest::i_isolate();
v8::HandleScope scope(CcTest::isolate());
Zone zone(isolate->allocator(), ZONE_NAME);
Handle<String> str = isolate->factory()->NewStringFromAsciiChecked(input);
FlatStringReader reader(isolate, str);
RegExpCompileData result;
JSRegExp::Flags flags = JSRegExp::kNone;
if (unicode) flags |= JSRegExp::kUnicode;
CHECK(v8::internal::RegExpParser::ParseRegExp(isolate, &zone, &reader, flags,
&result));
CHECK_NOT_NULL(result.tree);
CHECK(result.error == RegExpError::kNone);
std::ostringstream os;
result.tree->Print(os, &zone);
if (strcmp(expected, os.str().c_str()) != 0) {
printf("%s | %s\n", expected, os.str().c_str());
}
CHECK_EQ(0, strcmp(expected, os.str().c_str()));
}
static bool CheckSimple(const char* input) {
Isolate* isolate = CcTest::i_isolate();
v8::HandleScope scope(CcTest::isolate());
Zone zone(isolate->allocator(), ZONE_NAME);
Handle<String> str = isolate->factory()->NewStringFromAsciiChecked(input);
FlatStringReader reader(isolate, str);
RegExpCompileData result;
CHECK(v8::internal::RegExpParser::ParseRegExp(isolate, &zone, &reader,
JSRegExp::kNone, &result));
CHECK_NOT_NULL(result.tree);
CHECK(result.error == RegExpError::kNone);
return result.simple;
}
struct MinMaxPair {
int min_match;
int max_match;
};
static MinMaxPair CheckMinMaxMatch(const char* input) {
Isolate* isolate = CcTest::i_isolate();
v8::HandleScope scope(CcTest::isolate());
Zone zone(isolate->allocator(), ZONE_NAME);
Handle<String> str = isolate->factory()->NewStringFromAsciiChecked(input);
FlatStringReader reader(isolate, str);
RegExpCompileData result;
CHECK(v8::internal::RegExpParser::ParseRegExp(isolate, &zone, &reader,
JSRegExp::kNone, &result));
CHECK_NOT_NULL(result.tree);
CHECK(result.error == RegExpError::kNone);
int min_match = result.tree->min_match();
int max_match = result.tree->max_match();
MinMaxPair pair = {min_match, max_match};
return pair;
}
#define CHECK_PARSE_ERROR(input) CHECK(!CheckParse(input))
#define CHECK_SIMPLE(input, simple) CHECK_EQ(simple, CheckSimple(input));
#define CHECK_MIN_MAX(input, min, max) \
{ \
MinMaxPair min_max = CheckMinMaxMatch(input); \
CHECK_EQ(min, min_max.min_match); \
CHECK_EQ(max, min_max.max_match); \
}
TEST(RegExpParser) {
CHECK_PARSE_ERROR("?");
CheckParseEq("abc", "'abc'");
CheckParseEq("", "%");
CheckParseEq("abc|def", "(| 'abc' 'def')");
CheckParseEq("abc|def|ghi", "(| 'abc' 'def' 'ghi')");
CheckParseEq("^xxx$", "(: @^i 'xxx' @$i)");
CheckParseEq("ab\\b\\d\\bcd", "(: 'ab' @b [0-9] @b 'cd')");
CheckParseEq("\\w|\\d", "(| [0-9 A-Z _ a-z] [0-9])");
CheckParseEq("a*", "(# 0 - g 'a')");
CheckParseEq("a*?", "(# 0 - n 'a')");
CheckParseEq("abc+", "(: 'ab' (# 1 - g 'c'))");
CheckParseEq("abc+?", "(: 'ab' (# 1 - n 'c'))");
CheckParseEq("xyz?", "(: 'xy' (# 0 1 g 'z'))");
CheckParseEq("xyz??", "(: 'xy' (# 0 1 n 'z'))");
CheckParseEq("xyz{0,1}", "(: 'xy' (# 0 1 g 'z'))");
CheckParseEq("xyz{0,1}?", "(: 'xy' (# 0 1 n 'z'))");
CheckParseEq("xyz{93}", "(: 'xy' (# 93 93 g 'z'))");
CheckParseEq("xyz{93}?", "(: 'xy' (# 93 93 n 'z'))");
CheckParseEq("xyz{1,32}", "(: 'xy' (# 1 32 g 'z'))");
CheckParseEq("xyz{1,32}?", "(: 'xy' (# 1 32 n 'z'))");
CheckParseEq("xyz{1,}", "(: 'xy' (# 1 - g 'z'))");
CheckParseEq("xyz{1,}?", "(: 'xy' (# 1 - n 'z'))");
CheckParseEq("a\\fb\\nc\\rd\\te\\vf", "'a\\x0cb\\x0ac\\x0dd\\x09e\\x0bf'");
CheckParseEq("a\\nb\\bc", "(: 'a\\x0ab' @b 'c')");
CheckParseEq("(?:foo)", "(?: 'foo')");
CheckParseEq("(?: foo )", "(?: ' foo ')");
CheckParseEq("(foo|bar|baz)", "(^ (| 'foo' 'bar' 'baz'))");
CheckParseEq("foo|(bar|baz)|quux", "(| 'foo' (^ (| 'bar' 'baz')) 'quux')");
CheckParseEq("foo(?=bar)baz", "(: 'foo' (-> + 'bar') 'baz')");
CheckParseEq("foo(?!bar)baz", "(: 'foo' (-> - 'bar') 'baz')");
CheckParseEq("foo(?<=bar)baz", "(: 'foo' (<- + 'bar') 'baz')");
CheckParseEq("foo(?<!bar)baz", "(: 'foo' (<- - 'bar') 'baz')");
CheckParseEq("()", "(^ %)");
CheckParseEq("(?=)", "(-> + %)");
CheckParseEq("[]", "^[\\x00-\\u{10ffff}]"); // Doesn't compile on windows
CheckParseEq("[^]", "[\\x00-\\u{10ffff}]"); // \uffff isn't in codepage 1252
CheckParseEq("[x]", "[x]");
CheckParseEq("[xyz]", "[x y z]");
CheckParseEq("[a-zA-Z0-9]", "[a-z A-Z 0-9]");
CheckParseEq("[-123]", "[- 1 2 3]");
CheckParseEq("[^123]", "^[1 2 3]");
CheckParseEq("]", "']'");
CheckParseEq("}", "'}'");
CheckParseEq("[a-b-c]", "[a-b - c]");
CheckParseEq("[\\d]", "[0-9]");
CheckParseEq("[x\\dz]", "[x 0-9 z]");
CheckParseEq("[\\d-z]", "[0-9 - z]");
CheckParseEq("[\\d-\\d]", "[0-9 0-9 -]");
CheckParseEq("[z-\\d]", "[0-9 z -]");
// Control character outside character class.
CheckParseEq("\\cj\\cJ\\ci\\cI\\ck\\cK", "'\\x0a\\x0a\\x09\\x09\\x0b\\x0b'");
CheckParseEq("\\c!", "'\\c!'");
CheckParseEq("\\c_", "'\\c_'");
CheckParseEq("\\c~", "'\\c~'");
CheckParseEq("\\c1", "'\\c1'");
// Control character inside character class.
CheckParseEq("[\\c!]", "[\\ c !]");
CheckParseEq("[\\c_]", "[\\x1f]");
CheckParseEq("[\\c~]", "[\\ c ~]");
CheckParseEq("[\\ca]", "[\\x01]");
CheckParseEq("[\\cz]", "[\\x1a]");
CheckParseEq("[\\cA]", "[\\x01]");
CheckParseEq("[\\cZ]", "[\\x1a]");
CheckParseEq("[\\c1]", "[\\x11]");
CheckParseEq("[a\\]c]", "[a ] c]");
CheckParseEq("\\[\\]\\{\\}\\(\\)\\%\\^\\#\\ ", "'[]{}()%^# '");
CheckParseEq("[\\[\\]\\{\\}\\(\\)\\%\\^\\#\\ ]", "[[ ] { } ( ) % ^ # ]");
CheckParseEq("\\0", "'\\x00'");
CheckParseEq("\\8", "'8'");
CheckParseEq("\\9", "'9'");
CheckParseEq("\\11", "'\\x09'");
CheckParseEq("\\11a", "'\\x09a'");
CheckParseEq("\\011", "'\\x09'");
CheckParseEq("\\00011", "'\\x0011'");
CheckParseEq("\\118", "'\\x098'");
CheckParseEq("\\111", "'I'");
CheckParseEq("\\1111", "'I1'");
CheckParseEq("(x)(x)(x)\\1", "(: (^ 'x') (^ 'x') (^ 'x') (<- 1))");
CheckParseEq("(x)(x)(x)\\2", "(: (^ 'x') (^ 'x') (^ 'x') (<- 2))");
CheckParseEq("(x)(x)(x)\\3", "(: (^ 'x') (^ 'x') (^ 'x') (<- 3))");
CheckParseEq("(x)(x)(x)\\4", "(: (^ 'x') (^ 'x') (^ 'x') '\\x04')");
CheckParseEq("(x)(x)(x)\\1*",
"(: (^ 'x') (^ 'x') (^ 'x')"
" (# 0 - g (<- 1)))");
CheckParseEq("(x)(x)(x)\\2*",
"(: (^ 'x') (^ 'x') (^ 'x')"
" (# 0 - g (<- 2)))");
CheckParseEq("(x)(x)(x)\\3*",
"(: (^ 'x') (^ 'x') (^ 'x')"
" (# 0 - g (<- 3)))");
CheckParseEq("(x)(x)(x)\\4*",
"(: (^ 'x') (^ 'x') (^ 'x')"
" (# 0 - g '\\x04'))");
CheckParseEq("(x)(x)(x)(x)(x)(x)(x)(x)(x)(x)\\10",
"(: (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x')"
" (^ 'x') (^ 'x') (^ 'x') (^ 'x') (<- 10))");
CheckParseEq("(x)(x)(x)(x)(x)(x)(x)(x)(x)(x)\\11",
"(: (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x') (^ 'x')"
" (^ 'x') (^ 'x') (^ 'x') (^ 'x') '\\x09')");
CheckParseEq("(a)\\1", "(: (^ 'a') (<- 1))");
CheckParseEq("(a\\1)", "(^ 'a')");
CheckParseEq("(\\1a)", "(^ 'a')");
CheckParseEq("(\\2)(\\1)", "(: (^ (<- 2)) (^ (<- 1)))");
CheckParseEq("(?=a)?a", "'a'");
CheckParseEq("(?=a){0,10}a", "'a'");
CheckParseEq("(?=a){1,10}a", "(: (-> + 'a') 'a')");
CheckParseEq("(?=a){9,10}a", "(: (-> + 'a') 'a')");
CheckParseEq("(?!a)?a", "'a'");
CheckParseEq("\\1(a)", "(: (<- 1) (^ 'a'))");
CheckParseEq("(?!(a))\\1", "(: (-> - (^ 'a')) (<- 1))");
CheckParseEq("(?!\\1(a\\1)\\1)\\1",
"(: (-> - (: (<- 1) (^ 'a') (<- 1))) (<- 1))");
CheckParseEq("\\1\\2(a(?:\\1(b\\1\\2))\\2)\\1",
"(: (<- 1) (<- 2) (^ (: 'a' (?: (^ 'b')) (<- 2))) (<- 1))");
CheckParseEq("\\1\\2(a(?<=\\1(b\\1\\2))\\2)\\1",
"(: (<- 1) (<- 2) (^ (: 'a' (<- + (^ 'b')) (<- 2))) (<- 1))");
CheckParseEq("[\\0]", "[\\x00]");
CheckParseEq("[\\11]", "[\\x09]");
CheckParseEq("[\\11a]", "[\\x09 a]");
CheckParseEq("[\\011]", "[\\x09]");
CheckParseEq("[\\00011]", "[\\x00 1 1]");
CheckParseEq("[\\118]", "[\\x09 8]");
CheckParseEq("[\\111]", "[I]");
CheckParseEq("[\\1111]", "[I 1]");
CheckParseEq("\\x34", "'\x34'");
CheckParseEq("\\x60", "'\x60'");
CheckParseEq("\\x3z", "'x3z'");
CheckParseEq("\\c", "'\\c'");
CheckParseEq("\\u0034", "'\x34'");
CheckParseEq("\\u003z", "'u003z'");
CheckParseEq("foo[z]*", "(: 'foo' (# 0 - g [z]))");
CheckParseEq("^^^$$$\\b\\b\\b\\b", "(: @^i @^i @^i @$i @$i @$i @b @b @b @b)");
CheckParseEq("\\b\\b\\b\\b\\B\\B\\B\\B\\b\\b\\b\\b",
"(: @b @b @b @b @B @B @B @B @b @b @b @b)");
CheckParseEq("\\b\\B\\b", "(: @b @B @b)");
// Unicode regexps
CheckParseEq("\\u{12345}", "'\\ud808\\udf45'", true);
CheckParseEq("\\u{12345}\\u{23456}", "(! '\\ud808\\udf45' '\\ud84d\\udc56')",
true);
CheckParseEq("\\u{12345}|\\u{23456}", "(| '\\ud808\\udf45' '\\ud84d\\udc56')",
true);
CheckParseEq("\\u{12345}{3}", "(# 3 3 g '\\ud808\\udf45')", true);
CheckParseEq("\\u{12345}*", "(# 0 - g '\\ud808\\udf45')", true);
CheckParseEq("\\ud808\\udf45*", "(# 0 - g '\\ud808\\udf45')", true);
CheckParseEq("[\\ud808\\udf45-\\ud809\\udccc]", "[\\u{012345}-\\u{0124cc}]",
true);
CHECK_SIMPLE("", false);
CHECK_SIMPLE("a", true);
CHECK_SIMPLE("a|b", false);
CHECK_SIMPLE("a\\n", false);
CHECK_SIMPLE("^a", false);
CHECK_SIMPLE("a$", false);
CHECK_SIMPLE("a\\b!", false);
CHECK_SIMPLE("a\\Bb", false);
CHECK_SIMPLE("a*", false);
CHECK_SIMPLE("a*?", false);
CHECK_SIMPLE("a?", false);
CHECK_SIMPLE("a??", false);
CHECK_SIMPLE("a{0,1}?", false);
CHECK_SIMPLE("a{1,1}?", false);
CHECK_SIMPLE("a{1,2}?", false);
CHECK_SIMPLE("a+?", false);
CHECK_SIMPLE("(a)", false);
CHECK_SIMPLE("(a)\\1", false);
CHECK_SIMPLE("(\\1a)", false);
CHECK_SIMPLE("\\1(a)", false);
CHECK_SIMPLE("a\\s", false);
CHECK_SIMPLE("a\\S", false);
CHECK_SIMPLE("a\\d", false);
CHECK_SIMPLE("a\\D", false);
CHECK_SIMPLE("a\\w", false);
CHECK_SIMPLE("a\\W", false);
CHECK_SIMPLE("a.", false);
CHECK_SIMPLE("a\\q", false);
CHECK_SIMPLE("a[a]", false);
CHECK_SIMPLE("a[^a]", false);
CHECK_SIMPLE("a[a-z]", false);
CHECK_SIMPLE("a[\\q]", false);
CHECK_SIMPLE("a(?:b)", false);
CHECK_SIMPLE("a(?=b)", false);
CHECK_SIMPLE("a(?!b)", false);
CHECK_SIMPLE("\\x60", false);
CHECK_SIMPLE("\\u0060", false);
CHECK_SIMPLE("\\cA", false);
CHECK_SIMPLE("\\q", false);
CHECK_SIMPLE("\\1112", false);
CHECK_SIMPLE("\\0", false);
CHECK_SIMPLE("(a)\\1", false);
CHECK_SIMPLE("(?=a)?a", false);
CHECK_SIMPLE("(?!a)?a\\1", false);
CHECK_SIMPLE("(?:(?=a))a\\1", false);
CheckParseEq("a{}", "'a{}'");
CheckParseEq("a{,}", "'a{,}'");
CheckParseEq("a{", "'a{'");
CheckParseEq("a{z}", "'a{z}'");
CheckParseEq("a{1z}", "'a{1z}'");
CheckParseEq("a{12z}", "'a{12z}'");
CheckParseEq("a{12,", "'a{12,'");
CheckParseEq("a{12,3b", "'a{12,3b'");
CheckParseEq("{}", "'{}'");
CheckParseEq("{,}", "'{,}'");
CheckParseEq("{", "'{'");
CheckParseEq("{z}", "'{z}'");
CheckParseEq("{1z}", "'{1z}'");
CheckParseEq("{12z}", "'{12z}'");
CheckParseEq("{12,", "'{12,'");
CheckParseEq("{12,3b", "'{12,3b'");
CHECK_MIN_MAX("a", 1, 1);
CHECK_MIN_MAX("abc", 3, 3);
CHECK_MIN_MAX("a[bc]d", 3, 3);
CHECK_MIN_MAX("a|bc", 1, 2);
CHECK_MIN_MAX("ab|c", 1, 2);
CHECK_MIN_MAX("a||bc", 0, 2);
CHECK_MIN_MAX("|", 0, 0);
CHECK_MIN_MAX("(?:ab)", 2, 2);
CHECK_MIN_MAX("(?:ab|cde)", 2, 3);
CHECK_MIN_MAX("(?:ab)|cde", 2, 3);
CHECK_MIN_MAX("(ab)", 2, 2);
CHECK_MIN_MAX("(ab|cde)", 2, 3);
CHECK_MIN_MAX("(ab)\\1", 2, RegExpTree::kInfinity);
CHECK_MIN_MAX("(ab|cde)\\1", 2, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:ab)?", 0, 2);
CHECK_MIN_MAX("(?:ab)*", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:ab)+", 2, RegExpTree::kInfinity);
CHECK_MIN_MAX("a?", 0, 1);
CHECK_MIN_MAX("a*", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("a+", 1, RegExpTree::kInfinity);
CHECK_MIN_MAX("a??", 0, 1);
CHECK_MIN_MAX("a*?", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("a+?", 1, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a?)?", 0, 1);
CHECK_MIN_MAX("(?:a*)?", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a+)?", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a?)+", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a*)+", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a+)+", 1, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a?)*", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a*)*", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a+)*", 0, RegExpTree::kInfinity);
CHECK_MIN_MAX("a{0}", 0, 0);
CHECK_MIN_MAX("(?:a+){0}", 0, 0);
CHECK_MIN_MAX("(?:a+){0,0}", 0, 0);
CHECK_MIN_MAX("a*b", 1, RegExpTree::kInfinity);
CHECK_MIN_MAX("a+b", 2, RegExpTree::kInfinity);
CHECK_MIN_MAX("a*b|c", 1, RegExpTree::kInfinity);
CHECK_MIN_MAX("a+b|c", 1, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:a{5,1000000}){3,1000000}", 15, RegExpTree::kInfinity);
CHECK_MIN_MAX("(?:ab){4,7}", 8, 14);
CHECK_MIN_MAX("a\\bc", 2, 2);
CHECK_MIN_MAX("a\\Bc", 2, 2);
CHECK_MIN_MAX("a\\sc", 3, 3);
CHECK_MIN_MAX("a\\Sc", 3, 3);
CHECK_MIN_MAX("a(?=b)c", 2, 2);
CHECK_MIN_MAX("a(?=bbb|bb)c", 2, 2);
CHECK_MIN_MAX("a(?!bbb|bb)c", 2, 2);
CheckParseEq("(?<a>x)(?<b>x)(?<c>x)\\k<a>",
"(: (^ 'x') (^ 'x') (^ 'x') (<- 1))", true);
CheckParseEq("(?<a>x)(?<b>x)(?<c>x)\\k<b>",
"(: (^ 'x') (^ 'x') (^ 'x') (<- 2))", true);
CheckParseEq("(?<a>x)(?<b>x)(?<c>x)\\k<c>",
"(: (^ 'x') (^ 'x') (^ 'x') (<- 3))", true);
CheckParseEq("(?<a>a)\\k<a>", "(: (^ 'a') (<- 1))", true);
CheckParseEq("(?<a>a\\k<a>)", "(^ 'a')", true);
CheckParseEq("(?<a>\\k<a>a)", "(^ 'a')", true);
CheckParseEq("(?<a>\\k<b>)(?<b>\\k<a>)", "(: (^ (<- 2)) (^ (<- 1)))", true);
CheckParseEq("\\k<a>(?<a>a)", "(: (<- 1) (^ 'a'))", true);
CheckParseEq("(?<\\u{03C0}>a)", "(^ 'a')", true);
CheckParseEq("(?<\\u03C0>a)", "(^ 'a')", true);
}
TEST(ParserRegression) {
CheckParseEq("[A-Z$-][x]", "(! [A-Z $ -] [x])");
CheckParseEq("a{3,4*}", "(: 'a{3,' (# 0 - g '4') '}')");
CheckParseEq("{", "'{'");
CheckParseEq("a|", "(| 'a' %)");
}
static void ExpectError(const char* input, const char* expected,
bool unicode = false) {
Isolate* isolate = CcTest::i_isolate();
v8::HandleScope scope(CcTest::isolate());
Zone zone(isolate->allocator(), ZONE_NAME);
Handle<String> str = isolate->factory()->NewStringFromAsciiChecked(input);
FlatStringReader reader(isolate, str);
RegExpCompileData result;
JSRegExp::Flags flags = JSRegExp::kNone;
if (unicode) flags |= JSRegExp::kUnicode;
CHECK(!v8::internal::RegExpParser::ParseRegExp(isolate, &zone, &reader, flags,
&result));
CHECK_NULL(result.tree);
CHECK(result.error != RegExpError::kNone);
CHECK_EQ(0, strcmp(expected, RegExpErrorString(result.error)));
}
TEST(Errors) {
const char* kEndBackslash = "\\ at end of pattern";
ExpectError("\\", kEndBackslash);
const char* kUnterminatedGroup = "Unterminated group";
ExpectError("(foo", kUnterminatedGroup);
const char* kInvalidGroup = "Invalid group";
ExpectError("(?", kInvalidGroup);
const char* kUnterminatedCharacterClass = "Unterminated character class";
ExpectError("[", kUnterminatedCharacterClass);
ExpectError("[a-", kUnterminatedCharacterClass);
const char* kNothingToRepeat = "Nothing to repeat";
ExpectError("*", kNothingToRepeat);
ExpectError("?", kNothingToRepeat);
ExpectError("+", kNothingToRepeat);
ExpectError("{1}", kNothingToRepeat);
ExpectError("{1,2}", kNothingToRepeat);
ExpectError("{1,}", kNothingToRepeat);
// Check that we don't allow more than kMaxCapture captures
const int kMaxCaptures = 1 << 16; // Must match RegExpParser::kMaxCaptures.
const char* kTooManyCaptures = "Too many captures";
std::ostringstream os;
for (int i = 0; i <= kMaxCaptures; i++) {
os << "()";
}
ExpectError(os.str().c_str(), kTooManyCaptures);
const char* kInvalidCaptureName = "Invalid capture group name";
ExpectError("(?<>.)", kInvalidCaptureName, true);
ExpectError("(?<1>.)", kInvalidCaptureName, true);
ExpectError("(?<_%>.)", kInvalidCaptureName, true);
ExpectError("\\k<a", kInvalidCaptureName, true);
const char* kDuplicateCaptureName = "Duplicate capture group name";
ExpectError("(?<a>.)(?<a>.)", kDuplicateCaptureName, true);
const char* kInvalidUnicodeEscape = "Invalid Unicode escape";
ExpectError("(?<\\u{FISK}", kInvalidUnicodeEscape, true);
const char* kInvalidCaptureReferenced = "Invalid named capture referenced";
ExpectError("\\k<a>", kInvalidCaptureReferenced, true);
ExpectError("(?<b>)\\k<a>", kInvalidCaptureReferenced, true);
const char* kInvalidNamedReference = "Invalid named reference";
ExpectError("\\ka", kInvalidNamedReference, true);
}
static bool IsDigit(uc32 c) { return ('0' <= c && c <= '9'); }
static bool NotDigit(uc32 c) { return !IsDigit(c); }
static bool IsWhiteSpaceOrLineTerminator(uc32 c) {
// According to ECMA 5.1, 15.10.2.12 the CharacterClassEscape \s includes
// WhiteSpace (7.2) and LineTerminator (7.3) values.
return v8::internal::IsWhiteSpaceOrLineTerminator(c);
}
static bool NotWhiteSpaceNorLineTermiantor(uc32 c) {
return !IsWhiteSpaceOrLineTerminator(c);
}
static bool NotWord(uc32 c) { return !IsRegExpWord(c); }
static bool NotLineTerminator(uc32 c) { return !unibrow::IsLineTerminator(c); }
static void TestCharacterClassEscapes(uc32 c, bool(pred)(uc32 c)) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ZoneList<CharacterRange>* ranges =
zone.New<ZoneList<CharacterRange>>(2, &zone);
CharacterRange::AddClassEscape(c, ranges, &zone);
for (uc32 i = 0; i < (1 << 16); i++) {
bool in_class = false;
for (int j = 0; !in_class && j < ranges->length(); j++) {
CharacterRange& range = ranges->at(j);
in_class = (range.from() <= i && i <= range.to());
}
CHECK_EQ(pred(i), in_class);
}
}
TEST(CharacterClassEscapes) {
TestCharacterClassEscapes('.', NotLineTerminator);
TestCharacterClassEscapes('d', IsDigit);
TestCharacterClassEscapes('D', NotDigit);
TestCharacterClassEscapes('s', IsWhiteSpaceOrLineTerminator);
TestCharacterClassEscapes('S', NotWhiteSpaceNorLineTermiantor);
TestCharacterClassEscapes('w', IsRegExpWord);
TestCharacterClassEscapes('W', NotWord);
}
static RegExpNode* Compile(const char* input, bool multiline, bool unicode,
bool is_one_byte, Zone* zone) {
Isolate* isolate = CcTest::i_isolate();
Handle<String> str = isolate->factory()->NewStringFromAsciiChecked(input);
FlatStringReader reader(isolate, str);
RegExpCompileData compile_data;
compile_data.compilation_target = RegExpCompilationTarget::kNative;
JSRegExp::Flags flags = JSRegExp::kNone;
if (multiline) flags = JSRegExp::kMultiline;
if (unicode) flags = JSRegExp::kUnicode;
if (!v8::internal::RegExpParser::ParseRegExp(isolate, zone, &reader, flags,
&compile_data))
return nullptr;
Handle<String> pattern = isolate->factory()
->NewStringFromUtf8(CStrVector(input))
.ToHandleChecked();
Handle<String> sample_subject =
isolate->factory()->NewStringFromUtf8(CStrVector("")).ToHandleChecked();
RegExp::CompileForTesting(isolate, zone, &compile_data, flags, pattern,
sample_subject, is_one_byte);
return compile_data.node;
}
static void Execute(const char* input, bool multiline, bool unicode,
bool is_one_byte, bool dot_output = false) {
v8::HandleScope scope(CcTest::isolate());
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
RegExpNode* node = Compile(input, multiline, unicode, is_one_byte, &zone);
USE(node);
#ifdef DEBUG
if (dot_output) RegExp::DotPrintForTesting(input, node);
#endif // DEBUG
}
// Test of debug-only syntax.
#ifdef DEBUG
TEST(ParsePossessiveRepetition) {
bool old_flag_value = FLAG_regexp_possessive_quantifier;
// Enable possessive quantifier syntax.
FLAG_regexp_possessive_quantifier = true;
CheckParseEq("a*+", "(# 0 - p 'a')");
CheckParseEq("a++", "(# 1 - p 'a')");
CheckParseEq("a?+", "(# 0 1 p 'a')");
CheckParseEq("a{10,20}+", "(# 10 20 p 'a')");
CheckParseEq("za{10,20}+b", "(: 'z' (# 10 20 p 'a') 'b')");
// Disable possessive quantifier syntax.
FLAG_regexp_possessive_quantifier = false;
CHECK_PARSE_ERROR("a*+");
CHECK_PARSE_ERROR("a++");
CHECK_PARSE_ERROR("a?+");
CHECK_PARSE_ERROR("a{10,20}+");
CHECK_PARSE_ERROR("a{10,20}+b");
FLAG_regexp_possessive_quantifier = old_flag_value;
}
#endif
// Tests of interpreter.
#if V8_TARGET_ARCH_IA32
using ArchRegExpMacroAssembler = RegExpMacroAssemblerIA32;
#elif V8_TARGET_ARCH_X64
using ArchRegExpMacroAssembler = RegExpMacroAssemblerX64;
#elif V8_TARGET_ARCH_ARM
using ArchRegExpMacroAssembler = RegExpMacroAssemblerARM;
#elif V8_TARGET_ARCH_ARM64
using ArchRegExpMacroAssembler = RegExpMacroAssemblerARM64;
#elif V8_TARGET_ARCH_S390
using ArchRegExpMacroAssembler = RegExpMacroAssemblerS390;
#elif V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_PPC64
using ArchRegExpMacroAssembler = RegExpMacroAssemblerPPC;
#elif V8_TARGET_ARCH_MIPS
using ArchRegExpMacroAssembler = RegExpMacroAssemblerMIPS;
#elif V8_TARGET_ARCH_MIPS64
using ArchRegExpMacroAssembler = RegExpMacroAssemblerMIPS;
#elif V8_TARGET_ARCH_X87
using ArchRegExpMacroAssembler = RegExpMacroAssemblerX87;
#elif V8_TARGET_ARCH_RISCV64
using ArchRegExpMacroAssembler = RegExpMacroAssemblerRISCV;
#endif
class ContextInitializer {
public:
ContextInitializer()
: scope_(CcTest::isolate()), env_(v8::Context::New(CcTest::isolate())) {
env_->Enter();
}
~ContextInitializer() { env_->Exit(); }
private:
v8::HandleScope scope_;
v8::Local<v8::Context> env_;
};
// Create new JSRegExp object with only necessary fields (for this tests)
// initialized.
static Handle<JSRegExp> CreateJSRegExp(Handle<String> source, Handle<Code> code,
bool is_unicode = false) {
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Handle<JSFunction> constructor = isolate->regexp_function();
Handle<JSRegExp> regexp =
Handle<JSRegExp>::cast(factory->NewJSObject(constructor));
factory->SetRegExpIrregexpData(regexp, source, JSRegExp::kNone, 0,
JSRegExp::kNoBacktrackLimit);
regexp->SetDataAt(is_unicode ? JSRegExp::kIrregexpUC16CodeIndex
: JSRegExp::kIrregexpLatin1CodeIndex,
*code);
return regexp;
}
static ArchRegExpMacroAssembler::Result Execute(JSRegExp regexp, String input,
int start_offset,
Address input_start,
Address input_end,
int* captures) {
return static_cast<NativeRegExpMacroAssembler::Result>(
NativeRegExpMacroAssembler::Execute(
input, start_offset, reinterpret_cast<byte*>(input_start),
reinterpret_cast<byte*>(input_end), captures, 0, CcTest::i_isolate(),
regexp));
}
TEST(MacroAssemblerNativeSuccess) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
4);
m.Succeed();
Handle<String> source = factory->NewStringFromStaticChars("");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
int captures[4] = {42, 37, 87, 117};
Handle<String> input = factory->NewStringFromStaticChars("foofoo");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + seq_input->length(), captures);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(-1, captures[0]);
CHECK_EQ(-1, captures[1]);
CHECK_EQ(-1, captures[2]);
CHECK_EQ(-1, captures[3]);
}
TEST(MacroAssemblerNativeSimple) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
4);
Label fail, backtrack;
m.PushBacktrack(&fail);
m.CheckNotAtStart(0, nullptr);
m.LoadCurrentCharacter(2, nullptr);
m.CheckNotCharacter('o', nullptr);
m.LoadCurrentCharacter(1, nullptr, false);
m.CheckNotCharacter('o', nullptr);
m.LoadCurrentCharacter(0, nullptr, false);
m.CheckNotCharacter('f', nullptr);
m.WriteCurrentPositionToRegister(0, 0);
m.WriteCurrentPositionToRegister(1, 3);
m.AdvanceCurrentPosition(3);
m.PushBacktrack(&backtrack);
m.Succeed();
m.BindJumpTarget(&backtrack);
m.Backtrack();
m.BindJumpTarget(&fail);
m.Fail();
Handle<String> source = factory->NewStringFromStaticChars("^foo");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
int captures[4] = {42, 37, 87, 117};
Handle<String> input = factory->NewStringFromStaticChars("foofoo");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), captures);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, captures[0]);
CHECK_EQ(3, captures[1]);
CHECK_EQ(-1, captures[2]);
CHECK_EQ(-1, captures[3]);
input = factory->NewStringFromStaticChars("barbarbar");
seq_input = Handle<SeqOneByteString>::cast(input);
start_adr = seq_input->GetCharsAddress();
result = Execute(*regexp, *input, 0, start_adr, start_adr + input->length(),
captures);
CHECK_EQ(NativeRegExpMacroAssembler::FAILURE, result);
}
TEST(MacroAssemblerNativeSimpleUC16) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::UC16,
4);
Label fail, backtrack;
m.PushBacktrack(&fail);
m.CheckNotAtStart(0, nullptr);
m.LoadCurrentCharacter(2, nullptr);
m.CheckNotCharacter('o', nullptr);
m.LoadCurrentCharacter(1, nullptr, false);
m.CheckNotCharacter('o', nullptr);
m.LoadCurrentCharacter(0, nullptr, false);
m.CheckNotCharacter('f', nullptr);
m.WriteCurrentPositionToRegister(0, 0);
m.WriteCurrentPositionToRegister(1, 3);
m.AdvanceCurrentPosition(3);
m.PushBacktrack(&backtrack);
m.Succeed();
m.BindJumpTarget(&backtrack);
m.Backtrack();
m.BindJumpTarget(&fail);
m.Fail();
Handle<String> source = factory->NewStringFromStaticChars("^foo");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code, true);
int captures[4] = {42, 37, 87, 117};
const uc16 input_data[6] = {'f', 'o', 'o',
'f', 'o', static_cast<uc16>(0x2603)};
Handle<String> input =
factory->NewStringFromTwoByte(Vector<const uc16>(input_data, 6))
.ToHandleChecked();
Handle<SeqTwoByteString> seq_input = Handle<SeqTwoByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), captures);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, captures[0]);
CHECK_EQ(3, captures[1]);
CHECK_EQ(-1, captures[2]);
CHECK_EQ(-1, captures[3]);
const uc16 input_data2[9] = {
'b', 'a', 'r', 'b', 'a', 'r', 'b', 'a', static_cast<uc16>(0x2603)};
input = factory->NewStringFromTwoByte(Vector<const uc16>(input_data2, 9))
.ToHandleChecked();
seq_input = Handle<SeqTwoByteString>::cast(input);
start_adr = seq_input->GetCharsAddress();
result = Execute(*regexp, *input, 0, start_adr,
start_adr + input->length() * 2, captures);
CHECK_EQ(NativeRegExpMacroAssembler::FAILURE, result);
}
TEST(MacroAssemblerNativeBacktrack) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
0);
Label fail;
Label backtrack;
m.LoadCurrentCharacter(10, &fail);
m.Succeed();
m.BindJumpTarget(&fail);
m.PushBacktrack(&backtrack);
m.LoadCurrentCharacter(10, nullptr);
m.Succeed();
m.BindJumpTarget(&backtrack);
m.Fail();
Handle<String> source = factory->NewStringFromStaticChars("..........");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
Handle<String> input = factory->NewStringFromStaticChars("foofoo");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), nullptr);
CHECK_EQ(NativeRegExpMacroAssembler::FAILURE, result);
}
TEST(MacroAssemblerNativeBackReferenceLATIN1) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
4);
m.WriteCurrentPositionToRegister(0, 0);
m.AdvanceCurrentPosition(2);
m.WriteCurrentPositionToRegister(1, 0);
Label nomatch;
m.CheckNotBackReference(0, false, &nomatch);
m.Fail();
m.Bind(&nomatch);
m.AdvanceCurrentPosition(2);
Label missing_match;
m.CheckNotBackReference(0, false, &missing_match);
m.WriteCurrentPositionToRegister(2, 0);
m.Succeed();
m.Bind(&missing_match);
m.Fail();
Handle<String> source = factory->NewStringFromStaticChars("^(..)..\1");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
Handle<String> input = factory->NewStringFromStaticChars("fooofo");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
int output[4];
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), output);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, output[0]);
CHECK_EQ(2, output[1]);
CHECK_EQ(6, output[2]);
CHECK_EQ(-1, output[3]);
}
TEST(MacroAssemblerNativeBackReferenceUC16) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::UC16,
4);
m.WriteCurrentPositionToRegister(0, 0);
m.AdvanceCurrentPosition(2);
m.WriteCurrentPositionToRegister(1, 0);
Label nomatch;
m.CheckNotBackReference(0, false, &nomatch);
m.Fail();
m.Bind(&nomatch);
m.AdvanceCurrentPosition(2);
Label missing_match;
m.CheckNotBackReference(0, false, &missing_match);
m.WriteCurrentPositionToRegister(2, 0);
m.Succeed();
m.Bind(&missing_match);
m.Fail();
Handle<String> source = factory->NewStringFromStaticChars("^(..)..\1");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code, true);
const uc16 input_data[6] = {'f', 0x2028, 'o', 'o', 'f', 0x2028};
Handle<String> input =
factory->NewStringFromTwoByte(Vector<const uc16>(input_data, 6))
.ToHandleChecked();
Handle<SeqTwoByteString> seq_input = Handle<SeqTwoByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
int output[4];
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length() * 2, output);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, output[0]);
CHECK_EQ(2, output[1]);
CHECK_EQ(6, output[2]);
CHECK_EQ(-1, output[3]);
}
TEST(MacroAssemblernativeAtStart) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
0);
Label not_at_start, newline, fail;
m.CheckNotAtStart(0, ¬_at_start);
// Check that prevchar = '\n' and current = 'f'.
m.CheckCharacter('\n', &newline);
m.BindJumpTarget(&fail);
m.Fail();
m.Bind(&newline);
m.LoadCurrentCharacter(0, &fail);
m.CheckNotCharacter('f', &fail);
m.Succeed();
m.Bind(¬_at_start);
// Check that prevchar = 'o' and current = 'b'.
Label prevo;
m.CheckCharacter('o', &prevo);
m.Fail();
m.Bind(&prevo);
m.LoadCurrentCharacter(0, &fail);
m.CheckNotCharacter('b', &fail);
m.Succeed();
Handle<String> source = factory->NewStringFromStaticChars("(^f|ob)");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
Handle<String> input = factory->NewStringFromStaticChars("foobar");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), nullptr);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
result = Execute(*regexp, *input, 3, start_adr + 3,
start_adr + input->length(), nullptr);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
}
TEST(MacroAssemblerNativeBackRefNoCase) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
4);
Label fail, succ;
m.WriteCurrentPositionToRegister(0, 0);
m.WriteCurrentPositionToRegister(2, 0);
m.AdvanceCurrentPosition(3);
m.WriteCurrentPositionToRegister(3, 0);
m.CheckNotBackReferenceIgnoreCase(2, false, false, &fail); // Match "AbC".
m.CheckNotBackReferenceIgnoreCase(2, false, false, &fail); // Match "ABC".
Label expected_fail;
m.CheckNotBackReferenceIgnoreCase(2, false, false, &expected_fail);
m.BindJumpTarget(&fail);
m.Fail();
m.Bind(&expected_fail);
m.AdvanceCurrentPosition(3); // Skip "xYz"
m.CheckNotBackReferenceIgnoreCase(2, false, false, &succ);
m.Fail();
m.Bind(&succ);
m.WriteCurrentPositionToRegister(1, 0);
m.Succeed();
Handle<String> source =
factory->NewStringFromStaticChars("^(abc)\1\1(?!\1)...(?!\1)");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
Handle<String> input = factory->NewStringFromStaticChars("aBcAbCABCxYzab");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
int output[4];
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), output);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, output[0]);
CHECK_EQ(12, output[1]);
CHECK_EQ(0, output[2]);
CHECK_EQ(3, output[3]);
}
TEST(MacroAssemblerNativeRegisters) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
6);
uc16 foo_chars[3] = {'f', 'o', 'o'};
Vector<const uc16> foo(foo_chars, 3);
enum registers { out1, out2, out3, out4, out5, out6, sp, loop_cnt };
Label fail;
Label backtrack;
m.WriteCurrentPositionToRegister(out1, 0); // Output: [0]
m.PushRegister(out1, RegExpMacroAssembler::kNoStackLimitCheck);
m.PushBacktrack(&backtrack);
m.WriteStackPointerToRegister(sp);
// Fill stack and registers
m.AdvanceCurrentPosition(2);
m.WriteCurrentPositionToRegister(out1, 0);
m.PushRegister(out1, RegExpMacroAssembler::kNoStackLimitCheck);
m.PushBacktrack(&fail);
// Drop backtrack stack frames.
m.ReadStackPointerFromRegister(sp);
// And take the first backtrack (to &backtrack)
m.Backtrack();
m.PushCurrentPosition();
m.AdvanceCurrentPosition(2);
m.PopCurrentPosition();
m.BindJumpTarget(&backtrack);
m.PopRegister(out1);
m.ReadCurrentPositionFromRegister(out1);
m.AdvanceCurrentPosition(3);
m.WriteCurrentPositionToRegister(out2, 0); // [0,3]
Label loop;
m.SetRegister(loop_cnt, 0); // loop counter
m.Bind(&loop);
m.AdvanceRegister(loop_cnt, 1);
m.AdvanceCurrentPosition(1);
m.IfRegisterLT(loop_cnt, 3, &loop);
m.WriteCurrentPositionToRegister(out3, 0); // [0,3,6]
Label loop2;
m.SetRegister(loop_cnt, 2); // loop counter
m.Bind(&loop2);
m.AdvanceRegister(loop_cnt, -1);
m.AdvanceCurrentPosition(1);
m.IfRegisterGE(loop_cnt, 0, &loop2);
m.WriteCurrentPositionToRegister(out4, 0); // [0,3,6,9]
Label loop3;
Label exit_loop3;
m.PushRegister(out4, RegExpMacroAssembler::kNoStackLimitCheck);
m.PushRegister(out4, RegExpMacroAssembler::kNoStackLimitCheck);
m.ReadCurrentPositionFromRegister(out3);
m.Bind(&loop3);
m.AdvanceCurrentPosition(1);
m.CheckGreedyLoop(&exit_loop3);
m.GoTo(&loop3);
m.Bind(&exit_loop3);
m.PopCurrentPosition();
m.WriteCurrentPositionToRegister(out5, 0); // [0,3,6,9,9,-1]
m.Succeed();
m.BindJumpTarget(&fail);
m.Fail();
Handle<String> source = factory->NewStringFromStaticChars("<loop test>");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
// String long enough for test (content doesn't matter).
Handle<String> input = factory->NewStringFromStaticChars("foofoofoofoofoo");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
int output[6];
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), output);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, output[0]);
CHECK_EQ(3, output[1]);
CHECK_EQ(6, output[2]);
CHECK_EQ(9, output[3]);
CHECK_EQ(9, output[4]);
CHECK_EQ(-1, output[5]);
}
TEST(MacroAssemblerStackOverflow) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
0);
Label loop;
m.Bind(&loop);
m.PushBacktrack(&loop);
m.GoTo(&loop);
Handle<String> source =
factory->NewStringFromStaticChars("<stack overflow test>");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
// String long enough for test (content doesn't matter).
Handle<String> input = factory->NewStringFromStaticChars("dummy");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), nullptr);
CHECK_EQ(NativeRegExpMacroAssembler::EXCEPTION, result);
CHECK(isolate->has_pending_exception());
isolate->clear_pending_exception();
}
TEST(MacroAssemblerNativeLotsOfRegisters) {
v8::V8::Initialize();
ContextInitializer initializer;
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ArchRegExpMacroAssembler m(isolate, &zone, NativeRegExpMacroAssembler::LATIN1,
2);
// At least 2048, to ensure the allocated space for registers
// span one full page.
const int large_number = 8000;
m.WriteCurrentPositionToRegister(large_number, 42);
m.WriteCurrentPositionToRegister(0, 0);
m.WriteCurrentPositionToRegister(1, 1);
Label done;
m.CheckNotBackReference(0, false, &done); // Performs a system-stack push.
m.Bind(&done);
m.PushRegister(large_number, RegExpMacroAssembler::kNoStackLimitCheck);
m.PopRegister(1);
m.Succeed();
Handle<String> source =
factory->NewStringFromStaticChars("<huge register space test>");
Handle<Object> code_object = m.GetCode(source);
Handle<Code> code = Handle<Code>::cast(code_object);
Handle<JSRegExp> regexp = CreateJSRegExp(source, code);
// String long enough for test (content doesn't matter).
Handle<String> input = factory->NewStringFromStaticChars("sample text");
Handle<SeqOneByteString> seq_input = Handle<SeqOneByteString>::cast(input);
Address start_adr = seq_input->GetCharsAddress();
int captures[2];
NativeRegExpMacroAssembler::Result result = Execute(
*regexp, *input, 0, start_adr, start_adr + input->length(), captures);
CHECK_EQ(NativeRegExpMacroAssembler::SUCCESS, result);
CHECK_EQ(0, captures[0]);
CHECK_EQ(42, captures[1]);
isolate->clear_pending_exception();
}
TEST(MacroAssembler) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
RegExpBytecodeGenerator m(CcTest::i_isolate(), &zone);
// ^f(o)o.
Label start, fail, backtrack;
m.SetRegister(4, 42);
m.PushRegister(4, RegExpMacroAssembler::kNoStackLimitCheck);
m.AdvanceRegister(4, 42);
m.GoTo(&start);
m.Fail();
m.Bind(&start);
m.PushBacktrack(&fail);
m.CheckNotAtStart(0, nullptr);
m.LoadCurrentCharacter(0, nullptr);
m.CheckNotCharacter('f', nullptr);
m.LoadCurrentCharacter(1, nullptr);
m.CheckNotCharacter('o', nullptr);
m.LoadCurrentCharacter(2, nullptr);
m.CheckNotCharacter('o', nullptr);
m.WriteCurrentPositionToRegister(0, 0);
m.WriteCurrentPositionToRegister(1, 3);
m.WriteCurrentPositionToRegister(2, 1);
m.WriteCurrentPositionToRegister(3, 2);
m.AdvanceCurrentPosition(3);
m.PushBacktrack(&backtrack);
m.Succeed();
m.BindJumpTarget(&backtrack);
m.ClearRegisters(2, 3);
m.Backtrack();
m.BindJumpTarget(&fail);
m.PopRegister(0);
m.Fail();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
Handle<String> source = factory->NewStringFromStaticChars("^f(o)o");
Handle<ByteArray> array = Handle<ByteArray>::cast(m.GetCode(source));
int captures[5];
std::memset(captures, 0, sizeof(captures));
const uc16 str1[] = {'f', 'o', 'o', 'b', 'a', 'r'};
Handle<String> f1_16 =
factory->NewStringFromTwoByte(Vector<const uc16>(str1, 6))
.ToHandleChecked();
CHECK_EQ(IrregexpInterpreter::SUCCESS,
IrregexpInterpreter::MatchInternal(
isolate, *array, *f1_16, captures, 5, 5, 0,
RegExp::CallOrigin::kFromRuntime, JSRegExp::kNoBacktrackLimit));
CHECK_EQ(0, captures[0]);
CHECK_EQ(3, captures[1]);
CHECK_EQ(1, captures[2]);
CHECK_EQ(2, captures[3]);
CHECK_EQ(84, captures[4]);
const uc16 str2[] = {'b', 'a', 'r', 'f', 'o', 'o'};
Handle<String> f2_16 =
factory->NewStringFromTwoByte(Vector<const uc16>(str2, 6))
.ToHandleChecked();
std::memset(captures, 0, sizeof(captures));
CHECK_EQ(IrregexpInterpreter::FAILURE,
IrregexpInterpreter::MatchInternal(
isolate, *array, *f2_16, captures, 5, 5, 0,
RegExp::CallOrigin::kFromRuntime, JSRegExp::kNoBacktrackLimit));
// Failed matches don't alter output registers.
CHECK_EQ(0, captures[0]);
CHECK_EQ(0, captures[1]);
CHECK_EQ(0, captures[2]);
CHECK_EQ(0, captures[3]);
CHECK_EQ(0, captures[4]);
}
#ifndef V8_INTL_SUPPORT
static uc32 canonicalize(uc32 c) {
unibrow::uchar canon[unibrow::Ecma262Canonicalize::kMaxWidth];
int count = unibrow::Ecma262Canonicalize::Convert(c, '\0', canon, nullptr);
if (count == 0) {
return c;
} else {
CHECK_EQ(1, count);
return canon[0];
}
}
TEST(LatinCanonicalize) {
unibrow::Mapping<unibrow::Ecma262UnCanonicalize> un_canonicalize;
for (unibrow::uchar lower = 'a'; lower <= 'z'; lower++) {
unibrow::uchar upper = lower + ('A' - 'a');
CHECK_EQ(canonicalize(lower), canonicalize(upper));
unibrow::uchar uncanon[unibrow::Ecma262UnCanonicalize::kMaxWidth];
int length = un_canonicalize.get(lower, '\0', uncanon);
CHECK_EQ(2, length);
CHECK_EQ(upper, uncanon[0]);
CHECK_EQ(lower, uncanon[1]);
}
for (uc32 c = 128; c < (1 << 21); c++) CHECK_GE(canonicalize(c), 128);
unibrow::Mapping<unibrow::ToUppercase> to_upper;
// Canonicalization is only defined for the Basic Multilingual Plane.
for (uc32 c = 0; c < (1 << 16); c++) {
unibrow::uchar upper[unibrow::ToUppercase::kMaxWidth];
int length = to_upper.get(c, '\0', upper);
if (length == 0) {
length = 1;
upper[0] = c;
}
uc32 u = upper[0];
if (length > 1 || (c >= 128 && u < 128)) u = c;
CHECK_EQ(u, canonicalize(c));
}
}
static uc32 CanonRangeEnd(uc32 c) {
unibrow::uchar canon[unibrow::CanonicalizationRange::kMaxWidth];
int count = unibrow::CanonicalizationRange::Convert(c, '\0', canon, nullptr);
if (count == 0) {
return c;
} else {
CHECK_EQ(1, count);
return canon[0];
}
}
TEST(RangeCanonicalization) {
// Check that we arrive at the same result when using the basic
// range canonicalization primitives as when using immediate
// canonicalization.
unibrow::Mapping<unibrow::Ecma262UnCanonicalize> un_canonicalize;
int block_start = 0;
while (block_start <= 0xFFFF) {
uc32 block_end = CanonRangeEnd(block_start);
unsigned block_length = block_end - block_start + 1;
if (block_length > 1) {
unibrow::uchar first[unibrow::Ecma262UnCanonicalize::kMaxWidth];
int first_length = un_canonicalize.get(block_start, '\0', first);
for (unsigned i = 1; i < block_length; i++) {
unibrow::uchar succ[unibrow::Ecma262UnCanonicalize::kMaxWidth];
int succ_length = un_canonicalize.get(block_start + i, '\0', succ);
CHECK_EQ(first_length, succ_length);
for (int j = 0; j < succ_length; j++) {
int calc = first[j] + i;
int found = succ[j];
CHECK_EQ(calc, found);
}
}
}
block_start = block_start + block_length;
}
}
TEST(UncanonicalizeEquivalence) {
unibrow::Mapping<unibrow::Ecma262UnCanonicalize> un_canonicalize;
unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
for (int i = 0; i < (1 << 16); i++) {
int length = un_canonicalize.get(i, '\0', chars);
for (int j = 0; j < length; j++) {
unibrow::uchar chars2[unibrow::Ecma262UnCanonicalize::kMaxWidth];
int length2 = un_canonicalize.get(chars[j], '\0', chars2);
CHECK_EQ(length, length2);
for (int k = 0; k < length; k++)
CHECK_EQ(static_cast<int>(chars[k]), static_cast<int>(chars2[k]));
}
}
}
#endif
static void TestRangeCaseIndependence(Isolate* isolate, CharacterRange input,
Vector<CharacterRange> expected) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
int count = expected.length();
ZoneList<CharacterRange>* list =
zone.New<ZoneList<CharacterRange>>(count, &zone);
list->Add(input, &zone);
CharacterRange::AddCaseEquivalents(isolate, &zone, list, false);
list->Remove(0); // Remove the input before checking results.
CHECK_EQ(count, list->length());
for (int i = 0; i < list->length(); i++) {
CHECK_EQ(expected[i].from(), list->at(i).from());
CHECK_EQ(expected[i].to(), list->at(i).to());
}
}
static void TestSimpleRangeCaseIndependence(Isolate* isolate,
CharacterRange input,
CharacterRange expected) {
EmbeddedVector<CharacterRange, 1> vector;
vector[0] = expected;
TestRangeCaseIndependence(isolate, input, vector);
}
TEST(CharacterRangeCaseIndependence) {
Isolate* isolate = CcTest::i_isolate();
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Singleton('a'),
CharacterRange::Singleton('A'));
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Singleton('z'),
CharacterRange::Singleton('Z'));
#ifndef V8_INTL_SUPPORT
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('a', 'z'),
CharacterRange::Range('A', 'Z'));
#endif // !V8_INTL_SUPPORT
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('c', 'f'),
CharacterRange::Range('C', 'F'));
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('a', 'b'),
CharacterRange::Range('A', 'B'));
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('y', 'z'),
CharacterRange::Range('Y', 'Z'));
#ifndef V8_INTL_SUPPORT
TestSimpleRangeCaseIndependence(isolate,
CharacterRange::Range('a' - 1, 'z' + 1),
CharacterRange::Range('A', 'Z'));
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('A', 'Z'),
CharacterRange::Range('a', 'z'));
#endif // !V8_INTL_SUPPORT
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('C', 'F'),
CharacterRange::Range('c', 'f'));
#ifndef V8_INTL_SUPPORT
TestSimpleRangeCaseIndependence(isolate,
CharacterRange::Range('A' - 1, 'Z' + 1),
CharacterRange::Range('a', 'z'));
// Here we need to add [l-z] to complete the case independence of
// [A-Za-z] but we expect [a-z] to be added since we always add a
// whole block at a time.
TestSimpleRangeCaseIndependence(isolate, CharacterRange::Range('A', 'k'),
CharacterRange::Range('a', 'z'));
#endif // !V8_INTL_SUPPORT
}
static bool InClass(uc32 c,
const UnicodeRangeSplitter::CharacterRangeVector* ranges) {
if (ranges == nullptr) return false;
for (size_t i = 0; i < ranges->size(); i++) {
CharacterRange range = ranges->at(i);
if (range.from() <= c && c <= range.to()) return true;
}
return false;
}
TEST(UnicodeRangeSplitter) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ZoneList<CharacterRange>* base = zone.New<ZoneList<CharacterRange>>(1, &zone);
base->Add(CharacterRange::Everything(), &zone);
UnicodeRangeSplitter splitter(base);
// BMP
for (uc32 c = 0; c < 0xD800; c++) {
CHECK(InClass(c, splitter.bmp()));
CHECK(!InClass(c, splitter.lead_surrogates()));
CHECK(!InClass(c, splitter.trail_surrogates()));
CHECK(!InClass(c, splitter.non_bmp()));
}
// Lead surrogates
for (uc32 c = 0xD800; c < 0xDBFF; c++) {
CHECK(!InClass(c, splitter.bmp()));
CHECK(InClass(c, splitter.lead_surrogates()));
CHECK(!InClass(c, splitter.trail_surrogates()));
CHECK(!InClass(c, splitter.non_bmp()));
}
// Trail surrogates
for (uc32 c = 0xDC00; c < 0xDFFF; c++) {
CHECK(!InClass(c, splitter.bmp()));
CHECK(!InClass(c, splitter.lead_surrogates()));
CHECK(InClass(c, splitter.trail_surrogates()));
CHECK(!InClass(c, splitter.non_bmp()));
}
// BMP
for (uc32 c = 0xE000; c < 0xFFFF; c++) {
CHECK(InClass(c, splitter.bmp()));
CHECK(!InClass(c, splitter.lead_surrogates()));
CHECK(!InClass(c, splitter.trail_surrogates()));
CHECK(!InClass(c, splitter.non_bmp()));
}
// Non-BMP
for (uc32 c = 0x10000; c < 0x10FFFF; c++) {
CHECK(!InClass(c, splitter.bmp()));
CHECK(!InClass(c, splitter.lead_surrogates()));
CHECK(!InClass(c, splitter.trail_surrogates()));
CHECK(InClass(c, splitter.non_bmp()));
}
}
TEST(CanonicalizeCharacterSets) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ZoneList<CharacterRange>* list = zone.New<ZoneList<CharacterRange>>(4, &zone);
CharacterSet set(list);
list->Add(CharacterRange::Range(10, 20), &zone);
list->Add(CharacterRange::Range(30, 40), &zone);
list->Add(CharacterRange::Range(50, 60), &zone);
set.Canonicalize();
CHECK_EQ(3, list->length());
CHECK_EQ(10, list->at(0).from());
CHECK_EQ(20, list->at(0).to());
CHECK_EQ(30, list->at(1).from());
CHECK_EQ(40, list->at(1).to());
CHECK_EQ(50, list->at(2).from());
CHECK_EQ(60, list->at(2).to());
list->Rewind(0);
list->Add(CharacterRange::Range(10, 20), &zone);
list->Add(CharacterRange::Range(50, 60), &zone);
list->Add(CharacterRange::Range(30, 40), &zone);
set.Canonicalize();
CHECK_EQ(3, list->length());
CHECK_EQ(10, list->at(0).from());
CHECK_EQ(20, list->at(0).to());
CHECK_EQ(30, list->at(1).from());
CHECK_EQ(40, list->at(1).to());
CHECK_EQ(50, list->at(2).from());
CHECK_EQ(60, list->at(2).to());
list->Rewind(0);
list->Add(CharacterRange::Range(30, 40), &zone);
list->Add(CharacterRange::Range(10, 20), &zone);
list->Add(CharacterRange::Range(25, 25), &zone);
list->Add(CharacterRange::Range(100, 100), &zone);
list->Add(CharacterRange::Range(1, 1), &zone);
set.Canonicalize();
CHECK_EQ(5, list->length());
CHECK_EQ(1, list->at(0).from());
CHECK_EQ(1, list->at(0).to());
CHECK_EQ(10, list->at(1).from());
CHECK_EQ(20, list->at(1).to());
CHECK_EQ(25, list->at(2).from());
CHECK_EQ(25, list->at(2).to());
CHECK_EQ(30, list->at(3).from());
CHECK_EQ(40, list->at(3).to());
CHECK_EQ(100, list->at(4).from());
CHECK_EQ(100, list->at(4).to());
list->Rewind(0);
list->Add(CharacterRange::Range(10, 19), &zone);
list->Add(CharacterRange::Range(21, 30), &zone);
list->Add(CharacterRange::Range(20, 20), &zone);
set.Canonicalize();
CHECK_EQ(1, list->length());
CHECK_EQ(10, list->at(0).from());
CHECK_EQ(30, list->at(0).to());
}
TEST(CharacterRangeMerge) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
ZoneList<CharacterRange> l1(4, &zone);
ZoneList<CharacterRange> l2(4, &zone);
// Create all combinations of intersections of ranges, both singletons and
// longer.
int offset = 0;
// The five kinds of singleton intersections:
// X
// Y - outside before
// Y - outside touching start
// Y - overlap
// Y - outside touching end
// Y - outside after
for (int i = 0; i < 5; i++) {
l1.Add(CharacterRange::Singleton(offset + 2), &zone);
l2.Add(CharacterRange::Singleton(offset + i), &zone);
offset += 6;
}
// The seven kinds of singleton/non-singleton intersections:
// XXX
// Y - outside before
// Y - outside touching start
// Y - inside touching start
// Y - entirely inside
// Y - inside touching end
// Y - outside touching end
// Y - disjoint after
for (int i = 0; i < 7; i++) {
l1.Add(CharacterRange::Range(offset + 2, offset + 4), &zone);
l2.Add(CharacterRange::Singleton(offset + i), &zone);
offset += 8;
}
// The eleven kinds of non-singleton intersections:
//
// XXXXXXXX
// YYYY - outside before.
// YYYY - outside touching start.
// YYYY - overlapping start
// YYYY - inside touching start
// YYYY - entirely inside
// YYYY - inside touching end
// YYYY - overlapping end
// YYYY - outside touching end
// YYYY - outside after
// YYYYYYYY - identical
// YYYYYYYYYYYY - containing entirely.
for (int i = 0; i < 9; i++) {
l1.Add(CharacterRange::Range(offset + 6, offset + 15), &zone); // Length 8.
l2.Add(CharacterRange::Range(offset + 2 * i, offset + 2 * i + 3), &zone);
offset += 22;
}
l1.Add(CharacterRange::Range(offset + 6, offset + 15), &zone);
l2.Add(CharacterRange::Range(offset + 6, offset + 15), &zone);
offset += 22;
l1.Add(CharacterRange::Range(offset + 6, offset + 15), &zone);
l2.Add(CharacterRange::Range(offset + 4, offset + 17), &zone);
offset += 22;
// Different kinds of multi-range overlap:
// XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXX
// YYYY Y YYYY Y YYYY Y YYYY Y YYYY Y YYYY Y
l1.Add(CharacterRange::Range(offset, offset + 21), &zone);
l1.Add(CharacterRange::Range(offset + 31, offset + 52), &zone);
for (int i = 0; i < 6; i++) {
l2.Add(CharacterRange::Range(offset + 2, offset + 5), &zone);
l2.Add(CharacterRange::Singleton(offset + 8), &zone);
offset += 9;
}
CHECK(CharacterRange::IsCanonical(&l1));
CHECK(CharacterRange::IsCanonical(&l2));
ZoneList<CharacterRange> first_only(4, &zone);
ZoneList<CharacterRange> second_only(4, &zone);
ZoneList<CharacterRange> both(4, &zone);
}
TEST(Graph) { Execute("\\b\\w+\\b", false, true, true); }
namespace {
int* global_use_counts = nullptr;
void MockUseCounterCallback(v8::Isolate* isolate,
v8::Isolate::UseCounterFeature feature) {
++global_use_counts[feature];
}
} // namespace
// Test that ES2015+ RegExp compatibility fixes are in place, that they
// are not overly broad, and the appropriate UseCounters are incremented
TEST(UseCountRegExp) {
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
LocalContext env;
int use_counts[v8::Isolate::kUseCounterFeatureCount] = {};
global_use_counts = use_counts;
CcTest::isolate()->SetUseCounterCallback(MockUseCounterCallback);
// Compat fix: RegExp.prototype.sticky == undefined; UseCounter tracks it
v8::Local<v8::Value> resultSticky = CompileRun("RegExp.prototype.sticky");
CHECK_EQ(1, use_counts[v8::Isolate::kRegExpPrototypeStickyGetter]);
CHECK_EQ(0, use_counts[v8::Isolate::kRegExpPrototypeToString]);
CHECK(resultSticky->IsUndefined());
// re.sticky has approriate value and doesn't touch UseCounter
v8::Local<v8::Value> resultReSticky = CompileRun("/a/.sticky");
CHECK_EQ(1, use_counts[v8::Isolate::kRegExpPrototypeStickyGetter]);
CHECK_EQ(0, use_counts[v8::Isolate::kRegExpPrototypeToString]);
CHECK(resultReSticky->IsFalse());
// When the getter is called on another object, throw an exception
// and don't increment the UseCounter
v8::Local<v8::Value> resultStickyError = CompileRun(
"var exception;"
"try { "
" Object.getOwnPropertyDescriptor(RegExp.prototype, 'sticky')"
" .get.call(null);"
"} catch (e) {"
" exception = e;"
"}"
"exception");
CHECK_EQ(1, use_counts[v8::Isolate::kRegExpPrototypeStickyGetter]);
CHECK_EQ(0, use_counts[v8::Isolate::kRegExpPrototypeToString]);
CHECK(resultStickyError->IsObject());
// RegExp.prototype.toString() returns '/(?:)/' as a compatibility fix;
// a UseCounter is incremented to track it.
v8::Local<v8::Value> resultToString =
CompileRun("RegExp.prototype.toString().length");
CHECK_EQ(2, use_counts[v8::Isolate::kRegExpPrototypeStickyGetter]);
CHECK_EQ(1, use_counts[v8::Isolate::kRegExpPrototypeToString]);
CHECK(resultToString->IsInt32());
CHECK_EQ(6,
resultToString->Int32Value(isolate->GetCurrentContext()).FromJust());
// .toString() works on normal RegExps
v8::Local<v8::Value> resultReToString = CompileRun("/a/.toString().length");
CHECK_EQ(2, use_counts[v8::Isolate::kRegExpPrototypeStickyGetter]);
CHECK_EQ(1, use_counts[v8::Isolate::kRegExpPrototypeToString]);
CHECK(resultReToString->IsInt32());
CHECK_EQ(
3, resultReToString->Int32Value(isolate->GetCurrentContext()).FromJust());
// .toString() throws on non-RegExps that aren't RegExp.prototype
v8::Local<v8::Value> resultToStringError = CompileRun(
"var exception;"
"try { RegExp.prototype.toString.call(null) }"
"catch (e) { exception = e; }"
"exception");
CHECK_EQ(2, use_counts[v8::Isolate::kRegExpPrototypeStickyGetter]);
CHECK_EQ(1, use_counts[v8::Isolate::kRegExpPrototypeToString]);
CHECK(resultToStringError->IsObject());
}
class UncachedExternalString
: public v8::String::ExternalOneByteStringResource {
public:
const char* data() const override { return "abcdefghijklmnopqrstuvwxyz"; }
size_t length() const override { return 26; }
bool IsCacheable() const override { return false; }
};
TEST(UncachedExternalString) {
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
LocalContext env;
v8::Local<v8::String> external =
v8::String::NewExternalOneByte(isolate, new UncachedExternalString())
.ToLocalChecked();
CHECK(v8::Utils::OpenHandle(*external)->map() ==
ReadOnlyRoots(CcTest::i_isolate())
.uncached_external_one_byte_string_map());
v8::Local<v8::Object> global = env->Global();
global->Set(env.local(), v8_str("external"), external).FromJust();
CompileRun("var re = /y(.)/; re.test('ab');");
ExpectString("external.substring(1).match(re)[1]", "z");
}
// Test bytecode peephole optimization
void CreatePeepholeNoChangeBytecode(RegExpMacroAssembler* m) {
Label fail, backtrack;
m->PushBacktrack(&fail);
m->CheckNotAtStart(0, nullptr);
m->LoadCurrentCharacter(2, nullptr);
m->CheckNotCharacter('o', nullptr);
m->LoadCurrentCharacter(1, nullptr, false);
m->CheckNotCharacter('o', nullptr);
m->LoadCurrentCharacter(0, nullptr, false);
m->CheckNotCharacter('f', nullptr);
m->WriteCurrentPositionToRegister(0, 0);
m->WriteCurrentPositionToRegister(1, 3);
m->AdvanceCurrentPosition(3);
m->PushBacktrack(&backtrack);
m->Succeed();
m->Bind(&backtrack);
m->Backtrack();
m->Bind(&fail);
m->Fail();
}
TEST(PeepholeNoChange) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeNoChangeBytecode(&orig);
CreatePeepholeNoChangeBytecode(&opt);
Handle<String> source = factory->NewStringFromStaticChars("^foo");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
byte* byte_array = array->GetDataStartAddress();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
byte* byte_array_optimized = array_optimized->GetDataStartAddress();
CHECK_EQ(0, memcmp(byte_array, byte_array_optimized, length));
}
void CreatePeepholeSkipUntilCharBytecode(RegExpMacroAssembler* m) {
Label start;
m->Bind(&start);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckCharacter('x', nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&start);
}
TEST(PeepholeSkipUntilChar) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeSkipUntilCharBytecode(&orig);
CreatePeepholeSkipUntilCharBytecode(&opt);
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
int length_optimized = array_optimized->length();
int length_expected = RegExpBytecodeLength(BC_LOAD_CURRENT_CHAR) +
RegExpBytecodeLength(BC_CHECK_CHAR) +
RegExpBytecodeLength(BC_ADVANCE_CP_AND_GOTO) +
RegExpBytecodeLength(BC_POP_BT);
int length_optimized_expected = RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR) +
RegExpBytecodeLength(BC_POP_BT);
CHECK_EQ(length, length_expected);
CHECK_EQ(length_optimized, length_optimized_expected);
CHECK_EQ(BC_SKIP_UNTIL_CHAR, array_optimized->get(0));
CHECK_EQ(BC_POP_BT,
array_optimized->get(RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR)));
}
void CreatePeepholeSkipUntilBitInTableBytecode(RegExpMacroAssembler* m,
Factory* factory) {
Handle<ByteArray> bit_table = factory->NewByteArray(
RegExpMacroAssembler::kTableSize, AllocationType::kOld);
for (uint32_t i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
bit_table->set(i, 0);
}
Label start;
m->Bind(&start);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckBitInTable(bit_table, nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&start);
}
TEST(PeepholeSkipUntilBitInTable) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeSkipUntilBitInTableBytecode(&orig, factory);
CreatePeepholeSkipUntilBitInTableBytecode(&opt, factory);
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
int length_optimized = array_optimized->length();
int length_expected = RegExpBytecodeLength(BC_LOAD_CURRENT_CHAR) +
RegExpBytecodeLength(BC_CHECK_BIT_IN_TABLE) +
RegExpBytecodeLength(BC_ADVANCE_CP_AND_GOTO) +
RegExpBytecodeLength(BC_POP_BT);
int length_optimized_expected =
RegExpBytecodeLength(BC_SKIP_UNTIL_BIT_IN_TABLE) +
RegExpBytecodeLength(BC_POP_BT);
CHECK_EQ(length, length_expected);
CHECK_EQ(length_optimized, length_optimized_expected);
CHECK_EQ(BC_SKIP_UNTIL_BIT_IN_TABLE, array_optimized->get(0));
CHECK_EQ(BC_POP_BT, array_optimized->get(
RegExpBytecodeLength(BC_SKIP_UNTIL_BIT_IN_TABLE)));
}
void CreatePeepholeSkipUntilCharPosCheckedBytecode(RegExpMacroAssembler* m) {
Label start;
m->Bind(&start);
m->LoadCurrentCharacter(0, nullptr, true, 1, 2);
m->CheckCharacter('x', nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&start);
}
TEST(PeepholeSkipUntilCharPosChecked) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeSkipUntilCharPosCheckedBytecode(&orig);
CreatePeepholeSkipUntilCharPosCheckedBytecode(&opt);
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
int length_optimized = array_optimized->length();
int length_expected = RegExpBytecodeLength(BC_CHECK_CURRENT_POSITION) +
RegExpBytecodeLength(BC_LOAD_CURRENT_CHAR_UNCHECKED) +
RegExpBytecodeLength(BC_CHECK_CHAR) +
RegExpBytecodeLength(BC_ADVANCE_CP_AND_GOTO) +
RegExpBytecodeLength(BC_POP_BT);
int length_optimized_expected =
RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR_POS_CHECKED) +
RegExpBytecodeLength(BC_POP_BT);
CHECK_EQ(length, length_expected);
CHECK_EQ(length_optimized, length_optimized_expected);
CHECK_EQ(BC_SKIP_UNTIL_CHAR_POS_CHECKED, array_optimized->get(0));
CHECK_EQ(BC_POP_BT, array_optimized->get(RegExpBytecodeLength(
BC_SKIP_UNTIL_CHAR_POS_CHECKED)));
}
void CreatePeepholeSkipUntilCharAndBytecode(RegExpMacroAssembler* m) {
Label start;
m->Bind(&start);
m->LoadCurrentCharacter(0, nullptr, true, 1, 2);
m->CheckCharacterAfterAnd('x', 0xFF, nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&start);
}
TEST(PeepholeSkipUntilCharAnd) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeSkipUntilCharAndBytecode(&orig);
CreatePeepholeSkipUntilCharAndBytecode(&opt);
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
int length_optimized = array_optimized->length();
int length_expected = RegExpBytecodeLength(BC_CHECK_CURRENT_POSITION) +
RegExpBytecodeLength(BC_LOAD_CURRENT_CHAR_UNCHECKED) +
RegExpBytecodeLength(BC_AND_CHECK_CHAR) +
RegExpBytecodeLength(BC_ADVANCE_CP_AND_GOTO) +
RegExpBytecodeLength(BC_POP_BT);
int length_optimized_expected = RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR_AND) +
RegExpBytecodeLength(BC_POP_BT);
CHECK_EQ(length, length_expected);
CHECK_EQ(length_optimized, length_optimized_expected);
CHECK_EQ(BC_SKIP_UNTIL_CHAR_AND, array_optimized->get(0));
CHECK_EQ(BC_POP_BT,
array_optimized->get(RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR_AND)));
}
void CreatePeepholeSkipUntilCharOrCharBytecode(RegExpMacroAssembler* m) {
Label start;
m->Bind(&start);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckCharacter('x', nullptr);
m->CheckCharacter('y', nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&start);
}
TEST(PeepholeSkipUntilCharOrChar) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeSkipUntilCharOrCharBytecode(&orig);
CreatePeepholeSkipUntilCharOrCharBytecode(&opt);
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
int length_optimized = array_optimized->length();
int length_expected = RegExpBytecodeLength(BC_LOAD_CURRENT_CHAR) +
RegExpBytecodeLength(BC_CHECK_CHAR) +
RegExpBytecodeLength(BC_CHECK_CHAR) +
RegExpBytecodeLength(BC_ADVANCE_CP_AND_GOTO) +
RegExpBytecodeLength(BC_POP_BT);
int length_optimized_expected =
RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR_OR_CHAR) +
RegExpBytecodeLength(BC_POP_BT);
CHECK_EQ(length, length_expected);
CHECK_EQ(length_optimized, length_optimized_expected);
CHECK_EQ(BC_SKIP_UNTIL_CHAR_OR_CHAR, array_optimized->get(0));
CHECK_EQ(BC_POP_BT, array_optimized->get(
RegExpBytecodeLength(BC_SKIP_UNTIL_CHAR_OR_CHAR)));
}
void CreatePeepholeSkipUntilGtOrNotBitInTableBytecode(RegExpMacroAssembler* m,
Factory* factory) {
Handle<ByteArray> bit_table = factory->NewByteArray(
RegExpMacroAssembler::kTableSize, AllocationType::kOld);
for (uint32_t i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
bit_table->set(i, 0);
}
Label start, end, advance;
m->Bind(&start);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckCharacterGT('x', nullptr);
m->CheckBitInTable(bit_table, &advance);
m->GoTo(&end);
m->Bind(&advance);
m->AdvanceCurrentPosition(1);
m->GoTo(&start);
m->Bind(&end);
}
TEST(PeepholeSkipUntilGtOrNotBitInTable) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
CreatePeepholeSkipUntilGtOrNotBitInTableBytecode(&orig, factory);
CreatePeepholeSkipUntilGtOrNotBitInTableBytecode(&opt, factory);
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
int length = array->length();
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
int length_optimized = array_optimized->length();
int length_expected = RegExpBytecodeLength(BC_LOAD_CURRENT_CHAR) +
RegExpBytecodeLength(BC_CHECK_GT) +
RegExpBytecodeLength(BC_CHECK_BIT_IN_TABLE) +
RegExpBytecodeLength(BC_GOTO) +
RegExpBytecodeLength(BC_ADVANCE_CP_AND_GOTO) +
RegExpBytecodeLength(BC_POP_BT);
int length_optimized_expected =
RegExpBytecodeLength(BC_SKIP_UNTIL_GT_OR_NOT_BIT_IN_TABLE) +
RegExpBytecodeLength(BC_POP_BT);
CHECK_EQ(length, length_expected);
CHECK_EQ(length_optimized, length_optimized_expected);
CHECK_EQ(BC_SKIP_UNTIL_GT_OR_NOT_BIT_IN_TABLE, array_optimized->get(0));
CHECK_EQ(BC_POP_BT, array_optimized->get(RegExpBytecodeLength(
BC_SKIP_UNTIL_GT_OR_NOT_BIT_IN_TABLE)));
}
void CreatePeepholeLabelFixupsInsideBytecode(RegExpMacroAssembler* m,
Label* dummy_before,
Label* dummy_after,
Label* dummy_inside) {
Label loop;
m->Bind(dummy_before);
m->LoadCurrentCharacter(0, dummy_before);
m->CheckCharacter('a', dummy_after);
m->CheckCharacter('b', dummy_inside);
m->Bind(&loop);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckCharacter('x', nullptr);
m->Bind(dummy_inside);
m->CheckCharacter('y', nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&loop);
m->Bind(dummy_after);
m->LoadCurrentCharacter(0, dummy_before);
m->CheckCharacter('a', dummy_after);
m->CheckCharacter('b', dummy_inside);
}
TEST(PeepholeLabelFixupsInside) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
{
Label dummy_before, dummy_after, dummy_inside;
CreatePeepholeLabelFixupsInsideBytecode(&opt, &dummy_before, &dummy_after,
&dummy_inside);
}
Label dummy_before, dummy_after, dummy_inside;
CreatePeepholeLabelFixupsInsideBytecode(&orig, &dummy_before, &dummy_after,
&dummy_inside);
CHECK_EQ(0x00, dummy_before.pos());
CHECK_EQ(0x28, dummy_inside.pos());
CHECK_EQ(0x38, dummy_after.pos());
const Label* labels[] = {&dummy_before, &dummy_after, &dummy_inside};
const int label_positions[4][3] = {
{0x04, 0x3C}, // dummy_before
{0x0C, 0x44}, // dummy after
{0x14, 0x4C} // dummy inside
};
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
for (int label_idx = 0; label_idx < 3; label_idx++) {
for (int pos_idx = 0; pos_idx < 2; pos_idx++) {
CHECK_EQ(labels[label_idx]->pos(),
array->get(label_positions[label_idx][pos_idx]));
}
}
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
const int pos_fixups[] = {
0, // Position before optimization should be unchanged.
4, // Position after first replacement should be 4 (optimized size (20) -
// original size (32) + preserve length (16)).
};
const int target_fixups[] = {
0, // dummy_before should be unchanged
4, // dummy_inside should be 4
4 // dummy_after should be 4
};
for (int label_idx = 0; label_idx < 3; label_idx++) {
for (int pos_idx = 0; pos_idx < 2; pos_idx++) {
int label_pos = label_positions[label_idx][pos_idx] + pos_fixups[pos_idx];
int jump_address = *reinterpret_cast<uint32_t*>(
array_optimized->GetDataStartAddress() + label_pos);
int expected_jump_address =
labels[label_idx]->pos() + target_fixups[label_idx];
CHECK_EQ(expected_jump_address, jump_address);
}
}
}
void CreatePeepholeLabelFixupsComplexBytecode(RegExpMacroAssembler* m,
Label* dummy_before,
Label* dummy_between,
Label* dummy_after,
Label* dummy_inside) {
Label loop1, loop2;
m->Bind(dummy_before);
m->LoadCurrentCharacter(0, dummy_before);
m->CheckCharacter('a', dummy_between);
m->CheckCharacter('b', dummy_after);
m->CheckCharacter('c', dummy_inside);
m->Bind(&loop1);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckCharacter('x', nullptr);
m->CheckCharacter('y', nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&loop1);
m->Bind(dummy_between);
m->LoadCurrentCharacter(0, dummy_before);
m->CheckCharacter('a', dummy_between);
m->CheckCharacter('b', dummy_after);
m->CheckCharacter('c', dummy_inside);
m->Bind(&loop2);
m->LoadCurrentCharacter(0, nullptr, true);
m->CheckCharacter('x', nullptr);
m->Bind(dummy_inside);
m->CheckCharacter('y', nullptr);
m->AdvanceCurrentPosition(1);
m->GoTo(&loop2);
m->Bind(dummy_after);
m->LoadCurrentCharacter(0, dummy_before);
m->CheckCharacter('a', dummy_between);
m->CheckCharacter('b', dummy_after);
m->CheckCharacter('c', dummy_inside);
}
TEST(PeepholeLabelFixupsComplex) {
Zone zone(CcTest::i_isolate()->allocator(), ZONE_NAME);
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
HandleScope scope(isolate);
RegExpBytecodeGenerator orig(CcTest::i_isolate(), &zone);
RegExpBytecodeGenerator opt(CcTest::i_isolate(), &zone);
{
Label dummy_before, dummy_between, dummy_after, dummy_inside;
CreatePeepholeLabelFixupsComplexBytecode(
&opt, &dummy_before, &dummy_between, &dummy_after, &dummy_inside);
}
Label dummy_before, dummy_between, dummy_after, dummy_inside;
CreatePeepholeLabelFixupsComplexBytecode(&orig, &dummy_before, &dummy_between,
&dummy_after, &dummy_inside);
CHECK_EQ(0x00, dummy_before.pos());
CHECK_EQ(0x40, dummy_between.pos());
CHECK_EQ(0x70, dummy_inside.pos());
CHECK_EQ(0x80, dummy_after.pos());
const Label* labels[] = {&dummy_before, &dummy_between, &dummy_after,
&dummy_inside};
const int label_positions[4][3] = {
{0x04, 0x44, 0x84}, // dummy_before
{0x0C, 0x4C, 0x8C}, // dummy between
{0x14, 0x54, 0x94}, // dummy after
{0x1C, 0x5C, 0x9C} // dummy inside
};
Handle<String> source = factory->NewStringFromStaticChars("dummy");
i::FLAG_regexp_peephole_optimization = false;
Handle<ByteArray> array = Handle<ByteArray>::cast(orig.GetCode(source));
for (int label_idx = 0; label_idx < 4; label_idx++) {
for (int pos_idx = 0; pos_idx < 3; pos_idx++) {
CHECK_EQ(labels[label_idx]->pos(),
array->get(label_positions[label_idx][pos_idx]));
}
}
i::FLAG_regexp_peephole_optimization = true;
Handle<ByteArray> array_optimized =
Handle<ByteArray>::cast(opt.GetCode(source));
const int pos_fixups[] = {
0, // Position before optimization should be unchanged.
-12, // Position after first replacement should be -12 (optimized size =
// 20 - 32 = original size).
-8 // Position after second replacement should be -8 (-12 from first
// optimization -12 from second optimization + 16 preserved
// bytecodes).
};
const int target_fixups[] = {
0, // dummy_before should be unchanged
-12, // dummy_between should be -12
-8, // dummy_inside should be -8
-8 // dummy_after should be -8
};
for (int label_idx = 0; label_idx < 4; label_idx++) {
for (int pos_idx = 0; pos_idx < 3; pos_idx++) {
int label_pos = label_positions[label_idx][pos_idx] + pos_fixups[pos_idx];
int jump_address = *reinterpret_cast<uint32_t*>(
array_optimized->GetDataStartAddress() + label_pos);
int expected_jump_address =
labels[label_idx]->pos() + target_fixups[label_idx];
CHECK_EQ(expected_jump_address, jump_address);
}
}
}
TEST(UnicodePropertyEscapeCodeSize) {
i::FlagScope<bool> f(&v8::internal::FLAG_regexp_tier_up, false);
LocalContext env;
v8::HandleScope scope(CcTest::isolate());
i::Handle<i::JSRegExp> re = Utils::OpenHandle(
*CompileRun("const r = /\\p{L}\\p{L}\\p{L}/u; r.exec('\\u200b'); r;")
.As<v8::RegExp>());
static constexpr int kMaxSize = 200 * KB;
static constexpr bool kIsNotLatin1 = false;
Object maybe_code = re->Code(kIsNotLatin1);
Object maybe_bytecode = re->Bytecode(kIsNotLatin1);
if (maybe_bytecode.IsByteArray()) {
// On x64, excessive inlining produced >250KB.
CHECK_LT(ByteArray::cast(maybe_bytecode).Size(), kMaxSize);
} else if (maybe_code.IsCode()) {
// On x64, excessive inlining produced >360KB.
CHECK_LT(Code::cast(maybe_code).Size(), kMaxSize);
CHECK_EQ(Code::cast(maybe_code).kind(), CodeKind::REGEXP);
} else {
UNREACHABLE();
}
}
#undef CHECK_PARSE_ERROR
#undef CHECK_SIMPLE
#undef CHECK_MIN_MAX
} // namespace test_regexp
} // namespace internal
} // namespace v8
|