1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130
/*!
This module provides a regular expression parser.
*/
use core::{
borrow::Borrow,
cell::{Cell, RefCell},
mem,
};
use alloc::{
boxed::Box,
string::{String, ToString},
vec,
vec::Vec,
};
use crate::{
ast::{self, Ast, Position, Span},
either::Either,
is_escapeable_character, is_meta_character,
};
type Result<T> = core::result::Result<T, ast::Error>;
/// A primitive is an expression with no sub-expressions. This includes
/// literals, assertions and non-set character classes. This representation
/// is used as intermediate state in the parser.
///
/// This does not include ASCII character classes, since they can only appear
/// within a set character class.
#[derive(Clone, Debug, Eq, PartialEq)]
enum Primitive {
Literal(ast::Literal),
Assertion(ast::Assertion),
Dot(Span),
Perl(ast::ClassPerl),
Unicode(ast::ClassUnicode),
}
impl Primitive {
/// Return the span of this primitive.
fn span(&self) -> &Span {
match *self {
Primitive::Literal(ref x) => &x.span,
Primitive::Assertion(ref x) => &x.span,
Primitive::Dot(ref span) => span,
Primitive::Perl(ref x) => &x.span,
Primitive::Unicode(ref x) => &x.span,
}
}
/// Convert this primitive into a proper AST.
fn into_ast(self) -> Ast {
match self {
Primitive::Literal(lit) => Ast::Literal(lit),
Primitive::Assertion(assert) => Ast::Assertion(assert),
Primitive::Dot(span) => Ast::Dot(span),
Primitive::Perl(cls) => Ast::Class(ast::Class::Perl(cls)),
Primitive::Unicode(cls) => Ast::Class(ast::Class::Unicode(cls)),
}
}
/// Convert this primitive into an item in a character class.
///
/// If this primitive is not a legal item (i.e., an assertion or a dot),
/// then return an error.
fn into_class_set_item<P: Borrow<Parser>>(
self,
p: &ParserI<'_, P>,
) -> Result<ast::ClassSetItem> {
use self::Primitive::*;
use crate::ast::ClassSetItem;
match self {
Literal(lit) => Ok(ClassSetItem::Literal(lit)),
Perl(cls) => Ok(ClassSetItem::Perl(cls)),
Unicode(cls) => Ok(ClassSetItem::Unicode(cls)),
x => Err(p.error(*x.span(), ast::ErrorKind::ClassEscapeInvalid)),
}
}
/// Convert this primitive into a literal in a character class. In
/// particular, literals are the only valid items that can appear in
/// ranges.
///
/// If this primitive is not a legal item (i.e., a class, assertion or a
/// dot), then return an error.
fn into_class_literal<P: Borrow<Parser>>(
self,
p: &ParserI<'_, P>,
) -> Result<ast::Literal> {
use self::Primitive::*;
match self {
Literal(lit) => Ok(lit),
x => Err(p.error(*x.span(), ast::ErrorKind::ClassRangeLiteral)),
}
}
}
/// Returns true if the given character is a hexadecimal digit.
fn is_hex(c: char) -> bool {
('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
}
/// Returns true if the given character is a valid in a capture group name.
///
/// If `first` is true, then `c` is treated as the first character in the
/// group name (which must be alphabetic or underscore).
fn is_capture_char(c: char, first: bool) -> bool {
if first {
c == '_' || c.is_alphabetic()
} else {
c == '_' || c == '.' || c == '[' || c == ']' || c.is_alphanumeric()
}
}
/// A builder for a regular expression parser.
///
/// This builder permits modifying configuration options for the parser.
#[derive(Clone, Debug)]
pub struct ParserBuilder {
ignore_whitespace: bool,
nest_limit: u32,
octal: bool,
}
impl Default for ParserBuilder {
fn default() -> ParserBuilder {
ParserBuilder::new()
}
}
impl ParserBuilder {
/// Create a new parser builder with a default configuration.
pub fn new() -> ParserBuilder {
ParserBuilder {
ignore_whitespace: false,
nest_limit: 250,
octal: false,
}
}
/// Build a parser from this configuration with the given pattern.
pub fn build(&self) -> Parser {
Parser {
pos: Cell::new(Position { offset: 0, line: 1, column: 1 }),
capture_index: Cell::new(0),
nest_limit: self.nest_limit,
octal: self.octal,
initial_ignore_whitespace: self.ignore_whitespace,
ignore_whitespace: Cell::new(self.ignore_whitespace),
comments: RefCell::new(vec![]),
stack_group: RefCell::new(vec![]),
stack_class: RefCell::new(vec![]),
capture_names: RefCell::new(vec![]),
scratch: RefCell::new(String::new()),
}
}
/// Set the nesting limit for this parser.
///
/// The nesting limit controls how deep the abstract syntax tree is allowed
/// to be. If the AST exceeds the given limit (e.g., with too many nested
/// groups), then an error is returned by the parser.
///
/// The purpose of this limit is to act as a heuristic to prevent stack
/// overflow for consumers that do structural induction on an `Ast` using
/// explicit recursion. While this crate never does this (instead using
/// constant stack space and moving the call stack to the heap), other
/// crates may.
///
/// This limit is not checked until the entire AST is parsed. Therefore,
/// if callers want to put a limit on the amount of heap space used, then
/// they should impose a limit on the length, in bytes, of the concrete
/// pattern string. In particular, this is viable since this parser
/// implementation will limit itself to heap space proportional to the
/// length of the pattern string.
///
/// Note that a nest limit of `0` will return a nest limit error for most
/// patterns but not all. For example, a nest limit of `0` permits `a` but
/// not `ab`, since `ab` requires a concatenation, which results in a nest
/// depth of `1`. In general, a nest limit is not something that manifests
/// in an obvious way in the concrete syntax, therefore, it should not be
/// used in a granular way.
pub fn nest_limit(&mut self, limit: u32) -> &mut ParserBuilder {
self.nest_limit = limit;
self
}
/// Whether to support octal syntax or not.
///
/// Octal syntax is a little-known way of uttering Unicode codepoints in
/// a regular expression. For example, `a`, `\x61`, `\u0061` and
/// `\141` are all equivalent regular expressions, where the last example
/// shows octal syntax.
///
/// While supporting octal syntax isn't in and of itself a problem, it does
/// make good error messages harder. That is, in PCRE based regex engines,
/// syntax like `\0` invokes a backreference, which is explicitly
/// unsupported in Rust's regex engine. However, many users expect it to
/// be supported. Therefore, when octal support is disabled, the error
/// message will explicitly mention that backreferences aren't supported.
///
/// Octal syntax is disabled by default.
pub fn octal(&mut self, yes: bool) -> &mut ParserBuilder {
self.octal = yes;
self
}
/// Enable verbose mode in the regular expression.
///
/// When enabled, verbose mode permits insignificant whitespace in many
/// places in the regular expression, as well as comments. Comments are
/// started using `#` and continue until the end of the line.
///
/// By default, this is disabled. It may be selectively enabled in the
/// regular expression by using the `x` flag regardless of this setting.
pub fn ignore_whitespace(&mut self, yes: bool) -> &mut ParserBuilder {
self.ignore_whitespace = yes;
self
}
}
/// A regular expression parser.
///
/// This parses a string representation of a regular expression into an
/// abstract syntax tree. The size of the tree is proportional to the length
/// of the regular expression pattern.
///
/// A `Parser` can be configured in more detail via a [`ParserBuilder`].
#[derive(Clone, Debug)]
pub struct Parser {
/// The current position of the parser.
pos: Cell<Position>,
/// The current capture index.
capture_index: Cell<u32>,
/// The maximum number of open parens/brackets allowed. If the parser
/// exceeds this number, then an error is returned.
nest_limit: u32,
/// Whether to support octal syntax or not. When `false`, the parser will
/// return an error helpfully pointing out that backreferences are not
/// supported.
octal: bool,
/// The initial setting for `ignore_whitespace` as provided by
/// `ParserBuilder`. It is used when resetting the parser's state.
initial_ignore_whitespace: bool,
/// Whether whitespace should be ignored. When enabled, comments are
/// also permitted.
ignore_whitespace: Cell<bool>,
/// A list of comments, in order of appearance.
comments: RefCell<Vec<ast::Comment>>,
/// A stack of grouped sub-expressions, including alternations.
stack_group: RefCell<Vec<GroupState>>,
/// A stack of nested character classes. This is only non-empty when
/// parsing a class.
stack_class: RefCell<Vec<ClassState>>,
/// A sorted sequence of capture names. This is used to detect duplicate
/// capture names and report an error if one is detected.
capture_names: RefCell<Vec<ast::CaptureName>>,
/// A scratch buffer used in various places. Mostly this is used to
/// accumulate relevant characters from parts of a pattern.
scratch: RefCell<String>,
}
/// ParserI is the internal parser implementation.
///
/// We use this separate type so that we can carry the provided pattern string
/// along with us. In particular, a `Parser` internal state is not tied to any
/// one pattern, but `ParserI` is.
///
/// This type also lets us use `ParserI<&Parser>` in production code while
/// retaining the convenience of `ParserI<Parser>` for tests, which sometimes
/// work against the internal interface of the parser.
#[derive(Clone, Debug)]
struct ParserI<'s, P> {
/// The parser state/configuration.
parser: P,
/// The full regular expression provided by the user.
pattern: &'s str,
}
/// GroupState represents a single stack frame while parsing nested groups
/// and alternations. Each frame records the state up to an opening parenthesis
/// or a alternating bracket `|`.
#[derive(Clone, Debug)]
enum GroupState {
/// This state is pushed whenever an opening group is found.
Group {
/// The concatenation immediately preceding the opening group.
concat: ast::Concat,
/// The group that has been opened. Its sub-AST is always empty.
group: ast::Group,
/// Whether this group has the `x` flag enabled or not.
ignore_whitespace: bool,
},
/// This state is pushed whenever a new alternation branch is found. If
/// an alternation branch is found and this state is at the top of the
/// stack, then this state should be modified to include the new
/// alternation.
Alternation(ast::Alternation),
}
/// ClassState represents a single stack frame while parsing character classes.
/// Each frame records the state up to an intersection, difference, symmetric
/// difference or nested class.
///
/// Note that a parser's character class stack is only non-empty when parsing
/// a character class. In all other cases, it is empty.
#[derive(Clone, Debug)]
enum ClassState {
/// This state is pushed whenever an opening bracket is found.
Open {
/// The union of class items immediately preceding this class.
union: ast::ClassSetUnion,
/// The class that has been opened. Typically this just corresponds
/// to the `[`, but it can also include `[^` since `^` indicates
/// negation of the class.
set: ast::ClassBracketed,
},
/// This state is pushed when a operator is seen. When popped, the stored
/// set becomes the left hand side of the operator.
Op {
/// The type of the operation, i.e., &&, -- or ~~.
kind: ast::ClassSetBinaryOpKind,
/// The left-hand side of the operator.
lhs: ast::ClassSet,
},
}
impl Parser {
/// Create a new parser with a default configuration.
///
/// The parser can be run with either the `parse` or `parse_with_comments`
/// methods. The parse methods return an abstract syntax tree.
///
/// To set configuration options on the parser, use [`ParserBuilder`].
pub fn new() -> Parser {
ParserBuilder::new().build()
}
/// Parse the regular expression into an abstract syntax tree.
pub fn parse(&mut self, pattern: &str) -> Result<Ast> {
ParserI::new(self, pattern).parse()
}
/// Parse the regular expression and return an abstract syntax tree with
/// all of the comments found in the pattern.
pub fn parse_with_comments(
&mut self,
pattern: &str,
) -> Result<ast::WithComments> {
ParserI::new(self, pattern).parse_with_comments()
}
/// Reset the internal state of a parser.
///
/// This is called at the beginning of every parse. This prevents the
/// parser from running with inconsistent state (say, if a previous
/// invocation returned an error and the parser is reused).
fn reset(&self) {
// These settings should be in line with the construction
// in `ParserBuilder::build`.
self.pos.set(Position { offset: 0, line: 1, column: 1 });
self.ignore_whitespace.set(self.initial_ignore_whitespace);
self.comments.borrow_mut().clear();
self.stack_group.borrow_mut().clear();
self.stack_class.borrow_mut().clear();
}
}
impl<'s, P: Borrow<Parser>> ParserI<'s, P> {
/// Build an internal parser from a parser configuration and a pattern.
fn new(parser: P, pattern: &'s str) -> ParserI<'s, P> {
ParserI { parser, pattern }
}
/// Return a reference to the parser state.
fn parser(&self) -> &Parser {
self.parser.borrow()
}
/// Return a reference to the pattern being parsed.
fn pattern(&self) -> &str {
self.pattern.borrow()
}
/// Create a new error with the given span and error type.
fn error(&self, span: Span, kind: ast::ErrorKind) -> ast::Error {
ast::Error { kind, pattern: self.pattern().to_string(), span }
}
/// Return the current offset of the parser.
///
/// The offset starts at `0` from the beginning of the regular expression
/// pattern string.
fn offset(&self) -> usize {
self.parser().pos.get().offset
}
/// Return the current line number of the parser.
///
/// The line number starts at `1`.
fn line(&self) -> usize {
self.parser().pos.get().line
}
/// Return the current column of the parser.
///
/// The column number starts at `1` and is reset whenever a `\n` is seen.
fn column(&self) -> usize {
self.parser().pos.get().column
}
/// Return the next capturing index. Each subsequent call increments the
/// internal index.
///
/// The span given should correspond to the location of the opening
/// parenthesis.
///
/// If the capture limit is exceeded, then an error is returned.
fn next_capture_index(&self, span: Span) -> Result<u32> {
let current = self.parser().capture_index.get();
let i = current.checked_add(1).ok_or_else(|| {
self.error(span, ast::ErrorKind::CaptureLimitExceeded)
})?;
self.parser().capture_index.set(i);
Ok(i)
}
/// Adds the given capture name to this parser. If this capture name has
/// already been used, then an error is returned.
fn add_capture_name(&self, cap: &ast::CaptureName) -> Result<()> {
let mut names = self.parser().capture_names.borrow_mut();
match names
.binary_search_by_key(&cap.name.as_str(), |c| c.name.as_str())
{
Err(i) => {
names.insert(i, cap.clone());
Ok(())
}
Ok(i) => Err(self.error(
cap.span,
ast::ErrorKind::GroupNameDuplicate { original: names[i].span },
)),
}
}
/// Return whether the parser should ignore whitespace or not.
fn ignore_whitespace(&self) -> bool {
self.parser().ignore_whitespace.get()
}
/// Return the character at the current position of the parser.
///
/// This panics if the current position does not point to a valid char.
fn char(&self) -> char {
self.char_at(self.offset())
}
/// Return the character at the given position.
///
/// This panics if the given position does not point to a valid char.
fn char_at(&self, i: usize) -> char {
self.pattern()[i..]
.chars()
.next()
.unwrap_or_else(|| panic!("expected char at offset {}", i))
}
/// Bump the parser to the next Unicode scalar value.
///
/// If the end of the input has been reached, then `false` is returned.
fn bump(&self) -> bool {
if self.is_eof() {
return false;
}
let Position { mut offset, mut line, mut column } = self.pos();
if self.char() == '\n' {
line = line.checked_add(1).unwrap();
column = 1;
} else {
column = column.checked_add(1).unwrap();
}
offset += self.char().len_utf8();
self.parser().pos.set(Position { offset, line, column });
self.pattern()[self.offset()..].chars().next().is_some()
}
/// If the substring starting at the current position of the parser has
/// the given prefix, then bump the parser to the character immediately
/// following the prefix and return true. Otherwise, don't bump the parser
/// and return false.
fn bump_if(&self, prefix: &str) -> bool {
if self.pattern()[self.offset()..].starts_with(prefix) {
for _ in 0..prefix.chars().count() {
self.bump();
}
true
} else {
false
}
}
/// Returns true if and only if the parser is positioned at a look-around
/// prefix. The conditions under which this returns true must always
/// correspond to a regular expression that would otherwise be consider
/// invalid.
///
/// This should only be called immediately after parsing the opening of
/// a group or a set of flags.
fn is_lookaround_prefix(&self) -> bool {
self.bump_if("?=")
|| self.bump_if("?!")
|| self.bump_if("?<=")
|| self.bump_if("?<!")
}
/// Bump the parser, and if the `x` flag is enabled, bump through any
/// subsequent spaces. Return true if and only if the parser is not at
/// EOF.
fn bump_and_bump_space(&self) -> bool {
if !self.bump() {
return false;
}
self.bump_space();
!self.is_eof()
}
/// If the `x` flag is enabled (i.e., whitespace insensitivity with
/// comments), then this will advance the parser through all whitespace
/// and comments to the next non-whitespace non-comment byte.
///
/// If the `x` flag is disabled, then this is a no-op.
///
/// This should be used selectively throughout the parser where
/// arbitrary whitespace is permitted when the `x` flag is enabled. For
/// example, `{ 5 , 6}` is equivalent to `{5,6}`.
fn bump_space(&self) {
if !self.ignore_whitespace() {
return;
}
while !self.is_eof() {
if self.char().is_whitespace() {
self.bump();
} else if self.char() == '#' {
let start = self.pos();
let mut comment_text = String::new();
self.bump();
while !self.is_eof() {
let c = self.char();
self.bump();
if c == '\n' {
break;
}
comment_text.push(c);
}
let comment = ast::Comment {
span: Span::new(start, self.pos()),
comment: comment_text,
};
self.parser().comments.borrow_mut().push(comment);
} else {
break;
}
}
}
/// Peek at the next character in the input without advancing the parser.
///
/// If the input has been exhausted, then this returns `None`.
fn peek(&self) -> Option<char> {
if self.is_eof() {
return None;
}
self.pattern()[self.offset() + self.char().len_utf8()..].chars().next()
}
/// Like peek, but will ignore spaces when the parser is in whitespace
/// insensitive mode.
fn peek_space(&self) -> Option<char> {
if !self.ignore_whitespace() {
return self.peek();
}
if self.is_eof() {
return None;
}
let mut start = self.offset() + self.char().len_utf8();
let mut in_comment = false;
for (i, c) in self.pattern()[start..].char_indices() {
if c.is_whitespace() {
continue;
} else if !in_comment && c == '#' {
in_comment = true;
} else if in_comment && c == '\n' {
in_comment = false;
} else {
start += i;
break;
}
}
self.pattern()[start..].chars().next()
}
/// Returns true if the next call to `bump` would return false.
fn is_eof(&self) -> bool {
self.offset() == self.pattern().len()
}
/// Return the current position of the parser, which includes the offset,
/// line and column.
fn pos(&self) -> Position {
self.parser().pos.get()
}
/// Create a span at the current position of the parser. Both the start
/// and end of the span are set.
fn span(&self) -> Span {
Span::splat(self.pos())
}
/// Create a span that covers the current character.
fn span_char(&self) -> Span {
let mut next = Position {
offset: self.offset().checked_add(self.char().len_utf8()).unwrap(),
line: self.line(),
column: self.column().checked_add(1).unwrap(),
};
if self.char() == '\n' {
next.line += 1;
next.column = 1;
}
Span::new(self.pos(), next)
}
/// Parse and push a single alternation on to the parser's internal stack.
/// If the top of the stack already has an alternation, then add to that
/// instead of pushing a new one.
///
/// The concatenation given corresponds to a single alternation branch.
/// The concatenation returned starts the next branch and is empty.
///
/// This assumes the parser is currently positioned at `|` and will advance
/// the parser to the character following `|`.
#[inline(never)]
fn push_alternate(&self, mut concat: ast::Concat) -> Result<ast::Concat> {
assert_eq!(self.char(), '|');
concat.span.end = self.pos();
self.push_or_add_alternation(concat);
self.bump();
Ok(ast::Concat { span: self.span(), asts: vec![] })
}
/// Pushes or adds the given branch of an alternation to the parser's
/// internal stack of state.
fn push_or_add_alternation(&self, concat: ast::Concat) {
use self::GroupState::*;
let mut stack = self.parser().stack_group.borrow_mut();
if let Some(&mut Alternation(ref mut alts)) = stack.last_mut() {
alts.asts.push(concat.into_ast());
return;
}
stack.push(Alternation(ast::Alternation {
span: Span::new(concat.span.start, self.pos()),
asts: vec![concat.into_ast()],
}));
}
/// Parse and push a group AST (and its parent concatenation) on to the
/// parser's internal stack. Return a fresh concatenation corresponding
/// to the group's sub-AST.
///
/// If a set of flags was found (with no group), then the concatenation
/// is returned with that set of flags added.
///
/// This assumes that the parser is currently positioned on the opening
/// parenthesis. It advances the parser to the character at the start
/// of the sub-expression (or adjoining expression).
///
/// If there was a problem parsing the start of the group, then an error
/// is returned.
#[inline(never)]
fn push_group(&self, mut concat: ast::Concat) -> Result<ast::Concat> {
assert_eq!(self.char(), '(');
match self.parse_group()? {
Either::Left(set) => {
let ignore = set.flags.flag_state(ast::Flag::IgnoreWhitespace);
if let Some(v) = ignore {
self.parser().ignore_whitespace.set(v);
}
concat.asts.push(Ast::Flags(set));
Ok(concat)
}
Either::Right(group) => {
let old_ignore_whitespace = self.ignore_whitespace();
let new_ignore_whitespace = group
.flags()
.and_then(|f| f.flag_state(ast::Flag::IgnoreWhitespace))
.unwrap_or(old_ignore_whitespace);
self.parser().stack_group.borrow_mut().push(
GroupState::Group {
concat,
group,
ignore_whitespace: old_ignore_whitespace,
},
);
self.parser().ignore_whitespace.set(new_ignore_whitespace);
Ok(ast::Concat { span: self.span(), asts: vec![] })
}
}
}
/// Pop a group AST from the parser's internal stack and set the group's
/// AST to the given concatenation. Return the concatenation containing
/// the group.
///
/// This assumes that the parser is currently positioned on the closing
/// parenthesis and advances the parser to the character following the `)`.
///
/// If no such group could be popped, then an unopened group error is
/// returned.
#[inline(never)]
fn pop_group(&self, mut group_concat: ast::Concat) -> Result<ast::Concat> {
use self::GroupState::*;
assert_eq!(self.char(), ')');
let mut stack = self.parser().stack_group.borrow_mut();
let (mut prior_concat, mut group, ignore_whitespace, alt) = match stack
.pop()
{
Some(Group { concat, group, ignore_whitespace }) => {
(concat, group, ignore_whitespace, None)
}
Some(Alternation(alt)) => match stack.pop() {
Some(Group { concat, group, ignore_whitespace }) => {
(concat, group, ignore_whitespace, Some(alt))
}
None | Some(Alternation(_)) => {
return Err(self.error(
self.span_char(),
ast::ErrorKind::GroupUnopened,
));
}
},
None => {
return Err(self
.error(self.span_char(), ast::ErrorKind::GroupUnopened));
}
};
self.parser().ignore_whitespace.set(ignore_whitespace);
group_concat.span.end = self.pos();
self.bump();
group.span.end = self.pos();
match alt {
Some(mut alt) => {
alt.span.end = group_concat.span.end;
alt.asts.push(group_concat.into_ast());
group.ast = Box::new(alt.into_ast());
}
None => {
group.ast = Box::new(group_concat.into_ast());
}
}
prior_concat.asts.push(Ast::Group(group));
Ok(prior_concat)
}
/// Pop the last state from the parser's internal stack, if it exists, and
/// add the given concatenation to it. There either must be no state or a
/// single alternation item on the stack. Any other scenario produces an
/// error.
///
/// This assumes that the parser has advanced to the end.
#[inline(never)]
fn pop_group_end(&self, mut concat: ast::Concat) -> Result<Ast> {
concat.span.end = self.pos();
let mut stack = self.parser().stack_group.borrow_mut();
let ast = match stack.pop() {
None => Ok(concat.into_ast()),
Some(GroupState::Alternation(mut alt)) => {
alt.span.end = self.pos();
alt.asts.push(concat.into_ast());
Ok(Ast::Alternation(alt))
}
Some(GroupState::Group { group, .. }) => {
return Err(
self.error(group.span, ast::ErrorKind::GroupUnclosed)
);
}
};
// If we try to pop again, there should be nothing.
match stack.pop() {
None => ast,
Some(GroupState::Alternation(_)) => {
// This unreachable is unfortunate. This case can't happen
// because the only way we can be here is if there were two
// `GroupState::Alternation`s adjacent in the parser's stack,
// which we guarantee to never happen because we never push a
// `GroupState::Alternation` if one is already at the top of
// the stack.
unreachable!()
}
Some(GroupState::Group { group, .. }) => {
Err(self.error(group.span, ast::ErrorKind::GroupUnclosed))
}
}
}
/// Parse the opening of a character class and push the current class
/// parsing context onto the parser's stack. This assumes that the parser
/// is positioned at an opening `[`. The given union should correspond to
/// the union of set items built up before seeing the `[`.
///
/// If there was a problem parsing the opening of the class, then an error
/// is returned. Otherwise, a new union of set items for the class is
/// returned (which may be populated with either a `]` or a `-`).
#[inline(never)]
fn push_class_open(
&self,
parent_union: ast::ClassSetUnion,
) -> Result<ast::ClassSetUnion> {
assert_eq!(self.char(), '[');
let (nested_set, nested_union) = self.parse_set_class_open()?;
self.parser()
.stack_class
.borrow_mut()
.push(ClassState::Open { union: parent_union, set: nested_set });
Ok(nested_union)
}
/// Parse the end of a character class set and pop the character class
/// parser stack. The union given corresponds to the last union built
/// before seeing the closing `]`. The union returned corresponds to the
/// parent character class set with the nested class added to it.
///
/// This assumes that the parser is positioned at a `]` and will advance
/// the parser to the byte immediately following the `]`.
///
/// If the stack is empty after popping, then this returns the final
/// "top-level" character class AST (where a "top-level" character class
/// is one that is not nested inside any other character class).
///
/// If there is no corresponding opening bracket on the parser's stack,
/// then an error is returned.
#[inline(never)]
fn pop_class(
&self,
nested_union: ast::ClassSetUnion,
) -> Result<Either<ast::ClassSetUnion, ast::Class>> {
assert_eq!(self.char(), ']');
let item = ast::ClassSet::Item(nested_union.into_item());
let prevset = self.pop_class_op(item);
let mut stack = self.parser().stack_class.borrow_mut();
match stack.pop() {
None => {
// We can never observe an empty stack:
//
// 1) We are guaranteed to start with a non-empty stack since
// the character class parser is only initiated when it sees
// a `[`.
// 2) If we ever observe an empty stack while popping after
// seeing a `]`, then we signal the character class parser
// to terminate.
panic!("unexpected empty character class stack")
}
Some(ClassState::Op { .. }) => {
// This panic is unfortunate, but this case is impossible
// since we already popped the Op state if one exists above.
// Namely, every push to the class parser stack is guarded by
// whether an existing Op is already on the top of the stack.
// If it is, the existing Op is modified. That is, the stack
// can never have consecutive Op states.
panic!("unexpected ClassState::Op")
}
Some(ClassState::Open { mut union, mut set }) => {
self.bump();
set.span.end = self.pos();
set.kind = prevset;
if stack.is_empty() {
Ok(Either::Right(ast::Class::Bracketed(set)))
} else {
union.push(ast::ClassSetItem::Bracketed(Box::new(set)));
Ok(Either::Left(union))
}
}
}
}
/// Return an "unclosed class" error whose span points to the most
/// recently opened class.
///
/// This should only be called while parsing a character class.
#[inline(never)]
fn unclosed_class_error(&self) -> ast::Error {
for state in self.parser().stack_class.borrow().iter().rev() {
if let ClassState::Open { ref set, .. } = *state {
return self.error(set.span, ast::ErrorKind::ClassUnclosed);
}
}
// We are guaranteed to have a non-empty stack with at least
// one open bracket, so we should never get here.
panic!("no open character class found")
}
/// Push the current set of class items on to the class parser's stack as
/// the left hand side of the given operator.
///
/// A fresh set union is returned, which should be used to build the right
/// hand side of this operator.
#[inline(never)]
fn push_class_op(
&self,
next_kind: ast::ClassSetBinaryOpKind,
next_union: ast::ClassSetUnion,
) -> ast::ClassSetUnion {
let item = ast::ClassSet::Item(next_union.into_item());
let new_lhs = self.pop_class_op(item);
self.parser()
.stack_class
.borrow_mut()
.push(ClassState::Op { kind: next_kind, lhs: new_lhs });
ast::ClassSetUnion { span: self.span(), items: vec![] }
}
/// Pop a character class set from the character class parser stack. If the
/// top of the stack is just an item (not an operation), then return the
/// given set unchanged. If the top of the stack is an operation, then the
/// given set will be used as the rhs of the operation on the top of the
/// stack. In that case, the binary operation is returned as a set.
#[inline(never)]
fn pop_class_op(&self, rhs: ast::ClassSet) -> ast::ClassSet {
let mut stack = self.parser().stack_class.borrow_mut();
let (kind, lhs) = match stack.pop() {
Some(ClassState::Op { kind, lhs }) => (kind, lhs),
Some(state @ ClassState::Open { .. }) => {
stack.push(state);
return rhs;
}
None => unreachable!(),
};
let span = Span::new(lhs.span().start, rhs.span().end);
ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp {
span,
kind,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
})
}
}
impl<'s, P: Borrow<Parser>> ParserI<'s, P> {
/// Parse the regular expression into an abstract syntax tree.
fn parse(&self) -> Result<Ast> {
self.parse_with_comments().map(|astc| astc.ast)
}
/// Parse the regular expression and return an abstract syntax tree with
/// all of the comments found in the pattern.
fn parse_with_comments(&self) -> Result<ast::WithComments> {
assert_eq!(self.offset(), 0, "parser can only be used once");
self.parser().reset();
let mut concat = ast::Concat { span: self.span(), asts: vec![] };
loop {
self.bump_space();
if self.is_eof() {
break;
}
match self.char() {
'(' => concat = self.push_group(concat)?,
')' => concat = self.pop_group(concat)?,
'|' => concat = self.push_alternate(concat)?,
'[' => {
let class = self.parse_set_class()?;
concat.asts.push(Ast::Class(class));
}
'?' => {
concat = self.parse_uncounted_repetition(
concat,
ast::RepetitionKind::ZeroOrOne,
)?;
}
'*' => {
concat = self.parse_uncounted_repetition(
concat,
ast::RepetitionKind::ZeroOrMore,
)?;
}
'+' => {
concat = self.parse_uncounted_repetition(
concat,
ast::RepetitionKind::OneOrMore,
)?;
}
'{' => {
concat = self.parse_counted_repetition(concat)?;
}
_ => concat.asts.push(self.parse_primitive()?.into_ast()),
}
}
let ast = self.pop_group_end(concat)?;
NestLimiter::new(self).check(&ast)?;
Ok(ast::WithComments {
ast,
comments: mem::replace(
&mut *self.parser().comments.borrow_mut(),
vec![],
),
})
}
/// Parses an uncounted repetition operation. An uncounted repetition
/// operator includes ?, * and +, but does not include the {m,n} syntax.
/// The given `kind` should correspond to the operator observed by the
/// caller.
///
/// This assumes that the parser is currently positioned at the repetition
/// operator and advances the parser to the first character after the
/// operator. (Note that the operator may include a single additional `?`,
/// which makes the operator ungreedy.)
///
/// The caller should include the concatenation that is being built. The
/// concatenation returned includes the repetition operator applied to the
/// last expression in the given concatenation.
#[inline(never)]
fn parse_uncounted_repetition(
&self,
mut concat: ast::Concat,
kind: ast::RepetitionKind,
) -> Result<ast::Concat> {
assert!(
self.char() == '?' || self.char() == '*' || self.char() == '+'
);
let op_start = self.pos();
let ast = match concat.asts.pop() {
Some(ast) => ast,
None => {
return Err(
self.error(self.span(), ast::ErrorKind::RepetitionMissing)
)
}
};
match ast {
Ast::Empty(_) | Ast::Flags(_) => {
return Err(
self.error(self.span(), ast::ErrorKind::RepetitionMissing)
)
}
_ => {}
}
let mut greedy = true;
if self.bump() && self.char() == '?' {
greedy = false;
self.bump();
}
concat.asts.push(Ast::Repetition(ast::Repetition {
span: ast.span().with_end(self.pos()),
op: ast::RepetitionOp {
span: Span::new(op_start, self.pos()),
kind,
},
greedy,
ast: Box::new(ast),
}));
Ok(concat)
}
/// Parses a counted repetition operation. A counted repetition operator
/// corresponds to the {m,n} syntax, and does not include the ?, * or +
/// operators.
///
/// This assumes that the parser is currently positioned at the opening `{`
/// and advances the parser to the first character after the operator.
/// (Note that the operator may include a single additional `?`, which
/// makes the operator ungreedy.)
///
/// The caller should include the concatenation that is being built. The
/// concatenation returned includes the repetition operator applied to the
/// last expression in the given concatenation.
#[inline(never)]
fn parse_counted_repetition(
&self,
mut concat: ast::Concat,
) -> Result<ast::Concat> {
assert!(self.char() == '{');
let start = self.pos();
let ast = match concat.asts.pop() {
Some(ast) => ast,
None => {
return Err(
self.error(self.span(), ast::ErrorKind::RepetitionMissing)
)
}
};
match ast {
Ast::Empty(_) | Ast::Flags(_) => {
return Err(
self.error(self.span(), ast::ErrorKind::RepetitionMissing)
)
}
_ => {}
}
if !self.bump_and_bump_space() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::RepetitionCountUnclosed,
));
}
let count_start = specialize_err(
self.parse_decimal(),
ast::ErrorKind::DecimalEmpty,
ast::ErrorKind::RepetitionCountDecimalEmpty,
)?;
let mut range = ast::RepetitionRange::Exactly(count_start);
if self.is_eof() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::RepetitionCountUnclosed,
));
}
if self.char() == ',' {
if !self.bump_and_bump_space() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::RepetitionCountUnclosed,
));
}
if self.char() != '}' {
let count_end = specialize_err(
self.parse_decimal(),
ast::ErrorKind::DecimalEmpty,
ast::ErrorKind::RepetitionCountDecimalEmpty,
)?;
range = ast::RepetitionRange::Bounded(count_start, count_end);
} else {
range = ast::RepetitionRange::AtLeast(count_start);
}
}
if self.is_eof() || self.char() != '}' {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::RepetitionCountUnclosed,
));
}
let mut greedy = true;
if self.bump_and_bump_space() && self.char() == '?' {
greedy = false;
self.bump();
}
let op_span = Span::new(start, self.pos());
if !range.is_valid() {
return Err(
self.error(op_span, ast::ErrorKind::RepetitionCountInvalid)
);
}
concat.asts.push(Ast::Repetition(ast::Repetition {
span: ast.span().with_end(self.pos()),
op: ast::RepetitionOp {
span: op_span,
kind: ast::RepetitionKind::Range(range),
},
greedy,
ast: Box::new(ast),
}));
Ok(concat)
}
/// Parse a group (which contains a sub-expression) or a set of flags.
///
/// If a group was found, then it is returned with an empty AST. If a set
/// of flags is found, then that set is returned.
///
/// The parser should be positioned at the opening parenthesis.
///
/// This advances the parser to the character before the start of the
/// sub-expression (in the case of a group) or to the closing parenthesis
/// immediately following the set of flags.
///
/// # Errors
///
/// If flags are given and incorrectly specified, then a corresponding
/// error is returned.
///
/// If a capture name is given and it is incorrectly specified, then a
/// corresponding error is returned.
#[inline(never)]
fn parse_group(&self) -> Result<Either<ast::SetFlags, ast::Group>> {
assert_eq!(self.char(), '(');
let open_span = self.span_char();
self.bump();
self.bump_space();
if self.is_lookaround_prefix() {
return Err(self.error(
Span::new(open_span.start, self.span().end),
ast::ErrorKind::UnsupportedLookAround,
));
}
let inner_span = self.span();
let mut starts_with_p = true;
if self.bump_if("?P<") || {
starts_with_p = false;
self.bump_if("?<")
} {
let capture_index = self.next_capture_index(open_span)?;
let name = self.parse_capture_name(capture_index)?;
Ok(Either::Right(ast::Group {
span: open_span,
kind: ast::GroupKind::CaptureName { starts_with_p, name },
ast: Box::new(Ast::Empty(self.span())),
}))
} else if self.bump_if("?") {
if self.is_eof() {
return Err(
self.error(open_span, ast::ErrorKind::GroupUnclosed)
);
}
let flags = self.parse_flags()?;
let char_end = self.char();
self.bump();
if char_end == ')' {
// We don't allow empty flags, e.g., `(?)`. We instead
// interpret it as a repetition operator missing its argument.
if flags.items.is_empty() {
return Err(self.error(
inner_span,
ast::ErrorKind::RepetitionMissing,
));
}
Ok(Either::Left(ast::SetFlags {
span: Span { end: self.pos(), ..open_span },
flags,
}))
} else {
assert_eq!(char_end, ':');
Ok(Either::Right(ast::Group {
span: open_span,
kind: ast::GroupKind::NonCapturing(flags),
ast: Box::new(Ast::Empty(self.span())),
}))
}
} else {
let capture_index = self.next_capture_index(open_span)?;
Ok(Either::Right(ast::Group {
span: open_span,
kind: ast::GroupKind::CaptureIndex(capture_index),
ast: Box::new(Ast::Empty(self.span())),
}))
}
}
/// Parses a capture group name. Assumes that the parser is positioned at
/// the first character in the name following the opening `<` (and may
/// possibly be EOF). This advances the parser to the first character
/// following the closing `>`.
///
/// The caller must provide the capture index of the group for this name.
#[inline(never)]
fn parse_capture_name(
&self,
capture_index: u32,
) -> Result<ast::CaptureName> {
if self.is_eof() {
return Err(self
.error(self.span(), ast::ErrorKind::GroupNameUnexpectedEof));
}
let start = self.pos();
loop {
if self.char() == '>' {
break;
}
if !is_capture_char(self.char(), self.pos() == start) {
return Err(self.error(
self.span_char(),
ast::ErrorKind::GroupNameInvalid,
));
}
if !self.bump() {
break;
}
}
let end = self.pos();
if self.is_eof() {
return Err(self
.error(self.span(), ast::ErrorKind::GroupNameUnexpectedEof));
}
assert_eq!(self.char(), '>');
self.bump();
let name = &self.pattern()[start.offset..end.offset];
if name.is_empty() {
return Err(self.error(
Span::new(start, start),
ast::ErrorKind::GroupNameEmpty,
));
}
let capname = ast::CaptureName {
span: Span::new(start, end),
name: name.to_string(),
index: capture_index,
};
self.add_capture_name(&capname)?;
Ok(capname)
}
/// Parse a sequence of flags starting at the current character.
///
/// This advances the parser to the character immediately following the
/// flags, which is guaranteed to be either `:` or `)`.
///
/// # Errors
///
/// If any flags are duplicated, then an error is returned.
///
/// If the negation operator is used more than once, then an error is
/// returned.
///
/// If no flags could be found or if the negation operation is not followed
/// by any flags, then an error is returned.
#[inline(never)]
fn parse_flags(&self) -> Result<ast::Flags> {
let mut flags = ast::Flags { span: self.span(), items: vec![] };
let mut last_was_negation = None;
while self.char() != ':' && self.char() != ')' {
if self.char() == '-' {
last_was_negation = Some(self.span_char());
let item = ast::FlagsItem {
span: self.span_char(),
kind: ast::FlagsItemKind::Negation,
};
if let Some(i) = flags.add_item(item) {
return Err(self.error(
self.span_char(),
ast::ErrorKind::FlagRepeatedNegation {
original: flags.items[i].span,
},
));
}
} else {
last_was_negation = None;
let item = ast::FlagsItem {
span: self.span_char(),
kind: ast::FlagsItemKind::Flag(self.parse_flag()?),
};
if let Some(i) = flags.add_item(item) {
return Err(self.error(
self.span_char(),
ast::ErrorKind::FlagDuplicate {
original: flags.items[i].span,
},
));
}
}
if !self.bump() {
return Err(
self.error(self.span(), ast::ErrorKind::FlagUnexpectedEof)
);
}
}
if let Some(span) = last_was_negation {
return Err(self.error(span, ast::ErrorKind::FlagDanglingNegation));
}
flags.span.end = self.pos();
Ok(flags)
}
/// Parse the current character as a flag. Do not advance the parser.
///
/// # Errors
///
/// If the flag is not recognized, then an error is returned.
#[inline(never)]
fn parse_flag(&self) -> Result<ast::Flag> {
match self.char() {
'i' => Ok(ast::Flag::CaseInsensitive),
'm' => Ok(ast::Flag::MultiLine),
's' => Ok(ast::Flag::DotMatchesNewLine),
'U' => Ok(ast::Flag::SwapGreed),
'u' => Ok(ast::Flag::Unicode),
'R' => Ok(ast::Flag::CRLF),
'x' => Ok(ast::Flag::IgnoreWhitespace),
_ => {
Err(self
.error(self.span_char(), ast::ErrorKind::FlagUnrecognized))
}
}
}
/// Parse a primitive AST. e.g., A literal, non-set character class or
/// assertion.
///
/// This assumes that the parser expects a primitive at the current
/// location. i.e., All other non-primitive cases have been handled.
/// For example, if the parser's position is at `|`, then `|` will be
/// treated as a literal (e.g., inside a character class).
///
/// This advances the parser to the first character immediately following
/// the primitive.
fn parse_primitive(&self) -> Result<Primitive> {
match self.char() {
'\\' => self.parse_escape(),
'.' => {
let ast = Primitive::Dot(self.span_char());
self.bump();
Ok(ast)
}
'^' => {
let ast = Primitive::Assertion(ast::Assertion {
span: self.span_char(),
kind: ast::AssertionKind::StartLine,
});
self.bump();
Ok(ast)
}
'$' => {
let ast = Primitive::Assertion(ast::Assertion {
span: self.span_char(),
kind: ast::AssertionKind::EndLine,
});
self.bump();
Ok(ast)
}
c => {
let ast = Primitive::Literal(ast::Literal {
span: self.span_char(),
kind: ast::LiteralKind::Verbatim,
c,
});
self.bump();
Ok(ast)
}
}
}
/// Parse an escape sequence as a primitive AST.
///
/// This assumes the parser is positioned at the start of the escape
/// sequence, i.e., `\`. It advances the parser to the first position
/// immediately following the escape sequence.
#[inline(never)]
fn parse_escape(&self) -> Result<Primitive> {
assert_eq!(self.char(), '\\');
let start = self.pos();
if !self.bump() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::EscapeUnexpectedEof,
));
}
let c = self.char();
// Put some of the more complicated routines into helpers.
match c {
'0'..='7' => {
if !self.parser().octal {
return Err(self.error(
Span::new(start, self.span_char().end),
ast::ErrorKind::UnsupportedBackreference,
));
}
let mut lit = self.parse_octal();
lit.span.start = start;
return Ok(Primitive::Literal(lit));
}
'8'..='9' if !self.parser().octal => {
return Err(self.error(
Span::new(start, self.span_char().end),
ast::ErrorKind::UnsupportedBackreference,
));
}
'x' | 'u' | 'U' => {
let mut lit = self.parse_hex()?;
lit.span.start = start;
return Ok(Primitive::Literal(lit));
}
'p' | 'P' => {
let mut cls = self.parse_unicode_class()?;
cls.span.start = start;
return Ok(Primitive::Unicode(cls));
}
'd' | 's' | 'w' | 'D' | 'S' | 'W' => {
let mut cls = self.parse_perl_class();
cls.span.start = start;
return Ok(Primitive::Perl(cls));
}
_ => {}
}
// Handle all of the one letter sequences inline.
self.bump();
let span = Span::new(start, self.pos());
if is_meta_character(c) {
return Ok(Primitive::Literal(ast::Literal {
span,
kind: ast::LiteralKind::Meta,
c,
}));
}
if is_escapeable_character(c) {
return Ok(Primitive::Literal(ast::Literal {
span,
kind: ast::LiteralKind::Superfluous,
c,
}));
}
let special = |kind, c| {
Ok(Primitive::Literal(ast::Literal {
span,
kind: ast::LiteralKind::Special(kind),
c,
}))
};
match c {
'a' => special(ast::SpecialLiteralKind::Bell, '\x07'),
'f' => special(ast::SpecialLiteralKind::FormFeed, '\x0C'),
't' => special(ast::SpecialLiteralKind::Tab, '\t'),
'n' => special(ast::SpecialLiteralKind::LineFeed, '\n'),
'r' => special(ast::SpecialLiteralKind::CarriageReturn, '\r'),
'v' => special(ast::SpecialLiteralKind::VerticalTab, '\x0B'),
'A' => Ok(Primitive::Assertion(ast::Assertion {
span,
kind: ast::AssertionKind::StartText,
})),
'z' => Ok(Primitive::Assertion(ast::Assertion {
span,
kind: ast::AssertionKind::EndText,
})),
'b' => Ok(Primitive::Assertion(ast::Assertion {
span,
kind: ast::AssertionKind::WordBoundary,
})),
'B' => Ok(Primitive::Assertion(ast::Assertion {
span,
kind: ast::AssertionKind::NotWordBoundary,
})),
_ => Err(self.error(span, ast::ErrorKind::EscapeUnrecognized)),
}
}
/// Parse an octal representation of a Unicode codepoint up to 3 digits
/// long. This expects the parser to be positioned at the first octal
/// digit and advances the parser to the first character immediately
/// following the octal number. This also assumes that parsing octal
/// escapes is enabled.
///
/// Assuming the preconditions are met, this routine can never fail.
#[inline(never)]
fn parse_octal(&self) -> ast::Literal {
assert!(self.parser().octal);
assert!('0' <= self.char() && self.char() <= '7');
let start = self.pos();
// Parse up to two more digits.
while self.bump()
&& '0' <= self.char()
&& self.char() <= '7'
&& self.pos().offset - start.offset <= 2
{}
let end = self.pos();
let octal = &self.pattern()[start.offset..end.offset];
// Parsing the octal should never fail since the above guarantees a
// valid number.
let codepoint =
u32::from_str_radix(octal, 8).expect("valid octal number");
// The max value for 3 digit octal is 0777 = 511 and [0, 511] has no
// invalid Unicode scalar values.
let c = char::from_u32(codepoint).expect("Unicode scalar value");
ast::Literal {
span: Span::new(start, end),
kind: ast::LiteralKind::Octal,
c,
}
}
/// Parse a hex representation of a Unicode codepoint. This handles both
/// hex notations, i.e., `\xFF` and `\x{FFFF}`. This expects the parser to
/// be positioned at the `x`, `u` or `U` prefix. The parser is advanced to
/// the first character immediately following the hexadecimal literal.
#[inline(never)]
fn parse_hex(&self) -> Result<ast::Literal> {
assert!(
self.char() == 'x' || self.char() == 'u' || self.char() == 'U'
);
let hex_kind = match self.char() {
'x' => ast::HexLiteralKind::X,
'u' => ast::HexLiteralKind::UnicodeShort,
_ => ast::HexLiteralKind::UnicodeLong,
};
if !self.bump_and_bump_space() {
return Err(
self.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof)
);
}
if self.char() == '{' {
self.parse_hex_brace(hex_kind)
} else {
self.parse_hex_digits(hex_kind)
}
}
/// Parse an N-digit hex representation of a Unicode codepoint. This
/// expects the parser to be positioned at the first digit and will advance
/// the parser to the first character immediately following the escape
/// sequence.
///
/// The number of digits given must be 2 (for `\xNN`), 4 (for `\uNNNN`)
/// or 8 (for `\UNNNNNNNN`).
#[inline(never)]
fn parse_hex_digits(
&self,
kind: ast::HexLiteralKind,
) -> Result<ast::Literal> {
let mut scratch = self.parser().scratch.borrow_mut();
scratch.clear();
let start = self.pos();
for i in 0..kind.digits() {
if i > 0 && !self.bump_and_bump_space() {
return Err(self
.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof));
}
if !is_hex(self.char()) {
return Err(self.error(
self.span_char(),
ast::ErrorKind::EscapeHexInvalidDigit,
));
}
scratch.push(self.char());
}
// The final bump just moves the parser past the literal, which may
// be EOF.
self.bump_and_bump_space();
let end = self.pos();
let hex = scratch.as_str();
match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) {
None => Err(self.error(
Span::new(start, end),
ast::ErrorKind::EscapeHexInvalid,
)),
Some(c) => Ok(ast::Literal {
span: Span::new(start, end),
kind: ast::LiteralKind::HexFixed(kind),
c,
}),
}
}
/// Parse a hex representation of any Unicode scalar value. This expects
/// the parser to be positioned at the opening brace `{` and will advance
/// the parser to the first character following the closing brace `}`.
#[inline(never)]
fn parse_hex_brace(
&self,
kind: ast::HexLiteralKind,
) -> Result<ast::Literal> {
let mut scratch = self.parser().scratch.borrow_mut();
scratch.clear();
let brace_pos = self.pos();
let start = self.span_char().end;
while self.bump_and_bump_space() && self.char() != '}' {
if !is_hex(self.char()) {
return Err(self.error(
self.span_char(),
ast::ErrorKind::EscapeHexInvalidDigit,
));
}
scratch.push(self.char());
}
if self.is_eof() {
return Err(self.error(
Span::new(brace_pos, self.pos()),
ast::ErrorKind::EscapeUnexpectedEof,
));
}
let end = self.pos();
let hex = scratch.as_str();
assert_eq!(self.char(), '}');
self.bump_and_bump_space();
if hex.is_empty() {
return Err(self.error(
Span::new(brace_pos, self.pos()),
ast::ErrorKind::EscapeHexEmpty,
));
}
match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) {
None => Err(self.error(
Span::new(start, end),
ast::ErrorKind::EscapeHexInvalid,
)),
Some(c) => Ok(ast::Literal {
span: Span::new(start, self.pos()),
kind: ast::LiteralKind::HexBrace(kind),
c,
}),
}
}
/// Parse a decimal number into a u32 while trimming leading and trailing
/// whitespace.
///
/// This expects the parser to be positioned at the first position where
/// a decimal digit could occur. This will advance the parser to the byte
/// immediately following the last contiguous decimal digit.
///
/// If no decimal digit could be found or if there was a problem parsing
/// the complete set of digits into a u32, then an error is returned.
fn parse_decimal(&self) -> Result<u32> {
let mut scratch = self.parser().scratch.borrow_mut();
scratch.clear();
while !self.is_eof() && self.char().is_whitespace() {
self.bump();
}
let start = self.pos();
while !self.is_eof() && '0' <= self.char() && self.char() <= '9' {
scratch.push(self.char());
self.bump_and_bump_space();
}
let span = Span::new(start, self.pos());
while !self.is_eof() && self.char().is_whitespace() {
self.bump_and_bump_space();
}
let digits = scratch.as_str();
if digits.is_empty() {
return Err(self.error(span, ast::ErrorKind::DecimalEmpty));
}
match u32::from_str_radix(digits, 10).ok() {
Some(n) => Ok(n),
None => Err(self.error(span, ast::ErrorKind::DecimalInvalid)),
}
}
/// Parse a standard character class consisting primarily of characters or
/// character ranges, but can also contain nested character classes of
/// any type (sans `.`).
///
/// This assumes the parser is positioned at the opening `[`. If parsing
/// is successful, then the parser is advanced to the position immediately
/// following the closing `]`.
#[inline(never)]
fn parse_set_class(&self) -> Result<ast::Class> {
assert_eq!(self.char(), '[');
let mut union =
ast::ClassSetUnion { span: self.span(), items: vec![] };
loop {
self.bump_space();
if self.is_eof() {
return Err(self.unclosed_class_error());
}
match self.char() {
'[' => {
// If we've already parsed the opening bracket, then
// attempt to treat this as the beginning of an ASCII
// class. If ASCII class parsing fails, then the parser
// backs up to `[`.
if !self.parser().stack_class.borrow().is_empty() {
if let Some(cls) = self.maybe_parse_ascii_class() {
union.push(ast::ClassSetItem::Ascii(cls));
continue;
}
}
union = self.push_class_open(union)?;
}
']' => match self.pop_class(union)? {
Either::Left(nested_union) => {
union = nested_union;
}
Either::Right(class) => return Ok(class),
},
'&' if self.peek() == Some('&') => {
assert!(self.bump_if("&&"));
union = self.push_class_op(
ast::ClassSetBinaryOpKind::Intersection,
union,
);
}
'-' if self.peek() == Some('-') => {
assert!(self.bump_if("--"));
union = self.push_class_op(
ast::ClassSetBinaryOpKind::Difference,
union,
);
}
'~' if self.peek() == Some('~') => {
assert!(self.bump_if("~~"));
union = self.push_class_op(
ast::ClassSetBinaryOpKind::SymmetricDifference,
union,
);
}
_ => {
union.push(self.parse_set_class_range()?);
}
}
}
}
/// Parse a single primitive item in a character class set. The item to
/// be parsed can either be one of a simple literal character, a range
/// between two simple literal characters or a "primitive" character
/// class like \w or \p{Greek}.
///
/// If an invalid escape is found, or if a character class is found where
/// a simple literal is expected (e.g., in a range), then an error is
/// returned.
#[inline(never)]
fn parse_set_class_range(&self) -> Result<ast::ClassSetItem> {
let prim1 = self.parse_set_class_item()?;
self.bump_space();
if self.is_eof() {
return Err(self.unclosed_class_error());
}
// If the next char isn't a `-`, then we don't have a range.
// There are two exceptions. If the char after a `-` is a `]`, then
// `-` is interpreted as a literal `-`. Alternatively, if the char
// after a `-` is a `-`, then `--` corresponds to a "difference"
// operation.
if self.char() != '-'
|| self.peek_space() == Some(']')
|| self.peek_space() == Some('-')
{
return prim1.into_class_set_item(self);
}
// OK, now we're parsing a range, so bump past the `-` and parse the
// second half of the range.
if !self.bump_and_bump_space() {
return Err(self.unclosed_class_error());
}
let prim2 = self.parse_set_class_item()?;
let range = ast::ClassSetRange {
span: Span::new(prim1.span().start, prim2.span().end),
start: prim1.into_class_literal(self)?,
end: prim2.into_class_literal(self)?,
};
if !range.is_valid() {
return Err(
self.error(range.span, ast::ErrorKind::ClassRangeInvalid)
);
}
Ok(ast::ClassSetItem::Range(range))
}
/// Parse a single item in a character class as a primitive, where the
/// primitive either consists of a verbatim literal or a single escape
/// sequence.
///
/// This assumes the parser is positioned at the beginning of a primitive,
/// and advances the parser to the first position after the primitive if
/// successful.
///
/// Note that it is the caller's responsibility to report an error if an
/// illegal primitive was parsed.
#[inline(never)]
fn parse_set_class_item(&self) -> Result<Primitive> {
if self.char() == '\\' {
self.parse_escape()
} else {
let x = Primitive::Literal(ast::Literal {
span: self.span_char(),
kind: ast::LiteralKind::Verbatim,
c: self.char(),
});
self.bump();
Ok(x)
}
}
/// Parses the opening of a character class set. This includes the opening
/// bracket along with `^` if present to indicate negation. This also
/// starts parsing the opening set of unioned items if applicable, since
/// there are special rules applied to certain characters in the opening
/// of a character class. For example, `[^]]` is the class of all
/// characters not equal to `]`. (`]` would need to be escaped in any other
/// position.) Similarly for `-`.
///
/// In all cases, the op inside the returned `ast::ClassBracketed` is an
/// empty union. This empty union should be replaced with the actual item
/// when it is popped from the parser's stack.
///
/// This assumes the parser is positioned at the opening `[` and advances
/// the parser to the first non-special byte of the character class.
///
/// An error is returned if EOF is found.
#[inline(never)]
fn parse_set_class_open(
&self,
) -> Result<(ast::ClassBracketed, ast::ClassSetUnion)> {
assert_eq!(self.char(), '[');
let start = self.pos();
if !self.bump_and_bump_space() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::ClassUnclosed,
));
}
let negated = if self.char() != '^' {
false
} else {
if !self.bump_and_bump_space() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::ClassUnclosed,
));
}
true
};
// Accept any number of `-` as literal `-`.
let mut union =
ast::ClassSetUnion { span: self.span(), items: vec![] };
while self.char() == '-' {
union.push(ast::ClassSetItem::Literal(ast::Literal {
span: self.span_char(),
kind: ast::LiteralKind::Verbatim,
c: '-',
}));
if !self.bump_and_bump_space() {
return Err(self.error(
Span::new(start, start),
ast::ErrorKind::ClassUnclosed,
));
}
}
// If `]` is the *first* char in a set, then interpret it as a literal
// `]`. That is, an empty class is impossible to write.
if union.items.is_empty() && self.char() == ']' {
union.push(ast::ClassSetItem::Literal(ast::Literal {
span: self.span_char(),
kind: ast::LiteralKind::Verbatim,
c: ']',
}));
if !self.bump_and_bump_space() {
return Err(self.error(
Span::new(start, self.pos()),
ast::ErrorKind::ClassUnclosed,
));
}
}
let set = ast::ClassBracketed {
span: Span::new(start, self.pos()),
negated,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: Span::new(union.span.start, union.span.start),
items: vec![],
}),
};
Ok((set, union))
}
/// Attempt to parse an ASCII character class, e.g., `[:alnum:]`.
///
/// This assumes the parser is positioned at the opening `[`.
///
/// If no valid ASCII character class could be found, then this does not
/// advance the parser and `None` is returned. Otherwise, the parser is
/// advanced to the first byte following the closing `]` and the
/// corresponding ASCII class is returned.
#[inline(never)]
fn maybe_parse_ascii_class(&self) -> Option<ast::ClassAscii> {
// ASCII character classes are interesting from a parsing perspective
// because parsing cannot fail with any interesting error. For example,
// in order to use an ASCII character class, it must be enclosed in
// double brackets, e.g., `[[:alnum:]]`. Alternatively, you might think
// of it as "ASCII character characters have the syntax `[:NAME:]`
// which can only appear within character brackets." This means that
// things like `[[:lower:]A]` are legal constructs.
//
// However, if one types an incorrect ASCII character class, e.g.,
// `[[:loower:]]`, then we treat that as a normal nested character
// class containing the characters `:elorw`. One might argue that we
// should return an error instead since the repeated colons give away
// the intent to write an ASCII class. But what if the user typed
// `[[:lower]]` instead? How can we tell that was intended to be an
// ASCII class and not just a normal nested class?
//
// Reasonable people can probably disagree over this, but for better
// or worse, we implement semantics that never fails at the expense
// of better failure modes.
assert_eq!(self.char(), '[');
// If parsing fails, then we back up the parser to this starting point.
let start = self.pos();
let mut negated = false;
if !self.bump() || self.char() != ':' {
self.parser().pos.set(start);
return None;
}
if !self.bump() {
self.parser().pos.set(start);
return None;
}
if self.char() == '^' {
negated = true;
if !self.bump() {
self.parser().pos.set(start);
return None;
}
}
let name_start = self.offset();
while self.char() != ':' && self.bump() {}
if self.is_eof() {
self.parser().pos.set(start);
return None;
}
let name = &self.pattern()[name_start..self.offset()];
if !self.bump_if(":]") {
self.parser().pos.set(start);
return None;
}
let kind = match ast::ClassAsciiKind::from_name(name) {
Some(kind) => kind,
None => {
self.parser().pos.set(start);
return None;
}
};
Some(ast::ClassAscii {
span: Span::new(start, self.pos()),
kind,
negated,
})
}
/// Parse a Unicode class in either the single character notation, `\pN`
/// or the multi-character bracketed notation, `\p{Greek}`. This assumes
/// the parser is positioned at the `p` (or `P` for negation) and will
/// advance the parser to the character immediately following the class.
///
/// Note that this does not check whether the class name is valid or not.
#[inline(never)]
fn parse_unicode_class(&self) -> Result<ast::ClassUnicode> {
assert!(self.char() == 'p' || self.char() == 'P');
let mut scratch = self.parser().scratch.borrow_mut();
scratch.clear();
let negated = self.char() == 'P';
if !self.bump_and_bump_space() {
return Err(
self.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof)
);
}
let (start, kind) = if self.char() == '{' {
let start = self.span_char().end;
while self.bump_and_bump_space() && self.char() != '}' {
scratch.push(self.char());
}
if self.is_eof() {
return Err(self
.error(self.span(), ast::ErrorKind::EscapeUnexpectedEof));
}
assert_eq!(self.char(), '}');
self.bump();
let name = scratch.as_str();
if let Some(i) = name.find("!=") {
(
start,
ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::NotEqual,
name: name[..i].to_string(),
value: name[i + 2..].to_string(),
},
)
} else if let Some(i) = name.find(':') {
(
start,
ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::Colon,
name: name[..i].to_string(),
value: name[i + 1..].to_string(),
},
)
} else if let Some(i) = name.find('=') {
(
start,
ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::Equal,
name: name[..i].to_string(),
value: name[i + 1..].to_string(),
},
)
} else {
(start, ast::ClassUnicodeKind::Named(name.to_string()))
}
} else {
let start = self.pos();
let c = self.char();
if c == '\\' {
return Err(self.error(
self.span_char(),
ast::ErrorKind::UnicodeClassInvalid,
));
}
self.bump_and_bump_space();
let kind = ast::ClassUnicodeKind::OneLetter(c);
(start, kind)
};
Ok(ast::ClassUnicode {
span: Span::new(start, self.pos()),
negated,
kind,
})
}
/// Parse a Perl character class, e.g., `\d` or `\W`. This assumes the
/// parser is currently at a valid character class name and will be
/// advanced to the character immediately following the class.
#[inline(never)]
fn parse_perl_class(&self) -> ast::ClassPerl {
let c = self.char();
let span = self.span_char();
self.bump();
let (negated, kind) = match c {
'd' => (false, ast::ClassPerlKind::Digit),
'D' => (true, ast::ClassPerlKind::Digit),
's' => (false, ast::ClassPerlKind::Space),
'S' => (true, ast::ClassPerlKind::Space),
'w' => (false, ast::ClassPerlKind::Word),
'W' => (true, ast::ClassPerlKind::Word),
c => panic!("expected valid Perl class but got '{}'", c),
};
ast::ClassPerl { span, kind, negated }
}
}
/// A type that traverses a fully parsed Ast and checks whether its depth
/// exceeds the specified nesting limit. If it does, then an error is returned.
#[derive(Debug)]
struct NestLimiter<'p, 's, P> {
/// The parser that is checking the nest limit.
p: &'p ParserI<'s, P>,
/// The current depth while walking an Ast.
depth: u32,
}
impl<'p, 's, P: Borrow<Parser>> NestLimiter<'p, 's, P> {
fn new(p: &'p ParserI<'s, P>) -> NestLimiter<'p, 's, P> {
NestLimiter { p, depth: 0 }
}
#[inline(never)]
fn check(self, ast: &Ast) -> Result<()> {
ast::visit(ast, self)
}
fn increment_depth(&mut self, span: &Span) -> Result<()> {
let new = self.depth.checked_add(1).ok_or_else(|| {
self.p.error(
span.clone(),
ast::ErrorKind::NestLimitExceeded(u32::MAX),
)
})?;
let limit = self.p.parser().nest_limit;
if new > limit {
return Err(self.p.error(
span.clone(),
ast::ErrorKind::NestLimitExceeded(limit),
));
}
self.depth = new;
Ok(())
}
fn decrement_depth(&mut self) {
// Assuming the correctness of the visitor, this should never drop
// below 0.
self.depth = self.depth.checked_sub(1).unwrap();
}
}
impl<'p, 's, P: Borrow<Parser>> ast::Visitor for NestLimiter<'p, 's, P> {
type Output = ();
type Err = ast::Error;
fn finish(self) -> Result<()> {
Ok(())
}
fn visit_pre(&mut self, ast: &Ast) -> Result<()> {
let span = match *ast {
Ast::Empty(_)
| Ast::Flags(_)
| Ast::Literal(_)
| Ast::Dot(_)
| Ast::Assertion(_)
| Ast::Class(ast::Class::Unicode(_))
| Ast::Class(ast::Class::Perl(_)) => {
// These are all base cases, so we don't increment depth.
return Ok(());
}
Ast::Class(ast::Class::Bracketed(ref x)) => &x.span,
Ast::Repetition(ref x) => &x.span,
Ast::Group(ref x) => &x.span,
Ast::Alternation(ref x) => &x.span,
Ast::Concat(ref x) => &x.span,
};
self.increment_depth(span)
}
fn visit_post(&mut self, ast: &Ast) -> Result<()> {
match *ast {
Ast::Empty(_)
| Ast::Flags(_)
| Ast::Literal(_)
| Ast::Dot(_)
| Ast::Assertion(_)
| Ast::Class(ast::Class::Unicode(_))
| Ast::Class(ast::Class::Perl(_)) => {
// These are all base cases, so we don't decrement depth.
Ok(())
}
Ast::Class(ast::Class::Bracketed(_))
| Ast::Repetition(_)
| Ast::Group(_)
| Ast::Alternation(_)
| Ast::Concat(_) => {
self.decrement_depth();
Ok(())
}
}
}
fn visit_class_set_item_pre(
&mut self,
ast: &ast::ClassSetItem,
) -> Result<()> {
let span = match *ast {
ast::ClassSetItem::Empty(_)
| ast::ClassSetItem::Literal(_)
| ast::ClassSetItem::Range(_)
| ast::ClassSetItem::Ascii(_)
| ast::ClassSetItem::Unicode(_)
| ast::ClassSetItem::Perl(_) => {
// These are all base cases, so we don't increment depth.
return Ok(());
}
ast::ClassSetItem::Bracketed(ref x) => &x.span,
ast::ClassSetItem::Union(ref x) => &x.span,
};
self.increment_depth(span)
}
fn visit_class_set_item_post(
&mut self,
ast: &ast::ClassSetItem,
) -> Result<()> {
match *ast {
ast::ClassSetItem::Empty(_)
| ast::ClassSetItem::Literal(_)
| ast::ClassSetItem::Range(_)
| ast::ClassSetItem::Ascii(_)
| ast::ClassSetItem::Unicode(_)
| ast::ClassSetItem::Perl(_) => {
// These are all base cases, so we don't decrement depth.
Ok(())
}
ast::ClassSetItem::Bracketed(_) | ast::ClassSetItem::Union(_) => {
self.decrement_depth();
Ok(())
}
}
}
fn visit_class_set_binary_op_pre(
&mut self,
ast: &ast::ClassSetBinaryOp,
) -> Result<()> {
self.increment_depth(&ast.span)
}
fn visit_class_set_binary_op_post(
&mut self,
_ast: &ast::ClassSetBinaryOp,
) -> Result<()> {
self.decrement_depth();
Ok(())
}
}
/// When the result is an error, transforms the ast::ErrorKind from the source
/// Result into another one. This function is used to return clearer error
/// messages when possible.
fn specialize_err<T>(
result: Result<T>,
from: ast::ErrorKind,
to: ast::ErrorKind,
) -> Result<T> {
if let Err(e) = result {
if e.kind == from {
Err(ast::Error { kind: to, pattern: e.pattern, span: e.span })
} else {
Err(e)
}
} else {
result
}
}
#[cfg(test)]
mod tests {
use core::ops::Range;
use alloc::format;
use crate::ast::{self, Ast, Position, Span};
use super::*;
// Our own assert_eq, which has slightly better formatting (but honestly
// still kind of crappy).
macro_rules! assert_eq {
($left:expr, $right:expr) => {{
match (&$left, &$right) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
panic!(
"assertion failed: `(left == right)`\n\n\
left: `{:?}`\nright: `{:?}`\n\n",
left_val, right_val
)
}
}
}
}};
}
// We create these errors to compare with real ast::Errors in the tests.
// We define equality between TestError and ast::Error to disregard the
// pattern string in ast::Error, which is annoying to provide in tests.
#[derive(Clone, Debug)]
struct TestError {
span: Span,
kind: ast::ErrorKind,
}
impl PartialEq<ast::Error> for TestError {
fn eq(&self, other: &ast::Error) -> bool {
self.span == other.span && self.kind == other.kind
}
}
impl PartialEq<TestError> for ast::Error {
fn eq(&self, other: &TestError) -> bool {
self.span == other.span && self.kind == other.kind
}
}
fn s(str: &str) -> String {
str.to_string()
}
fn parser(pattern: &str) -> ParserI<'_, Parser> {
ParserI::new(Parser::new(), pattern)
}
fn parser_octal(pattern: &str) -> ParserI<'_, Parser> {
let parser = ParserBuilder::new().octal(true).build();
ParserI::new(parser, pattern)
}
fn parser_nest_limit(
pattern: &str,
nest_limit: u32,
) -> ParserI<'_, Parser> {
let p = ParserBuilder::new().nest_limit(nest_limit).build();
ParserI::new(p, pattern)
}
fn parser_ignore_whitespace(pattern: &str) -> ParserI<'_, Parser> {
let p = ParserBuilder::new().ignore_whitespace(true).build();
ParserI::new(p, pattern)
}
/// Short alias for creating a new span.
fn nspan(start: Position, end: Position) -> Span {
Span::new(start, end)
}
/// Short alias for creating a new position.
fn npos(offset: usize, line: usize, column: usize) -> Position {
Position::new(offset, line, column)
}
/// Create a new span from the given offset range. This assumes a single
/// line and sets the columns based on the offsets. i.e., This only works
/// out of the box for ASCII, which is fine for most tests.
fn span(range: Range<usize>) -> Span {
let start = Position::new(range.start, 1, range.start + 1);
let end = Position::new(range.end, 1, range.end + 1);
Span::new(start, end)
}
/// Create a new span for the corresponding byte range in the given string.
fn span_range(subject: &str, range: Range<usize>) -> Span {
let start = Position {
offset: range.start,
line: 1 + subject[..range.start].matches('\n').count(),
column: 1 + subject[..range.start]
.chars()
.rev()
.position(|c| c == '\n')
.unwrap_or(subject[..range.start].chars().count()),
};
let end = Position {
offset: range.end,
line: 1 + subject[..range.end].matches('\n').count(),
column: 1 + subject[..range.end]
.chars()
.rev()
.position(|c| c == '\n')
.unwrap_or(subject[..range.end].chars().count()),
};
Span::new(start, end)
}
/// Create a verbatim literal starting at the given position.
fn lit(c: char, start: usize) -> Ast {
lit_with(c, span(start..start + c.len_utf8()))
}
/// Create a meta literal starting at the given position.
fn meta_lit(c: char, span: Span) -> Ast {
Ast::Literal(ast::Literal { span, kind: ast::LiteralKind::Meta, c })
}
/// Create a verbatim literal with the given span.
fn lit_with(c: char, span: Span) -> Ast {
Ast::Literal(ast::Literal {
span,
kind: ast::LiteralKind::Verbatim,
c,
})
}
/// Create a concatenation with the given range.
fn concat(range: Range<usize>, asts: Vec<Ast>) -> Ast {
concat_with(span(range), asts)
}
/// Create a concatenation with the given span.
fn concat_with(span: Span, asts: Vec<Ast>) -> Ast {
Ast::Concat(ast::Concat { span, asts })
}
/// Create an alternation with the given span.
fn alt(range: Range<usize>, asts: Vec<Ast>) -> Ast {
Ast::Alternation(ast::Alternation { span: span(range), asts })
}
/// Create a capturing group with the given span.
fn group(range: Range<usize>, index: u32, ast: Ast) -> Ast {
Ast::Group(ast::Group {
span: span(range),
kind: ast::GroupKind::CaptureIndex(index),
ast: Box::new(ast),
})
}
/// Create an ast::SetFlags.
///
/// The given pattern should be the full pattern string. The range given
/// should correspond to the byte offsets where the flag set occurs.
///
/// If negated is true, then the set is interpreted as beginning with a
/// negation.
fn flag_set(
pat: &str,
range: Range<usize>,
flag: ast::Flag,
negated: bool,
) -> Ast {
let mut items = vec![ast::FlagsItem {
span: span_range(pat, (range.end - 2)..(range.end - 1)),
kind: ast::FlagsItemKind::Flag(flag),
}];
if negated {
items.insert(
0,
ast::FlagsItem {
span: span_range(pat, (range.start + 2)..(range.end - 2)),
kind: ast::FlagsItemKind::Negation,
},
);
}
Ast::Flags(ast::SetFlags {
span: span_range(pat, range.clone()),
flags: ast::Flags {
span: span_range(pat, (range.start + 2)..(range.end - 1)),
items,
},
})
}
#[test]
fn parse_nest_limit() {
// A nest limit of 0 still allows some types of regexes.
assert_eq!(
parser_nest_limit("", 0).parse(),
Ok(Ast::Empty(span(0..0)))
);
assert_eq!(parser_nest_limit("a", 0).parse(), Ok(lit('a', 0)));
// Test repetition operations, which require one level of nesting.
assert_eq!(
parser_nest_limit("a+", 0).parse().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::NestLimitExceeded(0),
}
);
assert_eq!(
parser_nest_limit("a+", 1).parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::OneOrMore,
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser_nest_limit("(a)+", 1).parse().unwrap_err(),
TestError {
span: span(0..3),
kind: ast::ErrorKind::NestLimitExceeded(1),
}
);
assert_eq!(
parser_nest_limit("a+*", 1).parse().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::NestLimitExceeded(1),
}
);
assert_eq!(
parser_nest_limit("a+*", 2).parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..3),
op: ast::RepetitionOp {
span: span(2..3),
kind: ast::RepetitionKind::ZeroOrMore,
},
greedy: true,
ast: Box::new(Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::OneOrMore,
},
greedy: true,
ast: Box::new(lit('a', 0)),
})),
}))
);
// Test concatenations. A concatenation requires one level of nesting.
assert_eq!(
parser_nest_limit("ab", 0).parse().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::NestLimitExceeded(0),
}
);
assert_eq!(
parser_nest_limit("ab", 1).parse(),
Ok(concat(0..2, vec![lit('a', 0), lit('b', 1)]))
);
assert_eq!(
parser_nest_limit("abc", 1).parse(),
Ok(concat(0..3, vec![lit('a', 0), lit('b', 1), lit('c', 2)]))
);
// Test alternations. An alternation requires one level of nesting.
assert_eq!(
parser_nest_limit("a|b", 0).parse().unwrap_err(),
TestError {
span: span(0..3),
kind: ast::ErrorKind::NestLimitExceeded(0),
}
);
assert_eq!(
parser_nest_limit("a|b", 1).parse(),
Ok(alt(0..3, vec![lit('a', 0), lit('b', 2)]))
);
assert_eq!(
parser_nest_limit("a|b|c", 1).parse(),
Ok(alt(0..5, vec![lit('a', 0), lit('b', 2), lit('c', 4)]))
);
// Test character classes. Classes form their own mini-recursive
// syntax!
assert_eq!(
parser_nest_limit("[a]", 0).parse().unwrap_err(),
TestError {
span: span(0..3),
kind: ast::ErrorKind::NestLimitExceeded(0),
}
);
assert_eq!(
parser_nest_limit("[a]", 1).parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..3),
negated: false,
kind: ast::ClassSet::Item(ast::ClassSetItem::Literal(
ast::Literal {
span: span(1..2),
kind: ast::LiteralKind::Verbatim,
c: 'a',
}
)),
})))
);
assert_eq!(
parser_nest_limit("[ab]", 1).parse().unwrap_err(),
TestError {
span: span(1..3),
kind: ast::ErrorKind::NestLimitExceeded(1),
}
);
assert_eq!(
parser_nest_limit("[ab[cd]]", 2).parse().unwrap_err(),
TestError {
span: span(3..7),
kind: ast::ErrorKind::NestLimitExceeded(2),
}
);
assert_eq!(
parser_nest_limit("[ab[cd]]", 3).parse().unwrap_err(),
TestError {
span: span(4..6),
kind: ast::ErrorKind::NestLimitExceeded(3),
}
);
assert_eq!(
parser_nest_limit("[a--b]", 1).parse().unwrap_err(),
TestError {
span: span(1..5),
kind: ast::ErrorKind::NestLimitExceeded(1),
}
);
assert_eq!(
parser_nest_limit("[a--bc]", 2).parse().unwrap_err(),
TestError {
span: span(4..6),
kind: ast::ErrorKind::NestLimitExceeded(2),
}
);
}
#[test]
fn parse_comments() {
let pat = "(?x)
# This is comment 1.
foo # This is comment 2.
# This is comment 3.
bar
# This is comment 4.";
let astc = parser(pat).parse_with_comments().unwrap();
assert_eq!(
astc.ast,
concat_with(
span_range(pat, 0..pat.len()),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
lit_with('f', span_range(pat, 26..27)),
lit_with('o', span_range(pat, 27..28)),
lit_with('o', span_range(pat, 28..29)),
lit_with('b', span_range(pat, 74..75)),
lit_with('a', span_range(pat, 75..76)),
lit_with('r', span_range(pat, 76..77)),
]
)
);
assert_eq!(
astc.comments,
vec![
ast::Comment {
span: span_range(pat, 5..26),
comment: s(" This is comment 1."),
},
ast::Comment {
span: span_range(pat, 30..51),
comment: s(" This is comment 2."),
},
ast::Comment {
span: span_range(pat, 53..74),
comment: s(" This is comment 3."),
},
ast::Comment {
span: span_range(pat, 78..98),
comment: s(" This is comment 4."),
},
]
);
}
#[test]
fn parse_holistic() {
assert_eq!(parser("]").parse(), Ok(lit(']', 0)));
assert_eq!(
parser(r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#\&\-\~").parse(),
Ok(concat(
0..36,
vec![
meta_lit('\\', span(0..2)),
meta_lit('.', span(2..4)),
meta_lit('+', span(4..6)),
meta_lit('*', span(6..8)),
meta_lit('?', span(8..10)),
meta_lit('(', span(10..12)),
meta_lit(')', span(12..14)),
meta_lit('|', span(14..16)),
meta_lit('[', span(16..18)),
meta_lit(']', span(18..20)),
meta_lit('{', span(20..22)),
meta_lit('}', span(22..24)),
meta_lit('^', span(24..26)),
meta_lit('$', span(26..28)),
meta_lit('#', span(28..30)),
meta_lit('&', span(30..32)),
meta_lit('-', span(32..34)),
meta_lit('~', span(34..36)),
]
))
);
}
#[test]
fn parse_ignore_whitespace() {
// Test that basic whitespace insensitivity works.
let pat = "(?x)a b";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
nspan(npos(0, 1, 1), npos(7, 1, 8)),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))),
lit_with('b', nspan(npos(6, 1, 7), npos(7, 1, 8))),
]
))
);
// Test that we can toggle whitespace insensitivity.
let pat = "(?x)a b(?-x)a b";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
nspan(npos(0, 1, 1), npos(15, 1, 16)),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))),
lit_with('b', nspan(npos(6, 1, 7), npos(7, 1, 8))),
flag_set(pat, 7..12, ast::Flag::IgnoreWhitespace, true),
lit_with('a', nspan(npos(12, 1, 13), npos(13, 1, 14))),
lit_with(' ', nspan(npos(13, 1, 14), npos(14, 1, 15))),
lit_with('b', nspan(npos(14, 1, 15), npos(15, 1, 16))),
]
))
);
// Test that nesting whitespace insensitive flags works.
let pat = "a (?x:a )a ";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..11),
vec![
lit_with('a', span_range(pat, 0..1)),
lit_with(' ', span_range(pat, 1..2)),
Ast::Group(ast::Group {
span: span_range(pat, 2..9),
kind: ast::GroupKind::NonCapturing(ast::Flags {
span: span_range(pat, 4..5),
items: vec![ast::FlagsItem {
span: span_range(pat, 4..5),
kind: ast::FlagsItemKind::Flag(
ast::Flag::IgnoreWhitespace
),
},],
}),
ast: Box::new(lit_with('a', span_range(pat, 6..7))),
}),
lit_with('a', span_range(pat, 9..10)),
lit_with(' ', span_range(pat, 10..11)),
]
))
);
// Test that whitespace after an opening paren is insignificant.
let pat = "(?x)( ?P<foo> a )";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..pat.len()),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
Ast::Group(ast::Group {
span: span_range(pat, 4..pat.len()),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: span_range(pat, 9..12),
name: s("foo"),
index: 1,
}
},
ast: Box::new(lit_with('a', span_range(pat, 14..15))),
}),
]
))
);
let pat = "(?x)( a )";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..pat.len()),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
Ast::Group(ast::Group {
span: span_range(pat, 4..pat.len()),
kind: ast::GroupKind::CaptureIndex(1),
ast: Box::new(lit_with('a', span_range(pat, 7..8))),
}),
]
))
);
let pat = "(?x)( ?: a )";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..pat.len()),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
Ast::Group(ast::Group {
span: span_range(pat, 4..pat.len()),
kind: ast::GroupKind::NonCapturing(ast::Flags {
span: span_range(pat, 8..8),
items: vec![],
}),
ast: Box::new(lit_with('a', span_range(pat, 11..12))),
}),
]
))
);
let pat = r"(?x)\x { 53 }";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..pat.len()),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
Ast::Literal(ast::Literal {
span: span(4..13),
kind: ast::LiteralKind::HexBrace(
ast::HexLiteralKind::X
),
c: 'S',
}),
]
))
);
// Test that whitespace after an escape is OK.
let pat = r"(?x)\ ";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..pat.len()),
vec![
flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false),
Ast::Literal(ast::Literal {
span: span_range(pat, 4..6),
kind: ast::LiteralKind::Superfluous,
c: ' ',
}),
]
))
);
}
#[test]
fn parse_newlines() {
let pat = ".\n.";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..3),
vec![
Ast::Dot(span_range(pat, 0..1)),
lit_with('\n', span_range(pat, 1..2)),
Ast::Dot(span_range(pat, 2..3)),
]
))
);
let pat = "foobar\nbaz\nquux\n";
assert_eq!(
parser(pat).parse(),
Ok(concat_with(
span_range(pat, 0..pat.len()),
vec![
lit_with('f', nspan(npos(0, 1, 1), npos(1, 1, 2))),
lit_with('o', nspan(npos(1, 1, 2), npos(2, 1, 3))),
lit_with('o', nspan(npos(2, 1, 3), npos(3, 1, 4))),
lit_with('b', nspan(npos(3, 1, 4), npos(4, 1, 5))),
lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))),
lit_with('r', nspan(npos(5, 1, 6), npos(6, 1, 7))),
lit_with('\n', nspan(npos(6, 1, 7), npos(7, 2, 1))),
lit_with('b', nspan(npos(7, 2, 1), npos(8, 2, 2))),
lit_with('a', nspan(npos(8, 2, 2), npos(9, 2, 3))),
lit_with('z', nspan(npos(9, 2, 3), npos(10, 2, 4))),
lit_with('\n', nspan(npos(10, 2, 4), npos(11, 3, 1))),
lit_with('q', nspan(npos(11, 3, 1), npos(12, 3, 2))),
lit_with('u', nspan(npos(12, 3, 2), npos(13, 3, 3))),
lit_with('u', nspan(npos(13, 3, 3), npos(14, 3, 4))),
lit_with('x', nspan(npos(14, 3, 4), npos(15, 3, 5))),
lit_with('\n', nspan(npos(15, 3, 5), npos(16, 4, 1))),
]
))
);
}
#[test]
fn parse_uncounted_repetition() {
assert_eq!(
parser(r"a*").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::ZeroOrMore,
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a+").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::OneOrMore,
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a?").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a??").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..3),
op: ast::RepetitionOp {
span: span(1..3),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: false,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a?").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a?b").parse(),
Ok(concat(
0..3,
vec![
Ast::Repetition(ast::Repetition {
span: span(0..2),
op: ast::RepetitionOp {
span: span(1..2),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: true,
ast: Box::new(lit('a', 0)),
}),
lit('b', 2),
]
))
);
assert_eq!(
parser(r"a??b").parse(),
Ok(concat(
0..4,
vec![
Ast::Repetition(ast::Repetition {
span: span(0..3),
op: ast::RepetitionOp {
span: span(1..3),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: false,
ast: Box::new(lit('a', 0)),
}),
lit('b', 3),
]
))
);
assert_eq!(
parser(r"ab?").parse(),
Ok(concat(
0..3,
vec![
lit('a', 0),
Ast::Repetition(ast::Repetition {
span: span(1..3),
op: ast::RepetitionOp {
span: span(2..3),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: true,
ast: Box::new(lit('b', 1)),
}),
]
))
);
assert_eq!(
parser(r"(ab)?").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..5),
op: ast::RepetitionOp {
span: span(4..5),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: true,
ast: Box::new(group(
0..4,
1,
concat(1..3, vec![lit('a', 1), lit('b', 2),])
)),
}))
);
assert_eq!(
parser(r"|a?").parse(),
Ok(alt(
0..3,
vec![
Ast::Empty(span(0..0)),
Ast::Repetition(ast::Repetition {
span: span(1..3),
op: ast::RepetitionOp {
span: span(2..3),
kind: ast::RepetitionKind::ZeroOrOne,
},
greedy: true,
ast: Box::new(lit('a', 1)),
}),
]
))
);
assert_eq!(
parser(r"*").parse().unwrap_err(),
TestError {
span: span(0..0),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"(?i)*").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"(*)").parse().unwrap_err(),
TestError {
span: span(1..1),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"(?:?)").parse().unwrap_err(),
TestError {
span: span(3..3),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"+").parse().unwrap_err(),
TestError {
span: span(0..0),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"?").parse().unwrap_err(),
TestError {
span: span(0..0),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"(?)").parse().unwrap_err(),
TestError {
span: span(1..1),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"|*").parse().unwrap_err(),
TestError {
span: span(1..1),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"|+").parse().unwrap_err(),
TestError {
span: span(1..1),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"|?").parse().unwrap_err(),
TestError {
span: span(1..1),
kind: ast::ErrorKind::RepetitionMissing,
}
);
}
#[test]
fn parse_counted_repetition() {
assert_eq!(
parser(r"a{5}").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..4),
op: ast::RepetitionOp {
span: span(1..4),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Exactly(5)
),
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a{5,}").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..5),
op: ast::RepetitionOp {
span: span(1..5),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::AtLeast(5)
),
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a{5,9}").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..6),
op: ast::RepetitionOp {
span: span(1..6),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Bounded(5, 9)
),
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a{5}?").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..5),
op: ast::RepetitionOp {
span: span(1..5),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Exactly(5)
),
},
greedy: false,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"ab{5}").parse(),
Ok(concat(
0..5,
vec![
lit('a', 0),
Ast::Repetition(ast::Repetition {
span: span(1..5),
op: ast::RepetitionOp {
span: span(2..5),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Exactly(5)
),
},
greedy: true,
ast: Box::new(lit('b', 1)),
}),
]
))
);
assert_eq!(
parser(r"ab{5}c").parse(),
Ok(concat(
0..6,
vec![
lit('a', 0),
Ast::Repetition(ast::Repetition {
span: span(1..5),
op: ast::RepetitionOp {
span: span(2..5),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Exactly(5)
),
},
greedy: true,
ast: Box::new(lit('b', 1)),
}),
lit('c', 5),
]
))
);
assert_eq!(
parser(r"a{ 5 }").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..6),
op: ast::RepetitionOp {
span: span(1..6),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Exactly(5)
),
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"a{ 5 , 9 }").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..10),
op: ast::RepetitionOp {
span: span(1..10),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Bounded(5, 9)
),
},
greedy: true,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser_ignore_whitespace(r"a{5,9} ?").parse(),
Ok(Ast::Repetition(ast::Repetition {
span: span(0..8),
op: ast::RepetitionOp {
span: span(1..8),
kind: ast::RepetitionKind::Range(
ast::RepetitionRange::Bounded(5, 9)
),
},
greedy: false,
ast: Box::new(lit('a', 0)),
}))
);
assert_eq!(
parser(r"(?i){0}").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"(?m){1,1}").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"a{]}").parse().unwrap_err(),
TestError {
span: span(2..2),
kind: ast::ErrorKind::RepetitionCountDecimalEmpty,
}
);
assert_eq!(
parser(r"a{1,]}").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::RepetitionCountDecimalEmpty,
}
);
assert_eq!(
parser(r"a{").parse().unwrap_err(),
TestError {
span: span(1..2),
kind: ast::ErrorKind::RepetitionCountUnclosed,
}
);
assert_eq!(
parser(r"a{}").parse().unwrap_err(),
TestError {
span: span(2..2),
kind: ast::ErrorKind::RepetitionCountDecimalEmpty,
}
);
assert_eq!(
parser(r"a{a").parse().unwrap_err(),
TestError {
span: span(2..2),
kind: ast::ErrorKind::RepetitionCountDecimalEmpty,
}
);
assert_eq!(
parser(r"a{9999999999}").parse().unwrap_err(),
TestError {
span: span(2..12),
kind: ast::ErrorKind::DecimalInvalid,
}
);
assert_eq!(
parser(r"a{9").parse().unwrap_err(),
TestError {
span: span(1..3),
kind: ast::ErrorKind::RepetitionCountUnclosed,
}
);
assert_eq!(
parser(r"a{9,a").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::RepetitionCountDecimalEmpty,
}
);
assert_eq!(
parser(r"a{9,9999999999}").parse().unwrap_err(),
TestError {
span: span(4..14),
kind: ast::ErrorKind::DecimalInvalid,
}
);
assert_eq!(
parser(r"a{9,").parse().unwrap_err(),
TestError {
span: span(1..4),
kind: ast::ErrorKind::RepetitionCountUnclosed,
}
);
assert_eq!(
parser(r"a{9,11").parse().unwrap_err(),
TestError {
span: span(1..6),
kind: ast::ErrorKind::RepetitionCountUnclosed,
}
);
assert_eq!(
parser(r"a{2,1}").parse().unwrap_err(),
TestError {
span: span(1..6),
kind: ast::ErrorKind::RepetitionCountInvalid,
}
);
assert_eq!(
parser(r"{5}").parse().unwrap_err(),
TestError {
span: span(0..0),
kind: ast::ErrorKind::RepetitionMissing,
}
);
assert_eq!(
parser(r"|{5}").parse().unwrap_err(),
TestError {
span: span(1..1),
kind: ast::ErrorKind::RepetitionMissing,
}
);
}
#[test]
fn parse_alternate() {
assert_eq!(
parser(r"a|b").parse(),
Ok(Ast::Alternation(ast::Alternation {
span: span(0..3),
asts: vec![lit('a', 0), lit('b', 2)],
}))
);
assert_eq!(
parser(r"(a|b)").parse(),
Ok(group(
0..5,
1,
Ast::Alternation(ast::Alternation {
span: span(1..4),
asts: vec![lit('a', 1), lit('b', 3)],
})
))
);
assert_eq!(
parser(r"a|b|c").parse(),
Ok(Ast::Alternation(ast::Alternation {
span: span(0..5),
asts: vec![lit('a', 0), lit('b', 2), lit('c', 4)],
}))
);
assert_eq!(
parser(r"ax|by|cz").parse(),
Ok(Ast::Alternation(ast::Alternation {
span: span(0..8),
asts: vec![
concat(0..2, vec![lit('a', 0), lit('x', 1)]),
concat(3..5, vec![lit('b', 3), lit('y', 4)]),
concat(6..8, vec![lit('c', 6), lit('z', 7)]),
],
}))
);
assert_eq!(
parser(r"(ax|by|cz)").parse(),
Ok(group(
0..10,
1,
Ast::Alternation(ast::Alternation {
span: span(1..9),
asts: vec![
concat(1..3, vec![lit('a', 1), lit('x', 2)]),
concat(4..6, vec![lit('b', 4), lit('y', 5)]),
concat(7..9, vec![lit('c', 7), lit('z', 8)]),
],
})
))
);
assert_eq!(
parser(r"(ax|(by|(cz)))").parse(),
Ok(group(
0..14,
1,
alt(
1..13,
vec![
concat(1..3, vec![lit('a', 1), lit('x', 2)]),
group(
4..13,
2,
alt(
5..12,
vec![
concat(
5..7,
vec![lit('b', 5), lit('y', 6)]
),
group(
8..12,
3,
concat(
9..11,
vec![lit('c', 9), lit('z', 10),]
)
),
]
)
),
]
)
))
);
assert_eq!(
parser(r"|").parse(),
Ok(alt(
0..1,
vec![Ast::Empty(span(0..0)), Ast::Empty(span(1..1)),]
))
);
assert_eq!(
parser(r"||").parse(),
Ok(alt(
0..2,
vec![
Ast::Empty(span(0..0)),
Ast::Empty(span(1..1)),
Ast::Empty(span(2..2)),
]
))
);
assert_eq!(
parser(r"a|").parse(),
Ok(alt(0..2, vec![lit('a', 0), Ast::Empty(span(2..2)),]))
);
assert_eq!(
parser(r"|a").parse(),
Ok(alt(0..2, vec![Ast::Empty(span(0..0)), lit('a', 1),]))
);
assert_eq!(
parser(r"(|)").parse(),
Ok(group(
0..3,
1,
alt(
1..2,
vec![Ast::Empty(span(1..1)), Ast::Empty(span(2..2)),]
)
))
);
assert_eq!(
parser(r"(a|)").parse(),
Ok(group(
0..4,
1,
alt(1..3, vec![lit('a', 1), Ast::Empty(span(3..3)),])
))
);
assert_eq!(
parser(r"(|a)").parse(),
Ok(group(
0..4,
1,
alt(1..3, vec![Ast::Empty(span(1..1)), lit('a', 2),])
))
);
assert_eq!(
parser(r"a|b)").parse().unwrap_err(),
TestError {
span: span(3..4),
kind: ast::ErrorKind::GroupUnopened,
}
);
assert_eq!(
parser(r"(a|b").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::GroupUnclosed,
}
);
}
#[test]
fn parse_unsupported_lookaround() {
assert_eq!(
parser(r"(?=a)").parse().unwrap_err(),
TestError {
span: span(0..3),
kind: ast::ErrorKind::UnsupportedLookAround,
}
);
assert_eq!(
parser(r"(?!a)").parse().unwrap_err(),
TestError {
span: span(0..3),
kind: ast::ErrorKind::UnsupportedLookAround,
}
);
assert_eq!(
parser(r"(?<=a)").parse().unwrap_err(),
TestError {
span: span(0..4),
kind: ast::ErrorKind::UnsupportedLookAround,
}
);
assert_eq!(
parser(r"(?<!a)").parse().unwrap_err(),
TestError {
span: span(0..4),
kind: ast::ErrorKind::UnsupportedLookAround,
}
);
}
#[test]
fn parse_group() {
assert_eq!(
parser("(?i)").parse(),
Ok(Ast::Flags(ast::SetFlags {
span: span(0..4),
flags: ast::Flags {
span: span(2..3),
items: vec![ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
}],
},
}))
);
assert_eq!(
parser("(?iU)").parse(),
Ok(Ast::Flags(ast::SetFlags {
span: span(0..5),
flags: ast::Flags {
span: span(2..4),
items: vec![
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(3..4),
kind: ast::FlagsItemKind::Flag(
ast::Flag::SwapGreed
),
},
],
},
}))
);
assert_eq!(
parser("(?i-U)").parse(),
Ok(Ast::Flags(ast::SetFlags {
span: span(0..6),
flags: ast::Flags {
span: span(2..5),
items: vec![
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(3..4),
kind: ast::FlagsItemKind::Negation,
},
ast::FlagsItem {
span: span(4..5),
kind: ast::FlagsItemKind::Flag(
ast::Flag::SwapGreed
),
},
],
},
}))
);
assert_eq!(
parser("()").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..2),
kind: ast::GroupKind::CaptureIndex(1),
ast: Box::new(Ast::Empty(span(1..1))),
}))
);
assert_eq!(
parser("(a)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..3),
kind: ast::GroupKind::CaptureIndex(1),
ast: Box::new(lit('a', 1)),
}))
);
assert_eq!(
parser("(())").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..4),
kind: ast::GroupKind::CaptureIndex(1),
ast: Box::new(Ast::Group(ast::Group {
span: span(1..3),
kind: ast::GroupKind::CaptureIndex(2),
ast: Box::new(Ast::Empty(span(2..2))),
})),
}))
);
assert_eq!(
parser("(?:a)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..5),
kind: ast::GroupKind::NonCapturing(ast::Flags {
span: span(2..2),
items: vec![],
}),
ast: Box::new(lit('a', 3)),
}))
);
assert_eq!(
parser("(?i:a)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..6),
kind: ast::GroupKind::NonCapturing(ast::Flags {
span: span(2..3),
items: vec![ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},],
}),
ast: Box::new(lit('a', 4)),
}))
);
assert_eq!(
parser("(?i-U:a)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..8),
kind: ast::GroupKind::NonCapturing(ast::Flags {
span: span(2..5),
items: vec![
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(3..4),
kind: ast::FlagsItemKind::Negation,
},
ast::FlagsItem {
span: span(4..5),
kind: ast::FlagsItemKind::Flag(
ast::Flag::SwapGreed
),
},
],
}),
ast: Box::new(lit('a', 6)),
}))
);
assert_eq!(
parser("(").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::GroupUnclosed,
}
);
assert_eq!(
parser("(?").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::GroupUnclosed,
}
);
assert_eq!(
parser("(?P").parse().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::FlagUnrecognized,
}
);
assert_eq!(
parser("(?P<").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::GroupNameUnexpectedEof,
}
);
assert_eq!(
parser("(a").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::GroupUnclosed,
}
);
assert_eq!(
parser("(()").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::GroupUnclosed,
}
);
assert_eq!(
parser(")").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::GroupUnopened,
}
);
assert_eq!(
parser("a)").parse().unwrap_err(),
TestError {
span: span(1..2),
kind: ast::ErrorKind::GroupUnopened,
}
);
}
#[test]
fn parse_capture_name() {
assert_eq!(
parser("(?<a>z)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..7),
kind: ast::GroupKind::CaptureName {
starts_with_p: false,
name: ast::CaptureName {
span: span(3..4),
name: s("a"),
index: 1,
}
},
ast: Box::new(lit('z', 5)),
}))
);
assert_eq!(
parser("(?P<a>z)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..8),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: span(4..5),
name: s("a"),
index: 1,
}
},
ast: Box::new(lit('z', 6)),
}))
);
assert_eq!(
parser("(?P<abc>z)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..10),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: span(4..7),
name: s("abc"),
index: 1,
}
},
ast: Box::new(lit('z', 8)),
}))
);
assert_eq!(
parser("(?P<a_1>z)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..10),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: span(4..7),
name: s("a_1"),
index: 1,
}
},
ast: Box::new(lit('z', 8)),
}))
);
assert_eq!(
parser("(?P<a.1>z)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..10),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: span(4..7),
name: s("a.1"),
index: 1,
}
},
ast: Box::new(lit('z', 8)),
}))
);
assert_eq!(
parser("(?P<a[1]>z)").parse(),
Ok(Ast::Group(ast::Group {
span: span(0..11),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: span(4..8),
name: s("a[1]"),
index: 1,
}
},
ast: Box::new(lit('z', 9)),
}))
);
assert_eq!(
parser("(?P<a¾>)").parse(),
Ok(Ast::Group(ast::Group {
span: Span::new(
Position::new(0, 1, 1),
Position::new(9, 1, 9),
),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: Span::new(
Position::new(4, 1, 5),
Position::new(7, 1, 7),
),
name: s("a¾"),
index: 1,
}
},
ast: Box::new(Ast::Empty(Span::new(
Position::new(8, 1, 8),
Position::new(8, 1, 8),
))),
}))
);
assert_eq!(
parser("(?P<名字>)").parse(),
Ok(Ast::Group(ast::Group {
span: Span::new(
Position::new(0, 1, 1),
Position::new(12, 1, 9),
),
kind: ast::GroupKind::CaptureName {
starts_with_p: true,
name: ast::CaptureName {
span: Span::new(
Position::new(4, 1, 5),
Position::new(10, 1, 7),
),
name: s("名字"),
index: 1,
}
},
ast: Box::new(Ast::Empty(Span::new(
Position::new(11, 1, 8),
Position::new(11, 1, 8),
))),
}))
);
assert_eq!(
parser("(?P<").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::GroupNameUnexpectedEof,
}
);
assert_eq!(
parser("(?P<>z)").parse().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::GroupNameEmpty,
}
);
assert_eq!(
parser("(?P<a").parse().unwrap_err(),
TestError {
span: span(5..5),
kind: ast::ErrorKind::GroupNameUnexpectedEof,
}
);
assert_eq!(
parser("(?P<ab").parse().unwrap_err(),
TestError {
span: span(6..6),
kind: ast::ErrorKind::GroupNameUnexpectedEof,
}
);
assert_eq!(
parser("(?P<0a").parse().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<~").parse().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<abc~").parse().unwrap_err(),
TestError {
span: span(7..8),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<a>y)(?P<a>z)").parse().unwrap_err(),
TestError {
span: span(12..13),
kind: ast::ErrorKind::GroupNameDuplicate {
original: span(4..5),
},
}
);
assert_eq!(
parser("(?P<5>)").parse().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<5a>)").parse().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<¾>)").parse().unwrap_err(),
TestError {
span: Span::new(
Position::new(4, 1, 5),
Position::new(6, 1, 6),
),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<¾a>)").parse().unwrap_err(),
TestError {
span: Span::new(
Position::new(4, 1, 5),
Position::new(6, 1, 6),
),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<☃>)").parse().unwrap_err(),
TestError {
span: Span::new(
Position::new(4, 1, 5),
Position::new(7, 1, 6),
),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
assert_eq!(
parser("(?P<a☃>)").parse().unwrap_err(),
TestError {
span: Span::new(
Position::new(5, 1, 6),
Position::new(8, 1, 7),
),
kind: ast::ErrorKind::GroupNameInvalid,
}
);
}
#[test]
fn parse_flags() {
assert_eq!(
parser("i:").parse_flags(),
Ok(ast::Flags {
span: span(0..1),
items: vec![ast::FlagsItem {
span: span(0..1),
kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive),
}],
})
);
assert_eq!(
parser("i)").parse_flags(),
Ok(ast::Flags {
span: span(0..1),
items: vec![ast::FlagsItem {
span: span(0..1),
kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive),
}],
})
);
assert_eq!(
parser("isU:").parse_flags(),
Ok(ast::Flags {
span: span(0..3),
items: vec![
ast::FlagsItem {
span: span(0..1),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(1..2),
kind: ast::FlagsItemKind::Flag(
ast::Flag::DotMatchesNewLine
),
},
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed),
},
],
})
);
assert_eq!(
parser("-isU:").parse_flags(),
Ok(ast::Flags {
span: span(0..4),
items: vec![
ast::FlagsItem {
span: span(0..1),
kind: ast::FlagsItemKind::Negation,
},
ast::FlagsItem {
span: span(1..2),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::DotMatchesNewLine
),
},
ast::FlagsItem {
span: span(3..4),
kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed),
},
],
})
);
assert_eq!(
parser("i-sU:").parse_flags(),
Ok(ast::Flags {
span: span(0..4),
items: vec![
ast::FlagsItem {
span: span(0..1),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(1..2),
kind: ast::FlagsItemKind::Negation,
},
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::DotMatchesNewLine
),
},
ast::FlagsItem {
span: span(3..4),
kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed),
},
],
})
);
assert_eq!(
parser("i-sR:").parse_flags(),
Ok(ast::Flags {
span: span(0..4),
items: vec![
ast::FlagsItem {
span: span(0..1),
kind: ast::FlagsItemKind::Flag(
ast::Flag::CaseInsensitive
),
},
ast::FlagsItem {
span: span(1..2),
kind: ast::FlagsItemKind::Negation,
},
ast::FlagsItem {
span: span(2..3),
kind: ast::FlagsItemKind::Flag(
ast::Flag::DotMatchesNewLine
),
},
ast::FlagsItem {
span: span(3..4),
kind: ast::FlagsItemKind::Flag(ast::Flag::CRLF),
},
],
})
);
assert_eq!(
parser("isU").parse_flags().unwrap_err(),
TestError {
span: span(3..3),
kind: ast::ErrorKind::FlagUnexpectedEof,
}
);
assert_eq!(
parser("isUa:").parse_flags().unwrap_err(),
TestError {
span: span(3..4),
kind: ast::ErrorKind::FlagUnrecognized,
}
);
assert_eq!(
parser("isUi:").parse_flags().unwrap_err(),
TestError {
span: span(3..4),
kind: ast::ErrorKind::FlagDuplicate { original: span(0..1) },
}
);
assert_eq!(
parser("i-sU-i:").parse_flags().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::FlagRepeatedNegation {
original: span(1..2),
},
}
);
assert_eq!(
parser("-)").parse_flags().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::FlagDanglingNegation,
}
);
assert_eq!(
parser("i-)").parse_flags().unwrap_err(),
TestError {
span: span(1..2),
kind: ast::ErrorKind::FlagDanglingNegation,
}
);
assert_eq!(
parser("iU-)").parse_flags().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::FlagDanglingNegation,
}
);
}
#[test]
fn parse_flag() {
assert_eq!(parser("i").parse_flag(), Ok(ast::Flag::CaseInsensitive));
assert_eq!(parser("m").parse_flag(), Ok(ast::Flag::MultiLine));
assert_eq!(parser("s").parse_flag(), Ok(ast::Flag::DotMatchesNewLine));
assert_eq!(parser("U").parse_flag(), Ok(ast::Flag::SwapGreed));
assert_eq!(parser("u").parse_flag(), Ok(ast::Flag::Unicode));
assert_eq!(parser("R").parse_flag(), Ok(ast::Flag::CRLF));
assert_eq!(parser("x").parse_flag(), Ok(ast::Flag::IgnoreWhitespace));
assert_eq!(
parser("a").parse_flag().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::FlagUnrecognized,
}
);
assert_eq!(
parser("☃").parse_flag().unwrap_err(),
TestError {
span: span_range("☃", 0..3),
kind: ast::ErrorKind::FlagUnrecognized,
}
);
}
#[test]
fn parse_primitive_non_escape() {
assert_eq!(
parser(r".").parse_primitive(),
Ok(Primitive::Dot(span(0..1)))
);
assert_eq!(
parser(r"^").parse_primitive(),
Ok(Primitive::Assertion(ast::Assertion {
span: span(0..1),
kind: ast::AssertionKind::StartLine,
}))
);
assert_eq!(
parser(r"$").parse_primitive(),
Ok(Primitive::Assertion(ast::Assertion {
span: span(0..1),
kind: ast::AssertionKind::EndLine,
}))
);
assert_eq!(
parser(r"a").parse_primitive(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..1),
kind: ast::LiteralKind::Verbatim,
c: 'a',
}))
);
assert_eq!(
parser(r"|").parse_primitive(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..1),
kind: ast::LiteralKind::Verbatim,
c: '|',
}))
);
assert_eq!(
parser(r"☃").parse_primitive(),
Ok(Primitive::Literal(ast::Literal {
span: span_range("☃", 0..3),
kind: ast::LiteralKind::Verbatim,
c: '☃',
}))
);
}
#[test]
fn parse_escape() {
assert_eq!(
parser(r"\|").parse_primitive(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..2),
kind: ast::LiteralKind::Meta,
c: '|',
}))
);
let specials = &[
(r"\a", '\x07', ast::SpecialLiteralKind::Bell),
(r"\f", '\x0C', ast::SpecialLiteralKind::FormFeed),
(r"\t", '\t', ast::SpecialLiteralKind::Tab),
(r"\n", '\n', ast::SpecialLiteralKind::LineFeed),
(r"\r", '\r', ast::SpecialLiteralKind::CarriageReturn),
(r"\v", '\x0B', ast::SpecialLiteralKind::VerticalTab),
];
for &(pat, c, ref kind) in specials {
assert_eq!(
parser(pat).parse_primitive(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..2),
kind: ast::LiteralKind::Special(kind.clone()),
c,
}))
);
}
assert_eq!(
parser(r"\A").parse_primitive(),
Ok(Primitive::Assertion(ast::Assertion {
span: span(0..2),
kind: ast::AssertionKind::StartText,
}))
);
assert_eq!(
parser(r"\z").parse_primitive(),
Ok(Primitive::Assertion(ast::Assertion {
span: span(0..2),
kind: ast::AssertionKind::EndText,
}))
);
assert_eq!(
parser(r"\b").parse_primitive(),
Ok(Primitive::Assertion(ast::Assertion {
span: span(0..2),
kind: ast::AssertionKind::WordBoundary,
}))
);
assert_eq!(
parser(r"\B").parse_primitive(),
Ok(Primitive::Assertion(ast::Assertion {
span: span(0..2),
kind: ast::AssertionKind::NotWordBoundary,
}))
);
// We also support superfluous escapes in most cases now too.
for c in ['!', '@', '%', '"', '\'', '/', ' '] {
let pat = format!(r"\{}", c);
assert_eq!(
parser(&pat).parse_primitive(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..2),
kind: ast::LiteralKind::Superfluous,
c,
}))
);
}
// Some superfluous escapes, namely [0-9A-Za-z], are still banned. This
// gives flexibility for future evolution.
assert_eq!(
parser(r"\e").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::EscapeUnrecognized,
}
);
assert_eq!(
parser(r"\y").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::EscapeUnrecognized,
}
);
// But also, < and > are banned, so that we may evolve them into
// start/end word boundary assertions. (Not sure if we will...)
assert_eq!(
parser(r"\<").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::EscapeUnrecognized,
}
);
assert_eq!(
parser(r"\>").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::EscapeUnrecognized,
}
);
// An unfinished escape is illegal.
assert_eq!(
parser(r"\").parse_escape().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
}
#[test]
fn parse_unsupported_backreference() {
assert_eq!(
parser(r"\0").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::UnsupportedBackreference,
}
);
assert_eq!(
parser(r"\9").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::UnsupportedBackreference,
}
);
}
#[test]
fn parse_octal() {
for i in 0..511 {
let pat = format!(r"\{:o}", i);
assert_eq!(
parser_octal(&pat).parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..pat.len()),
kind: ast::LiteralKind::Octal,
c: char::from_u32(i).unwrap(),
}))
);
}
assert_eq!(
parser_octal(r"\778").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..3),
kind: ast::LiteralKind::Octal,
c: '?',
}))
);
assert_eq!(
parser_octal(r"\7777").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..4),
kind: ast::LiteralKind::Octal,
c: '\u{01FF}',
}))
);
assert_eq!(
parser_octal(r"\778").parse(),
Ok(Ast::Concat(ast::Concat {
span: span(0..4),
asts: vec![
Ast::Literal(ast::Literal {
span: span(0..3),
kind: ast::LiteralKind::Octal,
c: '?',
}),
Ast::Literal(ast::Literal {
span: span(3..4),
kind: ast::LiteralKind::Verbatim,
c: '8',
}),
],
}))
);
assert_eq!(
parser_octal(r"\7777").parse(),
Ok(Ast::Concat(ast::Concat {
span: span(0..5),
asts: vec![
Ast::Literal(ast::Literal {
span: span(0..4),
kind: ast::LiteralKind::Octal,
c: '\u{01FF}',
}),
Ast::Literal(ast::Literal {
span: span(4..5),
kind: ast::LiteralKind::Verbatim,
c: '7',
}),
],
}))
);
assert_eq!(
parser_octal(r"\8").parse_escape().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::EscapeUnrecognized,
}
);
}
#[test]
fn parse_hex_two() {
for i in 0..256 {
let pat = format!(r"\x{:02x}", i);
assert_eq!(
parser(&pat).parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..pat.len()),
kind: ast::LiteralKind::HexFixed(ast::HexLiteralKind::X),
c: char::from_u32(i).unwrap(),
}))
);
}
assert_eq!(
parser(r"\xF").parse_escape().unwrap_err(),
TestError {
span: span(3..3),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\xG").parse_escape().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\xFG").parse_escape().unwrap_err(),
TestError {
span: span(3..4),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
}
#[test]
fn parse_hex_four() {
for i in 0..65536 {
let c = match char::from_u32(i) {
None => continue,
Some(c) => c,
};
let pat = format!(r"\u{:04x}", i);
assert_eq!(
parser(&pat).parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..pat.len()),
kind: ast::LiteralKind::HexFixed(
ast::HexLiteralKind::UnicodeShort
),
c,
}))
);
}
assert_eq!(
parser(r"\uF").parse_escape().unwrap_err(),
TestError {
span: span(3..3),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\uG").parse_escape().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\uFG").parse_escape().unwrap_err(),
TestError {
span: span(3..4),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\uFFG").parse_escape().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\uFFFG").parse_escape().unwrap_err(),
TestError {
span: span(5..6),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\uD800").parse_escape().unwrap_err(),
TestError {
span: span(2..6),
kind: ast::ErrorKind::EscapeHexInvalid,
}
);
}
#[test]
fn parse_hex_eight() {
for i in 0..65536 {
let c = match char::from_u32(i) {
None => continue,
Some(c) => c,
};
let pat = format!(r"\U{:08x}", i);
assert_eq!(
parser(&pat).parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..pat.len()),
kind: ast::LiteralKind::HexFixed(
ast::HexLiteralKind::UnicodeLong
),
c,
}))
);
}
assert_eq!(
parser(r"\UF").parse_escape().unwrap_err(),
TestError {
span: span(3..3),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\UG").parse_escape().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFG").parse_escape().unwrap_err(),
TestError {
span: span(3..4),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFFG").parse_escape().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFFFG").parse_escape().unwrap_err(),
TestError {
span: span(5..6),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFFFFG").parse_escape().unwrap_err(),
TestError {
span: span(6..7),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFFFFFG").parse_escape().unwrap_err(),
TestError {
span: span(7..8),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFFFFFFG").parse_escape().unwrap_err(),
TestError {
span: span(8..9),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\UFFFFFFFG").parse_escape().unwrap_err(),
TestError {
span: span(9..10),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
}
#[test]
fn parse_hex_brace() {
assert_eq!(
parser(r"\u{26c4}").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..8),
kind: ast::LiteralKind::HexBrace(
ast::HexLiteralKind::UnicodeShort
),
c: '⛄',
}))
);
assert_eq!(
parser(r"\U{26c4}").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..8),
kind: ast::LiteralKind::HexBrace(
ast::HexLiteralKind::UnicodeLong
),
c: '⛄',
}))
);
assert_eq!(
parser(r"\x{26c4}").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..8),
kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X),
c: '⛄',
}))
);
assert_eq!(
parser(r"\x{26C4}").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..8),
kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X),
c: '⛄',
}))
);
assert_eq!(
parser(r"\x{10fFfF}").parse_escape(),
Ok(Primitive::Literal(ast::Literal {
span: span(0..10),
kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X),
c: '\u{10FFFF}',
}))
);
assert_eq!(
parser(r"\x").parse_escape().unwrap_err(),
TestError {
span: span(2..2),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\x{").parse_escape().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\x{FF").parse_escape().unwrap_err(),
TestError {
span: span(2..5),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\x{}").parse_escape().unwrap_err(),
TestError {
span: span(2..4),
kind: ast::ErrorKind::EscapeHexEmpty,
}
);
assert_eq!(
parser(r"\x{FGF}").parse_escape().unwrap_err(),
TestError {
span: span(4..5),
kind: ast::ErrorKind::EscapeHexInvalidDigit,
}
);
assert_eq!(
parser(r"\x{FFFFFF}").parse_escape().unwrap_err(),
TestError {
span: span(3..9),
kind: ast::ErrorKind::EscapeHexInvalid,
}
);
assert_eq!(
parser(r"\x{D800}").parse_escape().unwrap_err(),
TestError {
span: span(3..7),
kind: ast::ErrorKind::EscapeHexInvalid,
}
);
assert_eq!(
parser(r"\x{FFFFFFFFF}").parse_escape().unwrap_err(),
TestError {
span: span(3..12),
kind: ast::ErrorKind::EscapeHexInvalid,
}
);
}
#[test]
fn parse_decimal() {
assert_eq!(parser("123").parse_decimal(), Ok(123));
assert_eq!(parser("0").parse_decimal(), Ok(0));
assert_eq!(parser("01").parse_decimal(), Ok(1));
assert_eq!(
parser("-1").parse_decimal().unwrap_err(),
TestError { span: span(0..0), kind: ast::ErrorKind::DecimalEmpty }
);
assert_eq!(
parser("").parse_decimal().unwrap_err(),
TestError { span: span(0..0), kind: ast::ErrorKind::DecimalEmpty }
);
assert_eq!(
parser("9999999999").parse_decimal().unwrap_err(),
TestError {
span: span(0..10),
kind: ast::ErrorKind::DecimalInvalid,
}
);
}
#[test]
fn parse_set_class() {
fn union(span: Span, items: Vec<ast::ClassSetItem>) -> ast::ClassSet {
ast::ClassSet::union(ast::ClassSetUnion { span, items })
}
fn intersection(
span: Span,
lhs: ast::ClassSet,
rhs: ast::ClassSet,
) -> ast::ClassSet {
ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp {
span,
kind: ast::ClassSetBinaryOpKind::Intersection,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
})
}
fn difference(
span: Span,
lhs: ast::ClassSet,
rhs: ast::ClassSet,
) -> ast::ClassSet {
ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp {
span,
kind: ast::ClassSetBinaryOpKind::Difference,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
})
}
fn symdifference(
span: Span,
lhs: ast::ClassSet,
rhs: ast::ClassSet,
) -> ast::ClassSet {
ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp {
span,
kind: ast::ClassSetBinaryOpKind::SymmetricDifference,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
})
}
fn itemset(item: ast::ClassSetItem) -> ast::ClassSet {
ast::ClassSet::Item(item)
}
fn item_ascii(cls: ast::ClassAscii) -> ast::ClassSetItem {
ast::ClassSetItem::Ascii(cls)
}
fn item_unicode(cls: ast::ClassUnicode) -> ast::ClassSetItem {
ast::ClassSetItem::Unicode(cls)
}
fn item_perl(cls: ast::ClassPerl) -> ast::ClassSetItem {
ast::ClassSetItem::Perl(cls)
}
fn item_bracket(cls: ast::ClassBracketed) -> ast::ClassSetItem {
ast::ClassSetItem::Bracketed(Box::new(cls))
}
fn lit(span: Span, c: char) -> ast::ClassSetItem {
ast::ClassSetItem::Literal(ast::Literal {
span,
kind: ast::LiteralKind::Verbatim,
c,
})
}
fn empty(span: Span) -> ast::ClassSetItem {
ast::ClassSetItem::Empty(span)
}
fn range(span: Span, start: char, end: char) -> ast::ClassSetItem {
let pos1 = Position {
offset: span.start.offset + start.len_utf8(),
column: span.start.column + 1,
..span.start
};
let pos2 = Position {
offset: span.end.offset - end.len_utf8(),
column: span.end.column - 1,
..span.end
};
ast::ClassSetItem::Range(ast::ClassSetRange {
span,
start: ast::Literal {
span: Span { end: pos1, ..span },
kind: ast::LiteralKind::Verbatim,
c: start,
},
end: ast::Literal {
span: Span { start: pos2, ..span },
kind: ast::LiteralKind::Verbatim,
c: end,
},
})
}
fn alnum(span: Span, negated: bool) -> ast::ClassAscii {
ast::ClassAscii { span, kind: ast::ClassAsciiKind::Alnum, negated }
}
fn lower(span: Span, negated: bool) -> ast::ClassAscii {
ast::ClassAscii { span, kind: ast::ClassAsciiKind::Lower, negated }
}
assert_eq!(
parser("[[:alnum:]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..11),
negated: false,
kind: itemset(item_ascii(alnum(span(1..10), false))),
})))
);
assert_eq!(
parser("[[[:alnum:]]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..13),
negated: false,
kind: itemset(item_bracket(ast::ClassBracketed {
span: span(1..12),
negated: false,
kind: itemset(item_ascii(alnum(span(2..11), false))),
})),
})))
);
assert_eq!(
parser("[[:alnum:]&&[:lower:]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..22),
negated: false,
kind: intersection(
span(1..21),
itemset(item_ascii(alnum(span(1..10), false))),
itemset(item_ascii(lower(span(12..21), false))),
),
})))
);
assert_eq!(
parser("[[:alnum:]--[:lower:]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..22),
negated: false,
kind: difference(
span(1..21),
itemset(item_ascii(alnum(span(1..10), false))),
itemset(item_ascii(lower(span(12..21), false))),
),
})))
);
assert_eq!(
parser("[[:alnum:]~~[:lower:]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..22),
negated: false,
kind: symdifference(
span(1..21),
itemset(item_ascii(alnum(span(1..10), false))),
itemset(item_ascii(lower(span(12..21), false))),
),
})))
);
assert_eq!(
parser("[a]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..3),
negated: false,
kind: itemset(lit(span(1..2), 'a')),
})))
);
assert_eq!(
parser(r"[a\]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..5),
negated: false,
kind: union(
span(1..4),
vec![
lit(span(1..2), 'a'),
ast::ClassSetItem::Literal(ast::Literal {
span: span(2..4),
kind: ast::LiteralKind::Meta,
c: ']',
}),
]
),
})))
);
assert_eq!(
parser(r"[a\-z]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..6),
negated: false,
kind: union(
span(1..5),
vec![
lit(span(1..2), 'a'),
ast::ClassSetItem::Literal(ast::Literal {
span: span(2..4),
kind: ast::LiteralKind::Meta,
c: '-',
}),
lit(span(4..5), 'z'),
]
),
})))
);
assert_eq!(
parser("[ab]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: union(
span(1..3),
vec![lit(span(1..2), 'a'), lit(span(2..3), 'b'),]
),
})))
);
assert_eq!(
parser("[a-]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: union(
span(1..3),
vec![lit(span(1..2), 'a'), lit(span(2..3), '-'),]
),
})))
);
assert_eq!(
parser("[-a]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: union(
span(1..3),
vec![lit(span(1..2), '-'), lit(span(2..3), 'a'),]
),
})))
);
assert_eq!(
parser(r"[\pL]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..5),
negated: false,
kind: itemset(item_unicode(ast::ClassUnicode {
span: span(1..4),
negated: false,
kind: ast::ClassUnicodeKind::OneLetter('L'),
})),
})))
);
assert_eq!(
parser(r"[\w]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: itemset(item_perl(ast::ClassPerl {
span: span(1..3),
kind: ast::ClassPerlKind::Word,
negated: false,
})),
})))
);
assert_eq!(
parser(r"[a\wz]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..6),
negated: false,
kind: union(
span(1..5),
vec![
lit(span(1..2), 'a'),
item_perl(ast::ClassPerl {
span: span(2..4),
kind: ast::ClassPerlKind::Word,
negated: false,
}),
lit(span(4..5), 'z'),
]
),
})))
);
assert_eq!(
parser("[a-z]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..5),
negated: false,
kind: itemset(range(span(1..4), 'a', 'z')),
})))
);
assert_eq!(
parser("[a-cx-z]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..8),
negated: false,
kind: union(
span(1..7),
vec![
range(span(1..4), 'a', 'c'),
range(span(4..7), 'x', 'z'),
]
),
})))
);
assert_eq!(
parser(r"[\w&&a-cx-z]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..12),
negated: false,
kind: intersection(
span(1..11),
itemset(item_perl(ast::ClassPerl {
span: span(1..3),
kind: ast::ClassPerlKind::Word,
negated: false,
})),
union(
span(5..11),
vec![
range(span(5..8), 'a', 'c'),
range(span(8..11), 'x', 'z'),
]
),
),
})))
);
assert_eq!(
parser(r"[a-cx-z&&\w]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..12),
negated: false,
kind: intersection(
span(1..11),
union(
span(1..7),
vec![
range(span(1..4), 'a', 'c'),
range(span(4..7), 'x', 'z'),
]
),
itemset(item_perl(ast::ClassPerl {
span: span(9..11),
kind: ast::ClassPerlKind::Word,
negated: false,
})),
),
})))
);
assert_eq!(
parser(r"[a--b--c]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..9),
negated: false,
kind: difference(
span(1..8),
difference(
span(1..5),
itemset(lit(span(1..2), 'a')),
itemset(lit(span(4..5), 'b')),
),
itemset(lit(span(7..8), 'c')),
),
})))
);
assert_eq!(
parser(r"[a~~b~~c]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..9),
negated: false,
kind: symdifference(
span(1..8),
symdifference(
span(1..5),
itemset(lit(span(1..2), 'a')),
itemset(lit(span(4..5), 'b')),
),
itemset(lit(span(7..8), 'c')),
),
})))
);
assert_eq!(
parser(r"[\^&&^]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..7),
negated: false,
kind: intersection(
span(1..6),
itemset(ast::ClassSetItem::Literal(ast::Literal {
span: span(1..3),
kind: ast::LiteralKind::Meta,
c: '^',
})),
itemset(lit(span(5..6), '^')),
),
})))
);
assert_eq!(
parser(r"[\&&&&]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..7),
negated: false,
kind: intersection(
span(1..6),
itemset(ast::ClassSetItem::Literal(ast::Literal {
span: span(1..3),
kind: ast::LiteralKind::Meta,
c: '&',
})),
itemset(lit(span(5..6), '&')),
),
})))
);
assert_eq!(
parser(r"[&&&&]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..6),
negated: false,
kind: intersection(
span(1..5),
intersection(
span(1..3),
itemset(empty(span(1..1))),
itemset(empty(span(3..3))),
),
itemset(empty(span(5..5))),
),
})))
);
let pat = "[☃-⛄]";
assert_eq!(
parser(pat).parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span_range(pat, 0..9),
negated: false,
kind: itemset(ast::ClassSetItem::Range(ast::ClassSetRange {
span: span_range(pat, 1..8),
start: ast::Literal {
span: span_range(pat, 1..4),
kind: ast::LiteralKind::Verbatim,
c: '☃',
},
end: ast::Literal {
span: span_range(pat, 5..8),
kind: ast::LiteralKind::Verbatim,
c: '⛄',
},
})),
})))
);
assert_eq!(
parser(r"[]]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..3),
negated: false,
kind: itemset(lit(span(1..2), ']')),
})))
);
assert_eq!(
parser(r"[]\[]").parse(),
Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..5),
negated: false,
kind: union(
span(1..4),
vec![
lit(span(1..2), ']'),
ast::ClassSetItem::Literal(ast::Literal {
span: span(2..4),
kind: ast::LiteralKind::Meta,
c: '[',
}),
]
),
})))
);
assert_eq!(
parser(r"[\[]]").parse(),
Ok(concat(
0..5,
vec![
Ast::Class(ast::Class::Bracketed(ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: itemset(ast::ClassSetItem::Literal(
ast::Literal {
span: span(1..3),
kind: ast::LiteralKind::Meta,
c: '[',
}
)),
})),
Ast::Literal(ast::Literal {
span: span(4..5),
kind: ast::LiteralKind::Verbatim,
c: ']',
}),
]
))
);
assert_eq!(
parser("[").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[[").parse().unwrap_err(),
TestError {
span: span(1..2),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[[-]").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[[[:alnum:]").parse().unwrap_err(),
TestError {
span: span(1..2),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser(r"[\b]").parse().unwrap_err(),
TestError {
span: span(1..3),
kind: ast::ErrorKind::ClassEscapeInvalid,
}
);
assert_eq!(
parser(r"[\w-a]").parse().unwrap_err(),
TestError {
span: span(1..3),
kind: ast::ErrorKind::ClassRangeLiteral,
}
);
assert_eq!(
parser(r"[a-\w]").parse().unwrap_err(),
TestError {
span: span(3..5),
kind: ast::ErrorKind::ClassRangeLiteral,
}
);
assert_eq!(
parser(r"[z-a]").parse().unwrap_err(),
TestError {
span: span(1..4),
kind: ast::ErrorKind::ClassRangeInvalid,
}
);
assert_eq!(
parser_ignore_whitespace("[a ").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser_ignore_whitespace("[a- ").parse().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::ClassUnclosed,
}
);
}
#[test]
fn parse_set_class_open() {
assert_eq!(parser("[a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..1),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(1..1),
items: vec![],
}),
};
let union = ast::ClassSetUnion { span: span(1..1), items: vec![] };
Ok((set, union))
});
assert_eq!(
parser_ignore_whitespace("[ a]").parse_set_class_open(),
{
let set = ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(4..4),
items: vec![],
}),
};
let union =
ast::ClassSetUnion { span: span(4..4), items: vec![] };
Ok((set, union))
}
);
assert_eq!(parser("[^a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..2),
negated: true,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(2..2),
items: vec![],
}),
};
let union = ast::ClassSetUnion { span: span(2..2), items: vec![] };
Ok((set, union))
});
assert_eq!(
parser_ignore_whitespace("[ ^ a]").parse_set_class_open(),
{
let set = ast::ClassBracketed {
span: span(0..4),
negated: true,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(4..4),
items: vec![],
}),
};
let union =
ast::ClassSetUnion { span: span(4..4), items: vec![] };
Ok((set, union))
}
);
assert_eq!(parser("[-a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..2),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(1..1),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(1..2),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(1..2),
kind: ast::LiteralKind::Verbatim,
c: '-',
})],
};
Ok((set, union))
});
assert_eq!(
parser_ignore_whitespace("[ - a]").parse_set_class_open(),
{
let set = ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(2..2),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(2..3),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(2..3),
kind: ast::LiteralKind::Verbatim,
c: '-',
})],
};
Ok((set, union))
}
);
assert_eq!(parser("[^-a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..3),
negated: true,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(2..2),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(2..3),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(2..3),
kind: ast::LiteralKind::Verbatim,
c: '-',
})],
};
Ok((set, union))
});
assert_eq!(parser("[--a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..3),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(1..1),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(1..3),
items: vec![
ast::ClassSetItem::Literal(ast::Literal {
span: span(1..2),
kind: ast::LiteralKind::Verbatim,
c: '-',
}),
ast::ClassSetItem::Literal(ast::Literal {
span: span(2..3),
kind: ast::LiteralKind::Verbatim,
c: '-',
}),
],
};
Ok((set, union))
});
assert_eq!(parser("[]a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..2),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(1..1),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(1..2),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(1..2),
kind: ast::LiteralKind::Verbatim,
c: ']',
})],
};
Ok((set, union))
});
assert_eq!(
parser_ignore_whitespace("[ ] a]").parse_set_class_open(),
{
let set = ast::ClassBracketed {
span: span(0..4),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(2..2),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(2..3),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(2..3),
kind: ast::LiteralKind::Verbatim,
c: ']',
})],
};
Ok((set, union))
}
);
assert_eq!(parser("[^]a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..3),
negated: true,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(2..2),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(2..3),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(2..3),
kind: ast::LiteralKind::Verbatim,
c: ']',
})],
};
Ok((set, union))
});
assert_eq!(parser("[-]a]").parse_set_class_open(), {
let set = ast::ClassBracketed {
span: span(0..2),
negated: false,
kind: ast::ClassSet::union(ast::ClassSetUnion {
span: span(1..1),
items: vec![],
}),
};
let union = ast::ClassSetUnion {
span: span(1..2),
items: vec![ast::ClassSetItem::Literal(ast::Literal {
span: span(1..2),
kind: ast::LiteralKind::Verbatim,
c: '-',
})],
};
Ok((set, union))
});
assert_eq!(
parser("[").parse_set_class_open().unwrap_err(),
TestError {
span: span(0..1),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser_ignore_whitespace("[ ")
.parse_set_class_open()
.unwrap_err(),
TestError {
span: span(0..5),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[^").parse_set_class_open().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[]").parse_set_class_open().unwrap_err(),
TestError {
span: span(0..2),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[-").parse_set_class_open().unwrap_err(),
TestError {
span: span(0..0),
kind: ast::ErrorKind::ClassUnclosed,
}
);
assert_eq!(
parser("[--").parse_set_class_open().unwrap_err(),
TestError {
span: span(0..0),
kind: ast::ErrorKind::ClassUnclosed,
}
);
// See: https://github.com/rust-lang/regex/issues/792
assert_eq!(
parser("(?x)[-#]").parse_with_comments().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::ClassUnclosed,
}
);
}
#[test]
fn maybe_parse_ascii_class() {
assert_eq!(
parser(r"[:alnum:]").maybe_parse_ascii_class(),
Some(ast::ClassAscii {
span: span(0..9),
kind: ast::ClassAsciiKind::Alnum,
negated: false,
})
);
assert_eq!(
parser(r"[:alnum:]A").maybe_parse_ascii_class(),
Some(ast::ClassAscii {
span: span(0..9),
kind: ast::ClassAsciiKind::Alnum,
negated: false,
})
);
assert_eq!(
parser(r"[:^alnum:]").maybe_parse_ascii_class(),
Some(ast::ClassAscii {
span: span(0..10),
kind: ast::ClassAsciiKind::Alnum,
negated: true,
})
);
let p = parser(r"[:");
assert_eq!(p.maybe_parse_ascii_class(), None);
assert_eq!(p.offset(), 0);
let p = parser(r"[:^");
assert_eq!(p.maybe_parse_ascii_class(), None);
assert_eq!(p.offset(), 0);
let p = parser(r"[^:alnum:]");
assert_eq!(p.maybe_parse_ascii_class(), None);
assert_eq!(p.offset(), 0);
let p = parser(r"[:alnnum:]");
assert_eq!(p.maybe_parse_ascii_class(), None);
assert_eq!(p.offset(), 0);
let p = parser(r"[:alnum]");
assert_eq!(p.maybe_parse_ascii_class(), None);
assert_eq!(p.offset(), 0);
let p = parser(r"[:alnum:");
assert_eq!(p.maybe_parse_ascii_class(), None);
assert_eq!(p.offset(), 0);
}
#[test]
fn parse_unicode_class() {
assert_eq!(
parser(r"\pN").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..3),
negated: false,
kind: ast::ClassUnicodeKind::OneLetter('N'),
}))
);
assert_eq!(
parser(r"\PN").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..3),
negated: true,
kind: ast::ClassUnicodeKind::OneLetter('N'),
}))
);
assert_eq!(
parser(r"\p{N}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..5),
negated: false,
kind: ast::ClassUnicodeKind::Named(s("N")),
}))
);
assert_eq!(
parser(r"\P{N}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..5),
negated: true,
kind: ast::ClassUnicodeKind::Named(s("N")),
}))
);
assert_eq!(
parser(r"\p{Greek}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..9),
negated: false,
kind: ast::ClassUnicodeKind::Named(s("Greek")),
}))
);
assert_eq!(
parser(r"\p{scx:Katakana}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..16),
negated: false,
kind: ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::Colon,
name: s("scx"),
value: s("Katakana"),
},
}))
);
assert_eq!(
parser(r"\p{scx=Katakana}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..16),
negated: false,
kind: ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::Equal,
name: s("scx"),
value: s("Katakana"),
},
}))
);
assert_eq!(
parser(r"\p{scx!=Katakana}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..17),
negated: false,
kind: ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::NotEqual,
name: s("scx"),
value: s("Katakana"),
},
}))
);
assert_eq!(
parser(r"\p{:}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..5),
negated: false,
kind: ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::Colon,
name: s(""),
value: s(""),
},
}))
);
assert_eq!(
parser(r"\p{=}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..5),
negated: false,
kind: ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::Equal,
name: s(""),
value: s(""),
},
}))
);
assert_eq!(
parser(r"\p{!=}").parse_escape(),
Ok(Primitive::Unicode(ast::ClassUnicode {
span: span(0..6),
negated: false,
kind: ast::ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::NotEqual,
name: s(""),
value: s(""),
},
}))
);
assert_eq!(
parser(r"\p").parse_escape().unwrap_err(),
TestError {
span: span(2..2),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\p{").parse_escape().unwrap_err(),
TestError {
span: span(3..3),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\p{N").parse_escape().unwrap_err(),
TestError {
span: span(4..4),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\p{Greek").parse_escape().unwrap_err(),
TestError {
span: span(8..8),
kind: ast::ErrorKind::EscapeUnexpectedEof,
}
);
assert_eq!(
parser(r"\pNz").parse(),
Ok(Ast::Concat(ast::Concat {
span: span(0..4),
asts: vec![
Ast::Class(ast::Class::Unicode(ast::ClassUnicode {
span: span(0..3),
negated: false,
kind: ast::ClassUnicodeKind::OneLetter('N'),
})),
Ast::Literal(ast::Literal {
span: span(3..4),
kind: ast::LiteralKind::Verbatim,
c: 'z',
}),
],
}))
);
assert_eq!(
parser(r"\p{Greek}z").parse(),
Ok(Ast::Concat(ast::Concat {
span: span(0..10),
asts: vec![
Ast::Class(ast::Class::Unicode(ast::ClassUnicode {
span: span(0..9),
negated: false,
kind: ast::ClassUnicodeKind::Named(s("Greek")),
})),
Ast::Literal(ast::Literal {
span: span(9..10),
kind: ast::LiteralKind::Verbatim,
c: 'z',
}),
],
}))
);
assert_eq!(
parser(r"\p\{").parse().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::UnicodeClassInvalid,
}
);
assert_eq!(
parser(r"\P\{").parse().unwrap_err(),
TestError {
span: span(2..3),
kind: ast::ErrorKind::UnicodeClassInvalid,
}
);
}
#[test]
fn parse_perl_class() {
assert_eq!(
parser(r"\d").parse_escape(),
Ok(Primitive::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Digit,
negated: false,
}))
);
assert_eq!(
parser(r"\D").parse_escape(),
Ok(Primitive::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Digit,
negated: true,
}))
);
assert_eq!(
parser(r"\s").parse_escape(),
Ok(Primitive::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Space,
negated: false,
}))
);
assert_eq!(
parser(r"\S").parse_escape(),
Ok(Primitive::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Space,
negated: true,
}))
);
assert_eq!(
parser(r"\w").parse_escape(),
Ok(Primitive::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Word,
negated: false,
}))
);
assert_eq!(
parser(r"\W").parse_escape(),
Ok(Primitive::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Word,
negated: true,
}))
);
assert_eq!(
parser(r"\d").parse(),
Ok(Ast::Class(ast::Class::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Digit,
negated: false,
})))
);
assert_eq!(
parser(r"\dz").parse(),
Ok(Ast::Concat(ast::Concat {
span: span(0..3),
asts: vec![
Ast::Class(ast::Class::Perl(ast::ClassPerl {
span: span(0..2),
kind: ast::ClassPerlKind::Digit,
negated: false,
})),
Ast::Literal(ast::Literal {
span: span(2..3),
kind: ast::LiteralKind::Verbatim,
c: 'z',
}),
],
}))
);
}
// This tests a bug fix where the nest limit checker wasn't decrementing
// its depth during post-traversal, which causes long regexes to trip
// the default limit too aggressively.
#[test]
fn regression_454_nest_too_big() {
let pattern = r#"
2(?:
[45]\d{3}|
7(?:
1[0-267]|
2[0-289]|
3[0-29]|
4[01]|
5[1-3]|
6[013]|
7[0178]|
91
)|
8(?:
0[125]|
[139][1-6]|
2[0157-9]|
41|
6[1-35]|
7[1-5]|
8[1-8]|
90
)|
9(?:
0[0-2]|
1[0-4]|
2[568]|
3[3-6]|
5[5-7]|
6[0167]|
7[15]|
8[0146-9]
)
)\d{4}
"#;
assert!(parser_nest_limit(pattern, 50).parse().is_ok());
}
// This tests that we treat a trailing `-` in a character class as a
// literal `-` even when whitespace mode is enabled and there is whitespace
// after the trailing `-`.
#[test]
fn regression_455_trailing_dash_ignore_whitespace() {
assert!(parser("(?x)[ / - ]").parse().is_ok());
assert!(parser("(?x)[ a - ]").parse().is_ok());
assert!(parser(
"(?x)[
a
- ]
"
)
.parse()
.is_ok());
assert!(parser(
"(?x)[
a # wat
- ]
"
)
.parse()
.is_ok());
assert!(parser("(?x)[ / -").parse().is_err());
assert!(parser("(?x)[ / - ").parse().is_err());
assert!(parser(
"(?x)[
/ -
"
)
.parse()
.is_err());
assert!(parser(
"(?x)[
/ - # wat
"
)
.parse()
.is_err());
}
}