File size: 187,881 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.PowerShell.Commands;
using System.Management.Automation.Subsystem;
using System.Management.Automation.Subsystem.DSC;
using Microsoft.PowerShell.DesiredStateConfiguration.Internal;
namespace System.Management.Automation.Language
{
/// <summary>
/// Defines the name modes for a dynamic keyword. A name expression may be required, optional or not permitted.
/// </summary>
public enum DynamicKeywordNameMode
{
/// <summary>
/// This keyword does not take a name value.
/// </summary>
NoName = 0,
/// <summary>
/// Name must be present and simple non-empty bare word.
/// </summary>
SimpleNameRequired = 1,
/// <summary>
/// Name must be present but can also be an expression.
/// </summary>
NameRequired = 2,
/// <summary>
/// Name may be optionally present, but if it is present, it must be a non-empty bare word.
/// </summary>
SimpleOptionalName = 3,
/// <summary>
/// Name may be optionally present, expression or bare word.
/// </summary>
OptionalName = 4,
}
/// <summary>
/// Defines the body mode for a dynamic keyword. It can be a scriptblock, hashtable or command which means no body.
/// </summary>
public enum DynamicKeywordBodyMode
{
/// <summary>
/// The keyword act like a command.
/// </summary>
Command = 0,
/// <summary>
/// The keyword has a scriptblock body.
/// </summary>
ScriptBlock = 1,
/// <summary>
/// The keyword has hashtable body.
/// </summary>
Hashtable = 2,
}
/// <summary>
/// Defines the schema/behaviour for a dynamic keyword.
/// a constrained.
/// </summary>
public class DynamicKeyword
{
#region static properties/functions
/// <summary>
/// Defines a dictionary of dynamic keywords, stored in thread-local storage.
/// </summary>
private static Dictionary<string, DynamicKeyword> DynamicKeywords
{
get
{
return t_dynamicKeywords ??= new Dictionary<string, DynamicKeyword>(StringComparer.OrdinalIgnoreCase);
}
}
[ThreadStatic]
private static Dictionary<string, DynamicKeyword> t_dynamicKeywords;
/// <summary>
/// Stack of DynamicKeywords Cache.
/// </summary>
private static Stack<Dictionary<string, DynamicKeyword>> DynamicKeywordsStack
{
get
{
return t_dynamicKeywordsStack ??= new Stack<Dictionary<string, DynamicKeyword>>();
}
}
[ThreadStatic]
private static Stack<Dictionary<string, DynamicKeyword>> t_dynamicKeywordsStack;
/// <summary>
/// Reset the keyword table to a new empty collection.
/// </summary>
public static void Reset()
{
t_dynamicKeywords = new Dictionary<string, DynamicKeyword>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Push current dynamicKeywords cache into stack.
/// </summary>
public static void Push()
{
DynamicKeywordsStack.Push(t_dynamicKeywords);
Reset();
}
/// <summary>
/// Pop up previous dynamicKeywords cache.
/// </summary>
public static void Pop()
{
t_dynamicKeywords = DynamicKeywordsStack.Pop();
}
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static DynamicKeyword GetKeyword(string name)
{
DynamicKeyword keywordToReturn;
DynamicKeyword.DynamicKeywords.TryGetValue(name, out keywordToReturn);
return keywordToReturn;
}
/// <summary>
/// Returns a copied list of all of the existing dynamic keyword definitions.
/// </summary>
/// <returns></returns>
public static List<DynamicKeyword> GetKeyword()
{
return new List<DynamicKeyword>(DynamicKeyword.DynamicKeywords.Values);
}
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool ContainsKeyword(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name));
throw e;
}
return DynamicKeyword.DynamicKeywords.ContainsKey(name);
}
/// <summary>
/// </summary>
/// <param name="keywordToAdd"></param>
public static void AddKeyword(DynamicKeyword keywordToAdd)
{
if (keywordToAdd == null)
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(keywordToAdd));
throw e;
}
// Allow overwriting of the existing entries
string name = keywordToAdd.Keyword;
if (string.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentNullException("keywordToAdd.Keyword");
}
DynamicKeyword.DynamicKeywords.Remove(name);
DynamicKeyword.DynamicKeywords.Add(name, keywordToAdd);
}
/// <summary>
/// Remove a single entry from the dynamic keyword collection
/// and clean up any associated data.
/// </summary>
/// <param name="name"></param>
public static void RemoveKeyword(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name));
throw e;
}
DynamicKeyword.DynamicKeywords.Remove(name);
}
/// <summary>
/// Check if it is a hidden keyword.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
internal static bool IsHiddenKeyword(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name));
throw e;
}
return s_hiddenDynamicKeywords.Contains(name);
}
/// <summary>
/// A set of dynamic keywords that are not supposed to be used in script directly.
/// They are for internal use only.
/// </summary>
private static readonly HashSet<string> s_hiddenDynamicKeywords =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "MSFT_Credential" };
#endregion
/// <summary>
/// Duplicates the DynamicKeyword.
/// </summary>
/// <returns>A copy of the DynamicKeyword.</returns>
public DynamicKeyword Copy()
{
DynamicKeyword keyword = new DynamicKeyword()
{
ImplementingModule = this.ImplementingModule,
ImplementingModuleVersion = this.ImplementingModuleVersion,
Keyword = this.Keyword,
ResourceName = this.ResourceName,
BodyMode = this.BodyMode,
DirectCall = this.DirectCall,
NameMode = this.NameMode,
MetaStatement = this.MetaStatement,
IsReservedKeyword = this.IsReservedKeyword,
HasReservedProperties = this.HasReservedProperties,
PreParse = this.PreParse,
PostParse = this.PostParse,
SemanticCheck = this.SemanticCheck
};
foreach (KeyValuePair<string, DynamicKeywordProperty> entry in this.Properties)
{
keyword.Properties.Add(entry.Key, entry.Value);
}
foreach (KeyValuePair<string, DynamicKeywordParameter> entry in this.Parameters)
{
keyword.Parameters.Add(entry.Key, entry.Value);
}
return keyword;
}
/// <summary>
/// The name of the module that implements the function corresponding to this keyword.
/// </summary>
public string ImplementingModule { get; set; }
/// <summary>
/// The version of the module that implements the function corresponding to this keyword.
/// </summary>
public Version ImplementingModuleVersion { get; set; }
/// <summary>
/// The keyword string
/// If an alias qualifier exist, use alias.
/// </summary>
public string Keyword { get; set; }
/// <summary>
/// The keyword resource name string.
/// </summary>
public string ResourceName { get; set; }
/// <summary>
/// Set to true if we should be looking for a scriptblock instead of a hashtable.
/// </summary>
public DynamicKeywordBodyMode BodyMode { get; set; }
/// <summary>
/// If true, then don't use the marshalled call. Just
/// rewrite the node as a simple direct function call.
/// If NameMode is other than NoName, then the name of the instance
/// will be passed as the parameter -InstanceName.
/// </summary>
public bool DirectCall { get; set; }
/// <summary>
/// This allows you to specify if the keyword takes a name argument and if so, what form that takes.
/// </summary>
public DynamicKeywordNameMode NameMode { get; set; }
/// <summary>
/// Indicate that the nothing should be added to the AST for this
/// dynamic keyword.
/// </summary>
public bool MetaStatement { get; set; }
/// <summary>
/// Indicate that the keyword is reserved for future use by powershell.
/// </summary>
public bool IsReservedKeyword { get; set; }
/// <summary>
/// Contains the list of properties that are reserved for future use.
/// </summary>
public bool HasReservedProperties { get; set; }
/// <summary>
/// A list of the properties allowed for this constructor.
/// </summary>
public Dictionary<string, DynamicKeywordProperty> Properties
{
get
{
return _properties ??= new Dictionary<string, DynamicKeywordProperty>(StringComparer.OrdinalIgnoreCase);
}
}
private Dictionary<string, DynamicKeywordProperty> _properties;
/// <summary>
/// A list of the parameters allowed for this constructor.
/// </summary>
public Dictionary<string, DynamicKeywordParameter> Parameters
{
get
{
return _parameters ??= new Dictionary<string, DynamicKeywordParameter>(StringComparer.OrdinalIgnoreCase);
}
}
private Dictionary<string, DynamicKeywordParameter> _parameters;
/// <summary>
/// A custom function that gets executed at parsing time before parsing dynamickeyword block
/// The delegate has one parameter: DynamicKeyword.
/// </summary>
public Func<DynamicKeyword, ParseError[]> PreParse { get; set; }
/// <summary>
/// A custom function that gets executed at parsing time after parsing dynamickeyword block.
/// </summary>
public Func<DynamicKeywordStatementAst, ParseError[]> PostParse { get; set; }
/// <summary>
/// A custom function that checks semantic for the given <see cref="DynamicKeywordStatementAst"/>
/// </summary>
public Func<DynamicKeywordStatementAst, ParseError[]> SemanticCheck { get; set; }
}
internal static class DynamicKeywordExtension
{
internal static bool IsMetaDSCResource(this DynamicKeyword keyword)
{
string implementingModule = keyword.ImplementingModule;
if (implementingModule != null)
{
ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem<ICrossPlatformDsc>();
if (dscSubsystem != null)
{
dscSubsystem.IsDefaultModuleNameForMetaConfigResource(implementingModule);
}
else
{
return implementingModule.Equals(DscClassCache.DefaultModuleInfoForMetaConfigResource.Item1, StringComparison.OrdinalIgnoreCase);
}
}
return false;
}
internal static bool IsCompatibleWithConfigurationType(this DynamicKeyword keyword, ConfigurationType ConfigurationType)
{
return ((ConfigurationType == ConfigurationType.Meta && keyword.IsMetaDSCResource()) ||
(ConfigurationType != ConfigurationType.Meta && !keyword.IsMetaDSCResource()));
}
private static readonly Dictionary<string, List<string>> s_excludeKeywords = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase)
{
{@"Node", new List<string> {@"Node"}},
};
/// <summary>
/// Get allowed keyword list for a given keyword.
/// </summary>
/// <param name="keyword"></param>
/// <param name="allowedKeywords"></param>
/// <returns>NULL if no keyword allowed for a given <see cref="DynamicKeyword"/></returns>
internal static IEnumerable<DynamicKeyword> GetAllowedKeywords(this DynamicKeyword keyword, IEnumerable<DynamicKeyword> allowedKeywords)
{
string keywordName = keyword.Keyword;
if (string.Equals(keywordName, @"Node", StringComparison.OrdinalIgnoreCase))
{
List<string> excludeKeywords;
if (s_excludeKeywords.TryGetValue(keywordName, out excludeKeywords))
{
return allowedKeywords.Where(k => !excludeKeywords.Contains(k.Keyword));
}
else
return allowedKeywords;
}
return null;
}
}
/// <summary>
/// Metadata about a member property for a dynamic keyword.
/// </summary>
public class DynamicKeywordProperty
{
/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The required type of the property.
/// </summary>
public string TypeConstraint { get; set; }
/// <summary>
/// Any attributes that the property has.
/// </summary>
public List<string> Attributes
{
get { return _attributes ??= new List<string>(); }
}
private List<string> _attributes;
/// <summary>
/// List of strings that may be used as values for this property.
/// </summary>
public List<string> Values
{
get { return _values ??= new List<string>(); }
}
private List<string> _values;
/// <summary>
/// Mapping the descriptive values to the actual values.
/// </summary>
public Dictionary<string, string> ValueMap
{
get { return _valueMap ??= new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); }
}
private Dictionary<string, string> _valueMap;
/// <summary>
/// Indicates that this property is mandatory and must be present.
/// </summary>
public bool Mandatory { get; set; }
/// <summary>
/// Indicates that this property is a key.
/// </summary>
public bool IsKey { get; set; }
/// <summary>
/// Indicates a range constraint on the property value.
/// </summary>
public Tuple<int, int> Range { get; set; }
}
/// <summary>
/// Metadata about a parameter for a dynamic keyword. Adds one
/// new property to the base classL Switch for switch parameters
/// (THere is no such thing as a switch property...)
/// </summary>
public class DynamicKeywordParameter : DynamicKeywordProperty
{
/// <summary>
/// Type if this is a switch parameter and takes no argument.
/// </summary>
public bool Switch { get; set; }
}
internal enum TokenizerMode
{
Command,
Expression,
TypeName,
Signature, // i.e. class or method declaration
}
/// <summary>
/// Indicates which suffix character(s) are present in the numeric literal being parsed by TryGetNumberValue.
/// </summary>
[Flags]
internal enum NumberSuffixFlags
{
/// <summary>
/// Indicates no suffix, a raw numeric literal. May be parsed as Int32, Int64, or Double.
/// </summary>
None = 0x0,
/// <summary>
/// Indicates 'u' suffix for unsigned integers. May be parsed as UInt32 or UInt64, depending on the value.
/// </summary>
Unsigned = 0x1,
/// <summary>
/// Indicates 'y' suffix for signed byte (sbyte) values.
/// </summary>
SignedByte = 0x2,
/// <summary>
/// Indicates 'uy' suffix for unsigned byte values.
/// This is a compound value, representing both SignedByte and Unsigned flags being set.
/// </summary>
UnsignedByte = 0x3,
/// <summary>
/// Indicates 's' suffix for short (Int16) integers.
/// </summary>
Short = 0x4,
/// <summary>
/// Indicates 'us' suffix for ushort (UInt16) integers.
/// This is a compound flag value, representing both Unsigned and Short flags being set.
/// </summary>
UnsignedShort = 0x5,
/// <summary>
/// Indicates 'l' suffix for long (Int64) integers.
/// </summary>
Long = 0x8,
/// <summary>
/// Indicates 'ul' suffix for ulong (UInt64) integers.
/// This is a compound flag value, representing both Unsigned and Long flags being set.
/// </summary>
UnsignedLong = 0x9,
/// <summary>
/// Indicates 'd' suffix for decimal (128-bit) real numbers.
/// </summary>
Decimal = 0x10,
/// <summary>
/// Indicates 'N' suffix for BigInteger (arbitrarily large integer) numerals.
/// </summary>
BigInteger = 0x20
}
/// <summary>
/// Indicates the format of a numeric literal.
/// </summary>
internal enum NumberFormat
{
/// <summary>
/// Indicates standard decimal literal, no necessary prefix.
/// </summary>
Decimal = 0x0,
/// <summary>
/// Indicates hexadecimal literal, with '0x' prefix.
/// </summary>
Hex = 0x1,
/// <summary>
/// Indicates binary literal, with '0b' prefix.
/// </summary>
Binary = 0x2
}
//
// Class used to do a partial snapshot of the state of the tokenizer.
// This is used for nested scans on the same string.
//
internal class TokenizerState
{
internal int NestedTokensAdjustment;
internal string Script;
internal int TokenStart;
internal int CurrentIndex;
internal Token FirstToken;
internal Token LastToken;
internal BitArray SkippedCharOffsets;
internal List<Token> TokenList;
}
[DebuggerDisplay("Mode = {Mode}; Script = {_script}")]
internal class Tokenizer
{
private static readonly Dictionary<string, TokenKind> s_keywordTable
= new Dictionary<string, TokenKind>(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, TokenKind> s_operatorTable
= new Dictionary<string, TokenKind>(StringComparer.OrdinalIgnoreCase);
private static readonly char s_invalidChar = char.MaxValue;
private static readonly int s_maxNumberOfUnicodeHexDigits = 6;
private readonly Parser _parser;
private PositionHelper _positionHelper;
private int _nestedTokensAdjustment;
// This BitArray is used to help ensure we get the correct extent in a corner case that looks something like:
// $(""abc"")
// In the above, we scan the characters between the parens once and create a token that is scanned later. This
// first pass scan replaces doubled quotes with single quotes so that a subsequent scan will see: "abc" instead
// of: ""abc"". (This isn't really necessary, but is done for backwards compatibility.) If we didn't track
// the skipped quotes, we'd generate incorrect extent of the string token on subsequent rescans.
private BitArray _skippedCharOffsets;
private string _script;
private int _tokenStart;
private int _currentIndex;
private InternalScriptExtent _beginSignatureExtent;
#region Tables for initialization
private static readonly string[] s_keywordText = new string[] {
/*1*/ "elseif", "if", "else", "switch", /*1*/
/*2*/ "foreach", "from", "in", "for", /*2*/
/*3*/ "while", "until", "do", "try", /*3*/
/*4*/ "catch", "finally", "trap", "data", /*4*/
/*5*/ "return", "continue", "break", "exit", /*5*/
/*6*/ "throw", "begin", "process", "end", /*6*/
/*7*/ "dynamicparam", "function", "filter", "param", /*7*/
/*8*/ "class", "define", "var", "using", /*8*/
/*9*/ "workflow", "parallel", "sequence", "inlinescript", /*9*/
/*A*/ "configuration", "public", "private", "static", /*A*/
/*B*/ "interface", "enum", "namespace", "module", /*B*/
/*C*/ "type", "assembly", "command", "hidden", /*C*/
/*D*/ "base", "default", "clean", /*D*/
};
private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] {
/*1*/ TokenKind.ElseIf, TokenKind.If, TokenKind.Else, TokenKind.Switch, /*1*/
/*2*/ TokenKind.Foreach, TokenKind.From, TokenKind.In, TokenKind.For, /*2*/
/*3*/ TokenKind.While, TokenKind.Until, TokenKind.Do, TokenKind.Try, /*3*/
/*4*/ TokenKind.Catch, TokenKind.Finally, TokenKind.Trap, TokenKind.Data, /*4*/
/*5*/ TokenKind.Return, TokenKind.Continue, TokenKind.Break, TokenKind.Exit, /*5*/
/*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/
/*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/
/*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/
/*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/
/*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/
/*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace, TokenKind.Module, /*B*/
/*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/
/*D*/ TokenKind.Base, TokenKind.Default, TokenKind.Clean, /*D*/
};
internal static readonly string[] _operatorText = new string[] {
/*1*/ "bnot", "not", "eq", "ieq", /*1*/
/*2*/ "ceq", "ne", "ine", "cne", /*2*/
/*3*/ "ge", "ige", "cge", "gt", /*3*/
/*4*/ "igt", "cgt", "lt", "ilt", /*4*/
/*5*/ "clt", "le", "ile", "cle", /*5*/
/*6*/ "like", "ilike", "clike", "notlike", /*6*/
/*7*/ "inotlike", "cnotlike", "match", "imatch", /*7*/
/*8*/ "cmatch", "notmatch", "inotmatch", "cnotmatch", /*8*/
/*9*/ "replace", "ireplace", "creplace", "contains", /*9*/
/*10*/ "icontains", "ccontains", "notcontains", "inotcontains", /*10*/
/*11*/ "cnotcontains", "in", "iin", "cin", /*11*/
/*12*/ "notin", "inotin", "cnotin", "split", /*12*/
/*13*/ "isplit", "csplit", "isnot", "is", /*13*/
/*14*/ "as", "f", "and", "band", /*14*/
/*15*/ "or", "bor", "xor", "bxor", /*15*/
/*16*/ "join", "shl", "shr", /*16*/
};
private static readonly TokenKind[] s_operatorTokenKind = new TokenKind[] {
/*1*/ TokenKind.Bnot, TokenKind.Not, TokenKind.Ieq, TokenKind.Ieq, /*1*/
/*2*/ TokenKind.Ceq, TokenKind.Ine, TokenKind.Ine, TokenKind.Cne, /*2*/
/*3*/ TokenKind.Ige, TokenKind.Ige, TokenKind.Cge, TokenKind.Igt, /*3*/
/*4*/ TokenKind.Igt, TokenKind.Cgt, TokenKind.Ilt, TokenKind.Ilt, /*4*/
/*5*/ TokenKind.Clt, TokenKind.Ile, TokenKind.Ile, TokenKind.Cle, /*5*/
/*6*/ TokenKind.Ilike, TokenKind.Ilike, TokenKind.Clike, TokenKind.Inotlike, /*6*/
/*7*/ TokenKind.Inotlike, TokenKind.Cnotlike, TokenKind.Imatch, TokenKind.Imatch, /*7*/
/*8*/ TokenKind.Cmatch, TokenKind.Inotmatch, TokenKind.Inotmatch, TokenKind.Cnotmatch, /*8*/
/*9*/ TokenKind.Ireplace, TokenKind.Ireplace, TokenKind.Creplace, TokenKind.Icontains, /*9*/
/*10*/ TokenKind.Icontains, TokenKind.Ccontains, TokenKind.Inotcontains, TokenKind.Inotcontains, /*10*/
/*11*/ TokenKind.Cnotcontains, TokenKind.Iin, TokenKind.Iin, TokenKind.Cin, /*11*/
/*12*/ TokenKind.Inotin, TokenKind.Inotin, TokenKind.Cnotin, TokenKind.Isplit, /*12*/
/*13*/ TokenKind.Isplit, TokenKind.Csplit, TokenKind.IsNot, TokenKind.Is, /*13*/
/*14*/ TokenKind.As, TokenKind.Format, TokenKind.And, TokenKind.Band, /*14*/
/*15*/ TokenKind.Or, TokenKind.Bor, TokenKind.Xor, TokenKind.Bxor, /*15*/
/*16*/ TokenKind.Join, TokenKind.Shl, TokenKind.Shr, /*16*/
};
#endregion Tables for initialization
static Tokenizer()
{
Diagnostics.Assert(s_keywordText.Length == s_keywordTokenKind.Length, "Keyword table sizes must match");
Diagnostics.Assert(_operatorText.Length == s_operatorTokenKind.Length, "Operator table sizes must match");
for (int i = 0; i < s_keywordText.Length; ++i)
{
s_keywordTable.Add(s_keywordText[i], s_keywordTokenKind[i]);
}
for (int i = 0; i < _operatorText.Length; ++i)
{
s_operatorTable.Add(_operatorText[i], s_operatorTokenKind[i]);
}
// The real signature (in mshsip.cpp) has spaces, but we ignore whitespace when looking
// for signatures because we only care about things that look like a signature.
// The hash we compute is intentionally dumb, we want collisions to catch similar strings,
// so we just sum up the characters.
const string beginSig = "sig#beginsignatureblock";
beginSig.Aggregate(0, static (current, t) => current + t);
// Spot check to help make sure the arrays are in sync
Diagnostics.Assert(s_keywordTable["using"] == TokenKind.Using, "Keyword table out of sync w/ enum");
Diagnostics.Assert(s_operatorTable["join"] == TokenKind.Join, "Operator table out of sync w/ enum");
}
internal Tokenizer(Parser parser)
{
_parser = parser;
}
internal TokenizerMode Mode { get; set; }
internal bool AllowSignedNumbers { get; set; }
// TODO: use auto-properties when making 'ternary operator' an official feature.
private bool _forceEndNumberOnTernaryOpChars;
internal bool ForceEndNumberOnTernaryOpChars
{
get { return _forceEndNumberOnTernaryOpChars; }
set { _forceEndNumberOnTernaryOpChars = value; }
}
internal bool WantSimpleName { get; set; }
internal bool InWorkflowContext { get; set; }
internal List<Token> TokenList { get; set; }
internal Token FirstToken { get; private set; }
internal Token LastToken { get; private set; }
private List<Token> RequiresTokens { get; set; }
private bool InCommandMode() { return Mode == TokenizerMode.Command; }
private bool InExpressionMode() { return Mode == TokenizerMode.Expression; }
private bool InTypeNameMode() { return Mode == TokenizerMode.TypeName; }
private bool InSignatureMode() { return Mode == TokenizerMode.Signature; }
internal void Initialize(string fileName, string input, List<Token> tokenList)
{
_positionHelper = new PositionHelper(fileName, input);
_script = input;
this.TokenList = tokenList;
this.FirstToken = null;
this.LastToken = null;
this.RequiresTokens = null;
_beginSignatureExtent = null;
List<int> lineStartMap = new List<int>(100) { 0 };
for (int i = 0; i < input.Length; ++i)
{
char c = input[i];
if (c == '\r')
{
if ((i + 1) < input.Length && input[i + 1] == '\n')
{
i += 1;
}
lineStartMap.Add(i + 1);
}
if (c == '\n')
{
lineStartMap.Add(i + 1);
}
}
_currentIndex = 0;
Mode = TokenizerMode.Command;
_positionHelper.LineStartMap = lineStartMap.ToArray();
}
internal TokenizerState StartNestedScan(UnscannedSubExprToken nestedText)
{
TokenizerState ts = new TokenizerState
{
CurrentIndex = _currentIndex,
NestedTokensAdjustment = _nestedTokensAdjustment,
Script = _script,
TokenStart = _tokenStart,
FirstToken = FirstToken,
LastToken = LastToken,
SkippedCharOffsets = _skippedCharOffsets,
TokenList = TokenList,
};
_currentIndex = 0;
_nestedTokensAdjustment = ((InternalScriptExtent)nestedText.Extent).StartOffset;
_script = nestedText.Value;
_tokenStart = 0;
_skippedCharOffsets = nestedText.SkippedCharOffsets;
TokenList = (TokenList != null) ? new List<Token>() : null;
return ts;
}
internal void FinishNestedScan(TokenizerState ts)
{
_currentIndex = ts.CurrentIndex;
_nestedTokensAdjustment = ts.NestedTokensAdjustment;
_script = ts.Script;
_tokenStart = ts.TokenStart;
FirstToken = ts.FirstToken;
LastToken = ts.LastToken;
_skippedCharOffsets = ts.SkippedCharOffsets;
TokenList = ts.TokenList;
}
#region Utilities
private char GetChar()
{
Diagnostics.Assert(_currentIndex >= 0, "GetChar reading before start of input.");
Diagnostics.Assert(_currentIndex <= _script.Length + 1, "GetChar reading after end of input.");
// Increment _currentIndex, even if it goes over the Length so callers can call UngetChar to unget EOF.
int current = _currentIndex++;
if (current >= _script.Length)
{
return '\0';
}
return _script[current];
}
private void UngetChar()
{
Diagnostics.Assert(_currentIndex > 0, "UngetChar ungetting before start of input.");
_currentIndex -= 1;
}
private char PeekChar()
{
Diagnostics.Assert(_currentIndex >= 0 && _currentIndex <= _script.Length, "PeekChar out of range.");
if (_currentIndex == _script.Length)
{
return '\0';
}
return _script[_currentIndex];
}
private void SkipChar()
{
Diagnostics.Assert((_currentIndex + 1) <= _script.Length, "SkipChar can't skip past EOF");
_currentIndex += 1;
}
private bool AtEof()
{
return _currentIndex > _script.Length;
}
internal static bool IsKeyword(string str)
{
if (s_keywordTable.ContainsKey(str))
{
return true;
}
if (DynamicKeyword.ContainsKeyword(str) && !DynamicKeyword.IsHiddenKeyword(str))
{
return true;
}
return false;
}
internal void SkipNewlines(bool skipSemis)
{
// We normally don't create any tokens in a Skip method, but the
// V2 tokenizer api returns newline, semi-colon, and line
// continuation tokens so we create them as they are encountered.
again:
char c = GetChar();
switch (c)
{
case ' ':
case '\t':
case '\f':
case '\v':
case SpecialChars.NoBreakSpace:
case SpecialChars.NextLine:
SkipWhiteSpace();
goto again;
case '\r':
case '\n':
ScanNewline(c);
goto again;
case ';':
if (skipSemis)
{
ScanSemicolon();
goto again;
}
break;
case '#':
_tokenStart = _currentIndex - 1;
ScanLineComment();
goto again;
case '<':
if (PeekChar() == '#')
{
_tokenStart = _currentIndex - 1;
SkipChar();
ScanBlockComment();
goto again;
}
break;
case '`':
char c1 = GetChar();
if (c1 == '\n' || c1 == '\r')
{
ScanLineContinuation(c1);
goto again;
}
if (char.IsWhiteSpace(c1))
{
SkipWhiteSpace();
goto again;
}
UngetChar();
break;
default:
if (c.IsWhitespace())
{
SkipWhiteSpace();
goto again;
}
break;
}
UngetChar();
}
private void SkipWhiteSpace()
{
while (true)
{
char c = PeekChar();
if (!c.IsWhitespace())
{
break;
}
SkipChar();
}
}
private void ScanNewline(char c)
{
_tokenStart = _currentIndex - 1;
NormalizeCRLF(c);
// Memory optimization: only create the token if it will be stored
if (TokenList != null)
{
NewToken(TokenKind.NewLine);
}
}
private void ScanSemicolon()
{
_tokenStart = _currentIndex - 1;
// Memory optimization: only create the token if it will be stored
if (TokenList != null)
{
NewToken(TokenKind.Semi);
}
}
private void ScanLineContinuation(char c)
{
_tokenStart = _currentIndex - 2;
NormalizeCRLF(c);
// Memory optimization: only create the token if it will be stored
if (TokenList != null)
{
NewToken(TokenKind.LineContinuation);
}
}
internal int GetRestorePoint()
{
_tokenStart = _currentIndex;
return CurrentExtent().StartOffset;
}
internal void Resync(Token token)
{
// The parser has decided to backtrack and the tokenizer needs to pretend that it's
// starting over from the beginning of token.
Resync(((InternalScriptExtent)token.Extent).StartOffset);
}
internal void Resync(int start)
{
int adjustment = _nestedTokensAdjustment;
if (_skippedCharOffsets != null)
{
for (int i = _nestedTokensAdjustment; i < start - 1 && i < _skippedCharOffsets.Length; ++i)
{
if (_skippedCharOffsets[i])
{
adjustment += 1;
}
}
}
_currentIndex = start - adjustment;
if (_currentIndex > _script.Length + 1)
{
_currentIndex = _script.Length + 1;
}
else if (_currentIndex < 0)
{
_currentIndex = 0;
}
if (FirstToken != null && _currentIndex <= ((InternalScriptExtent)FirstToken.Extent).StartOffset)
{
FirstToken = null;
}
if (TokenList != null && TokenList.Count > 0)
{
// If we were saving tokens, remove all tokens from token to the end of the saved tokens.
RemoveTokensFromListDuringResync(TokenList, start);
}
if (RequiresTokens != null && RequiresTokens.Count > 0)
{
RemoveTokensFromListDuringResync(RequiresTokens, start);
}
}
internal void RemoveTokensFromListDuringResync(List<Token> tokenList, int start)
{
int removeFrom = 0;
// If we were saving tokens, remove all tokens from token to the end of the saved tokens.
int i = tokenList.Count - 1;
if (i >= 0 && tokenList[i].Kind == TokenKind.EndOfInput)
{
i -= 1;
}
for (; i >= 0; i--)
{
if (((InternalScriptExtent)tokenList[i].Extent).EndOffset <= start)
{
removeFrom = i + 1;
break;
}
}
tokenList.RemoveRange(removeFrom, tokenList.Count - removeFrom);
}
internal void ReplaceSavedTokens(Token firstOldToken, Token lastOldToken, Token newToken)
{
int startOffset = ((InternalScriptExtent)firstOldToken.Extent).StartOffset;
int endOffset = ((InternalScriptExtent)lastOldToken.Extent).EndOffset;
int lastTokenToReplace = -1;
for (int i = TokenList.Count - 1; i >= 0; i--)
{
if (((InternalScriptExtent)TokenList[i].Extent).EndOffset == endOffset)
{
lastTokenToReplace = i;
continue;
}
if (((InternalScriptExtent)TokenList[i].Extent).StartOffset == startOffset)
{
TokenList.RemoveRange(i, lastTokenToReplace - i + 1);
TokenList.Insert(i, newToken);
break;
}
}
}
private void NormalizeCRLF(char c)
{
// CRs in Windows line endings are ignored
if (c == '\r' && PeekChar() == '\n')
{
SkipChar();
}
}
internal void CheckAstIsBeforeSignature(Ast ast)
{
if (_beginSignatureExtent == null)
return;
if (_beginSignatureExtent.StartOffset < ast.Extent.StartOffset)
{
ReportError(ast.Extent,
nameof(ParserStrings.TokenAfterEndOfValidScriptText),
ParserStrings.TokenAfterEndOfValidScriptText);
}
}
private void ReportError(int errorOffset, string errorId, string errorMsg, params object[] args)
{
_parser.ReportError(NewScriptExtent(errorOffset, errorOffset + 1), errorId, errorMsg, args);
}
private void ReportError(IScriptExtent extent, string errorId, string errorMsg)
{
_parser.ReportError(extent, errorId, errorMsg);
}
private void ReportError(IScriptExtent extent, string errorId, string errorMsg, object arg)
{
_parser.ReportError(extent, errorId, errorMsg, arg);
}
private void ReportError(IScriptExtent extent, string errorId, string errorMsg, object arg1, object arg2)
{
_parser.ReportError(extent, errorId, errorMsg, arg1, arg2);
}
private void ReportIncompleteInput(int errorOffset, string errorId, string errorMsg)
{
_parser.ReportIncompleteInput(NewScriptExtent(errorOffset, _currentIndex), errorId, errorMsg);
}
private void ReportIncompleteInput(int errorOffset, string errorId, string errorMsg, object arg)
{
_parser.ReportIncompleteInput(NewScriptExtent(errorOffset, _currentIndex), errorId, errorMsg, arg);
}
private InternalScriptExtent NewScriptExtent(int start, int end)
{
return new InternalScriptExtent(_positionHelper, start + _nestedTokensAdjustment, end + _nestedTokensAdjustment);
}
internal InternalScriptExtent CurrentExtent()
{
int start = _tokenStart + _nestedTokensAdjustment;
int end = _currentIndex + _nestedTokensAdjustment;
if (_skippedCharOffsets != null)
{
int i = _nestedTokensAdjustment;
for (; i < start && i < _skippedCharOffsets.Length; ++i)
{
if (_skippedCharOffsets[i])
{
start += 1;
end += 1;
}
}
for (; i < end && i < _skippedCharOffsets.Length; ++i)
{
if (_skippedCharOffsets[i])
{
end += 1;
}
}
}
return new InternalScriptExtent(_positionHelper, start, end);
}
internal IScriptExtent GetScriptExtent()
{
return NewScriptExtent(0, _script.Length);
}
private Token NewCommentToken()
{
return SaveToken(new Token(CurrentExtent(), TokenKind.Comment, TokenFlags.None));
}
private T SaveToken<T>(T token) where T : Token
{
TokenList?.Add(token);
// Keep track of the first and last token even if we're not saving tokens
// for the special variables $$ and $^.
switch (token.Kind)
{
case TokenKind.NewLine:
case TokenKind.LineContinuation:
case TokenKind.Comment:
case TokenKind.EndOfInput:
// Don't remember these tokens, they aren't useful in $$ and $^.
break;
default:
FirstToken ??= token;
LastToken = token;
break;
}
return token;
}
private Token NewToken(TokenKind kind)
{
return SaveToken(new Token(CurrentExtent(), kind, TokenFlags.None));
}
private Token NewNumberToken(object value)
{
return SaveToken(new NumberToken(CurrentExtent(), value, TokenFlags.None));
}
private Token NewParameterToken(string name, bool sawColon)
{
return SaveToken(new ParameterToken(CurrentExtent(), name, sawColon));
}
private VariableToken NewVariableToken(VariablePath path, bool splatted)
{
return SaveToken(new VariableToken(CurrentExtent(), path, TokenFlags.None, splatted));
}
private StringToken NewStringLiteralToken(string value, TokenKind tokenKind, TokenFlags flags)
{
return SaveToken(new StringLiteralToken(CurrentExtent(), flags, tokenKind, value));
}
private StringToken NewStringExpandableToken(string value, string formatString, TokenKind tokenKind, List<Token> nestedTokens, TokenFlags flags)
{
if (nestedTokens != null && nestedTokens.Count == 0)
{
nestedTokens = null;
}
else if ((flags & TokenFlags.TokenInError) == 0)
{
if (nestedTokens.Any(static tok => tok.HasError))
{
flags |= TokenFlags.TokenInError;
}
}
return SaveToken(new StringExpandableToken(CurrentExtent(), tokenKind, value, formatString, nestedTokens, flags));
}
private Token NewGenericExpandableToken(string value, string formatString, List<Token> nestedTokens)
{
return NewStringExpandableToken(value, formatString, TokenKind.Generic, nestedTokens, TokenFlags.None);
}
private Token NewGenericToken(string value)
{
return NewStringLiteralToken(value, TokenKind.Generic, TokenFlags.None);
}
private Token NewInputRedirectionToken()
{
return SaveToken(new InputRedirectionToken(CurrentExtent()));
}
private Token NewFileRedirectionToken(int from, bool append, bool fromSpecifiedExplicitly)
{
if (fromSpecifiedExplicitly && InExpressionMode())
{
UngetChar();
if (append)
{
UngetChar();
}
return NewNumberToken(from);
}
return SaveToken(new FileRedirectionToken(CurrentExtent(), (RedirectionStream)from, append));
}
private Token NewMergingRedirectionToken(int from, int to)
{
return SaveToken(new MergingRedirectionToken(CurrentExtent(), (RedirectionStream)from, (RedirectionStream)to));
}
private LabelToken NewLabelToken(string value)
{
return SaveToken(new LabelToken(CurrentExtent(), TokenFlags.None, value));
}
internal bool IsAtEndOfScript(IScriptExtent extent, bool checkCommentsAndWhitespace = false)
{
var scriptExtent = (InternalScriptExtent)extent;
return scriptExtent.EndOffset >= _script.Length
|| (checkCommentsAndWhitespace && OnlyWhitespaceOrCommentsAfterExtent(scriptExtent));
}
private bool OnlyWhitespaceOrCommentsAfterExtent(InternalScriptExtent extent)
{
for (int i = extent.EndOffset; i < _script.Length; ++i)
{
if (_script[i] == '#')
{
// SkipLineComment will return the position after the comment end
// which is either at the end of the file, or a cr or lf.
i = SkipLineComment(i + 1) - 1;
continue;
}
if (_script[i] == '<' && (i + 1) < _script.Length && _script[i + 1] == '#')
{
i = SkipBlockComment(i + 2) - 1;
continue;
}
if (!_script[i].IsWhitespace())
{
return false;
}
}
return true;
}
internal bool IsPipeContinuation(IScriptExtent extent)
{
// If the first non-whitespace & non-comment (regular or block) character following a newline is a pipe, we have
// pipe continuation.
return extent.EndOffset < _script.Length && ContinuationAfterExtent(extent, continuationChar: '|');
}
private bool ContinuationAfterExtent(IScriptExtent extent, char continuationChar)
{
bool lastNonWhitespaceIsNewline = true;
int i = extent.EndOffset;
// Since some token pattern matching looks for multiple characters (e.g. newline or block comment)
// we stop searching at _script.Length - 1 and perform one additional check after the while loop.
// This avoids having to compare i + 1 against the script length in multiple locations inside the
// loop.
while (i < _script.Length - 1)
{
char c = _script[i];
if (c.IsWhitespace())
{
i++;
continue;
}
if (c == '\n')
{
if (lastNonWhitespaceIsNewline)
{
// blank or whitespace-only lines are not allowed in automatic line continuation
return false;
}
lastNonWhitespaceIsNewline = true;
i++;
continue;
}
else if (c == '\r')
{
if (lastNonWhitespaceIsNewline)
{
// blank or whitespace-only lines are not allowed in automatic line continuation
return false;
}
lastNonWhitespaceIsNewline = true;
i += _script[i + 1] == '\n' ? 2 : 1;
continue;
}
lastNonWhitespaceIsNewline = false;
if (c == '#')
{
// SkipLineComment will return the position after the comment end
// which is either at the end of the file, or a cr or lf.
i = SkipLineComment(i + 1);
continue;
}
if (c == '<' && _script[i + 1] == '#')
{
i = SkipBlockComment(i + 2);
continue;
}
return c == continuationChar;
}
return _script[_script.Length - 1] == continuationChar;
}
private int SkipLineComment(int i)
{
for (; i < _script.Length; ++i)
{
char c = _script[i];
if (c == '\r' || c == '\n')
{
break;
}
}
return i;
}
private int SkipBlockComment(int i)
{
for (; i < _script.Length; ++i)
{
char c = _script[i];
if (c == '#' && (i + 1) < _script.Length && _script[i + 1] == '>')
{
return i + 2;
}
}
return i;
}
private char Backtick(char c, out char surrogateCharacter)
{
surrogateCharacter = s_invalidChar;
switch (c)
{
case '0':
return '\0';
case 'a':
return '\a';
case 'b':
return '\b';
case 'e':
return '\u001b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'u':
return ScanUnicodeEscape(out surrogateCharacter);
case 'v':
return '\v';
default:
return c;
}
}
private char ScanUnicodeEscape(out char surrogateCharacter)
{
int escSeqStartIndex = _currentIndex - 2;
surrogateCharacter = s_invalidChar;
char c = GetChar();
if (c != '{')
{
UngetChar();
IScriptExtent errorExtent = NewScriptExtent(escSeqStartIndex, _currentIndex);
ReportError(errorExtent,
nameof(ParserStrings.InvalidUnicodeEscapeSequence),
ParserStrings.InvalidUnicodeEscapeSequence);
return s_invalidChar;
}
// Scan the rest of the Unicode escape sequence - one to six hex digits terminated plus the closing '}'.
var sb = GetStringBuilder();
int i;
for (i = 0; i < s_maxNumberOfUnicodeHexDigits + 1; i++)
{
c = GetChar();
// Sequence has been terminated.
if (c == '}')
{
if (i == 0)
{
// Sequence must have at least one hex char.
Release(sb);
IScriptExtent errorExtent = NewScriptExtent(escSeqStartIndex, _currentIndex);
ReportError(errorExtent,
nameof(ParserStrings.InvalidUnicodeEscapeSequence),
ParserStrings.InvalidUnicodeEscapeSequence);
return s_invalidChar;
}
break;
}
else if (!c.IsHexDigit())
{
UngetChar();
Release(sb);
if (i < s_maxNumberOfUnicodeHexDigits)
{
ReportError(_currentIndex,
nameof(ParserStrings.InvalidUnicodeEscapeSequence),
ParserStrings.InvalidUnicodeEscapeSequence);
}
else
{
ReportError(_currentIndex,
nameof(ParserStrings.MissingUnicodeEscapeSequenceTerminator),
ParserStrings.MissingUnicodeEscapeSequenceTerminator);
}
return s_invalidChar;
}
else if (i == s_maxNumberOfUnicodeHexDigits)
{
UngetChar();
Release(sb);
ReportError(_currentIndex,
nameof(ParserStrings.TooManyDigitsInUnicodeEscapeSequence),
ParserStrings.TooManyDigitsInUnicodeEscapeSequence);
return s_invalidChar;
}
sb.Append(c);
}
string hexStr = GetStringAndRelease(sb);
uint unicodeValue = uint.Parse(hexStr, NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo);
if (unicodeValue <= char.MaxValue)
{
return ((char)unicodeValue);
}
else if (unicodeValue <= 0x10FFFF)
{
return GetCharsFromUtf32(unicodeValue, out surrogateCharacter);
}
else
{
// Place the error indicator under only the hex digits in the esc sequence.
IScriptExtent errorExtent = NewScriptExtent(escSeqStartIndex + 3, _currentIndex - 1);
ReportError(errorExtent,
nameof(ParserStrings.InvalidUnicodeEscapeSequenceValue),
ParserStrings.InvalidUnicodeEscapeSequenceValue);
return s_invalidChar;
}
}
private static char GetCharsFromUtf32(uint codepoint, out char lowSurrogate)
{
if (codepoint < (uint)0x00010000)
{
lowSurrogate = s_invalidChar;
return (char)codepoint;
}
else
{
Diagnostics.Assert((codepoint > 0x0000FFFF) && (codepoint <= 0x0010FFFF), "Codepoint is out of range for a surrogate pair");
lowSurrogate = (char)((codepoint - 0x00010000) % 0x0400 + 0xDC00);
return (char)((codepoint - 0x00010000) / 0x0400 + 0xD800);
}
}
private void ScanToEndOfCommentLine(out bool sawBeginSig, out bool matchedRequires)
{
// When we get here, we are scanning a line comment. To avoid rescanning,
// we look for a script signature while we scan to the end of the line.
//
// We want to find both real signatures and fake signatures, with the goal of disallowing any
// code after anything that looks like a signature because people often stop reading a script
// once they see a signature - making it relatively easy to "hide" trojan like code in a script
// after a fake signature.
//
// To "match" a signature, we compare its similarity (using Levenshtein Distance) to find
// comments that look confusingly similar to the actual signature block (mapping to lowercase,
// and ignoring spaces).
//
// At the same time, we also want to match #requires. We do this with a simple state machine,
// incrementing the state as we continue to match, or set requiresMatchState to -1 if we failed to match.
var commentLine = GetStringBuilder();
int requiresMatchState = 0;
matchedRequires = false;
while (true)
{
char c = GetChar();
if (!c.IsWhitespace())
{
commentLine.Append(c);
}
switch (c)
{
case 'e':
case 'E':
if (requiresMatchState == 1 || requiresMatchState == 6)
requiresMatchState += 1;
else
requiresMatchState = -1;
break;
case 'i':
case 'I':
if (requiresMatchState == 4)
requiresMatchState += 1;
else
requiresMatchState = -1;
break;
case 'q':
case 'Q':
if (requiresMatchState == 2)
requiresMatchState += 1;
else
requiresMatchState = -1;
break;
case 'r':
case 'R':
if (requiresMatchState == 0 || requiresMatchState == 5)
requiresMatchState += 1;
else
requiresMatchState = -1;
break;
case 's':
case 'S':
if (requiresMatchState == 7)
matchedRequires = true;
else
requiresMatchState = -1;
break;
case 'u':
case 'U':
if (requiresMatchState == 3)
requiresMatchState += 1;
else
requiresMatchState = -1;
break;
case '\0':
if (AtEof())
{
goto case '\n';
}
goto default;
case '\r':
case '\n':
UngetChar();
// Detect a line comment that disguises itself to look like the beginning of a signature block.
// This could be used to hide code at the bottom of a script, since people might assume there is nothing else after the signature.
//
// The token similarity threshold was chosen by instrumenting the tokenizer and
// analyzing every comment from PoshCode, Technet Script Center, and Windows.
//
// The closest comments above "10" had a score of 11, which are marginal and
// appropriately close to being tricky.
//
// # END BEGIN SCRIPT BLOCK
// # SET TEXT SIGNATURE
//
// Below 11 were only actual signature blocks:
//
// # SIG # END SIGNATURE BLOCK
// # SIG # BEGIN SIGNATURE BLOCK
//
// There were only 279 (out of 269,387) comments with a similarity of 11,12,13,14, or 15.
// At a similarity of 16-77, there were thousands of comments per similarity bucket.
const string beginSignatureTextNoSpace = "sig#beginsignatureblock\n";
const int beginTokenSimilarityThreshold = 10;
const int beginTokenSimilarityUpperBound = 34; // beginSignatureTextNoSpace.Length + beginTokenSimilarityThreshold
const int beginTokenSimilarityLowerBound = 14; // beginSignatureTextNoSpace.Length - beginTokenSimilarityThreshold
// Quick exit - the comment line is more than 'threshold' longer, or is less than 'threshold' shorter. Therefore,
// its similarity will be over the threshold.
if (commentLine.Length > beginTokenSimilarityUpperBound || commentLine.Length < beginTokenSimilarityLowerBound)
{
sawBeginSig = false;
}
else
{
// Perf note - the GetStringSimilarity function is able to evaluate approximately 50kb of pure comments
// (1000 lines, each of length between 10 and 80 characters) in about 40ms, compared to 6ms it took to
// doing the error-prone hashing approach we had implemented before.
//
// The average script is 14% comments and parses in about 5.05 ms with this algorithm,
// about 4.45 ms with the more simplistic algorithm.
string commentLineComparison = commentLine.ToString().ToLowerInvariant();
if (_beginTokenSimilarity2dArray == null)
{
// Create the 2 dimensional array for edit distance calculation if it hasn't been created yet.
_beginTokenSimilarity2dArray = new int[beginTokenSimilarityUpperBound + 1, beginSignatureTextNoSpace.Length + 1];
}
else
{
// Zero out the 2 dimensional array before using it.
Array.Clear(_beginTokenSimilarity2dArray, 0, _beginTokenSimilarity2dArray.Length);
}
int sawBeginTokenSimilarity = GetStringSimilarity(commentLineComparison, beginSignatureTextNoSpace, _beginTokenSimilarity2dArray);
sawBeginSig = sawBeginTokenSimilarity < beginTokenSimilarityThreshold;
}
Release(commentLine);
return;
default:
requiresMatchState = -1;
break;
}
}
}
#endregion Utilities
#region Object reuse
// A two-dimensional integer array reused for calculating string similarity.
private int[,] _beginTokenSimilarity2dArray;
private readonly Queue<StringBuilder> _stringBuilders = new Queue<StringBuilder>();
private StringBuilder GetStringBuilder()
{
return _stringBuilders.Count == 0 ? new StringBuilder() : _stringBuilders.Dequeue();
}
private void Release(StringBuilder sb)
{
// We don't want to cache too much, so limit to 10 string builders
// and don't keep any that have > 1kb
if (_stringBuilders.Count < 10 && sb.Capacity < 1024)
{
sb.Clear();
_stringBuilders.Enqueue(sb);
}
}
private string GetStringAndRelease(StringBuilder sb)
{
var result = sb.ToString();
Release(sb);
return result;
}
#endregion Object reuse
#region Comments
private void ScanLineComment()
{
bool sawBeginSig;
bool matchedRequires;
ScanToEndOfCommentLine(out sawBeginSig, out matchedRequires);
var token = NewCommentToken();
if (sawBeginSig)
{
_beginSignatureExtent = CurrentExtent();
}
else if (matchedRequires && _nestedTokensAdjustment == 0)
{
RequiresTokens ??= new List<Token>();
RequiresTokens.Add(token);
}
}
private void ScanBlockComment()
{
int errorIndex = _currentIndex - 2;
while (true)
{
char c = GetChar();
if (c == '#' && PeekChar() == '>')
{
SkipChar();
break;
}
if (c == '\r')
{
NormalizeCRLF(c);
}
else if (c == '\0' && AtEof())
{
UngetChar();
ReportIncompleteInput(errorIndex,
nameof(ParserStrings.MissingTerminatorMultiLineComment),
ParserStrings.MissingTerminatorMultiLineComment);
break;
}
}
NewCommentToken();
}
// Implementation of the Levenshtein Distance algorithm
// https://en.wikipedia.org/wiki/Levenshtein_distance
private static int GetStringSimilarity(string first, string second, int[,] distanceMap = null)
{
Diagnostics.Assert(!string.IsNullOrEmpty(first) && !string.IsNullOrEmpty(second), "Caller never calls us with empty strings");
// Store a distance map to store the number of edits required to
// convert the first <row> letters of First to the first <column>
// letters of Second.
distanceMap ??= new int[first.Length + 1, second.Length + 1];
// Initialize the first row and column of the matrix - the number
// of edits required when one of the strings is empty is just
// the length of the non-empty string
for (int row = 0; row <= first.Length; row++)
{
distanceMap[row, 0] = row;
}
for (int column = 0; column <= second.Length; column++)
{
distanceMap[0, column] = column;
}
// Visit all prefixes and determine the minimum edit distance
for (int row = 1; row <= first.Length; row++)
{
for (int column = 1; column <= second.Length; column++)
{
// If these two characters are the same, then
// The edit distance is the same as it was for the
// two shorter substrings without this character.
if (first[row - 1] == second[column - 1])
{
distanceMap[row, column] = distanceMap[row - 1, column - 1];
}
else
{
// Otherwise, the edit distance is the minimum
// of doing an addition of a character, a deletion
// of a character, or a substitution of a character
distanceMap[row, column] = Math.Min(
Math.Min(
distanceMap[row - 1, column] + 1,
distanceMap[row, column - 1] + 1),
distanceMap[row - 1, column - 1] + 1);
}
}
}
return distanceMap[first.Length, second.Length];
}
#region Requires
internal ScriptRequirements GetScriptRequirements()
{
if (RequiresTokens == null)
return null;
// Make sure a nested scan of the #requires lines don't affect our processing here.
var requiresTokens = RequiresTokens.ToArray();
RequiresTokens = null;
string requiredShellId = null;
Version requiredVersion = null;
List<string> requiredEditions = null;
List<ModuleSpecification> requiredModules = null;
List<PSSnapInSpecification> requiredSnapins = null;
List<string> requiredAssemblies = null;
bool requiresElevation = false;
foreach (var token in requiresTokens)
{
var requiresExtent = new InternalScriptExtent(_positionHelper, token.Extent.StartOffset + 1, token.Extent.EndOffset);
var state = StartNestedScan(new UnscannedSubExprToken(requiresExtent, TokenFlags.None, requiresExtent.Text, null));
var commandAst = _parser.CommandRule(forDynamicKeyword: false) as CommandAst;
_parser._ungotToken = null;
FinishNestedScan(state);
string snapinName = null;
Version snapinVersion = null;
if (commandAst != null)
{
var commandName = commandAst.GetCommandName();
if (!string.Equals(commandName, "requires", StringComparison.OrdinalIgnoreCase))
{
ReportError(commandAst.Extent,
nameof(DiscoveryExceptions.ScriptRequiresInvalidFormat),
DiscoveryExceptions.ScriptRequiresInvalidFormat);
}
var snapinSpecified = false;
for (int i = 1; i < commandAst.CommandElements.Count; i++)
{
var parameter = commandAst.CommandElements[i] as CommandParameterAst;
if (parameter != null &&
PSSnapinToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
snapinSpecified = true;
requiredSnapins ??= new List<PSSnapInSpecification>();
break;
}
}
for (int i = 1; i < commandAst.CommandElements.Count; i++)
{
var parameter = commandAst.CommandElements[i] as CommandParameterAst;
if (parameter != null)
{
HandleRequiresParameter(parameter, commandAst.CommandElements, snapinSpecified,
ref i, ref snapinName, ref snapinVersion,
ref requiredShellId, ref requiredVersion, ref requiredEditions, ref requiredModules, ref requiredAssemblies, ref requiresElevation);
}
else
{
ReportError(commandAst.CommandElements[i].Extent,
nameof(DiscoveryExceptions.ScriptRequiresInvalidFormat),
DiscoveryExceptions.ScriptRequiresInvalidFormat);
}
}
if (snapinName != null)
{
Diagnostics.Assert(PSSnapInInfo.IsPSSnapinIdValid(snapinName), "we shouldn't set snapinName if it wasn't valid");
requiredSnapins.Add(new PSSnapInSpecification(snapinName) { Version = snapinVersion });
}
}
}
return new ScriptRequirements
{
RequiredApplicationId = requiredShellId,
RequiredPSVersion = requiredVersion,
RequiredPSEditions = requiredEditions != null
? new ReadOnlyCollection<string>(requiredEditions)
: ScriptRequirements.EmptyEditionCollection,
RequiredAssemblies = requiredAssemblies != null
? new ReadOnlyCollection<string>(requiredAssemblies)
: ScriptRequirements.EmptyAssemblyCollection,
RequiredModules = requiredModules != null
? new ReadOnlyCollection<ModuleSpecification>(requiredModules)
: ScriptRequirements.EmptyModuleCollection,
IsElevationRequired = requiresElevation
};
}
private const string shellIDToken = "shellid";
private const string PSSnapinToken = "pssnapin";
private const string versionToken = "version";
private const string editionToken = "psedition";
private const string assemblyToken = "assembly";
private const string modulesToken = "modules";
private const string elevationToken = "runasadministrator";
private void HandleRequiresParameter(CommandParameterAst parameter,
ReadOnlyCollection<CommandElementAst> commandElements,
bool snapinSpecified,
ref int index,
ref string snapinName,
ref Version snapinVersion,
ref string requiredShellId,
ref Version requiredVersion,
ref List<string> requiredEditions,
ref List<ModuleSpecification> requiredModules,
ref List<string> requiredAssemblies,
ref bool requiresElevation)
{
Ast argumentAst = parameter.Argument ?? (index + 1 < commandElements.Count ? commandElements[++index] : null);
if (elevationToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
requiresElevation = true;
if (argumentAst != null)
{
ReportError(parameter.Extent,
nameof(ParserStrings.ParameterCannotHaveArgument),
ParserStrings.ParameterCannotHaveArgument,
parameter.ParameterName);
}
return;
}
if (argumentAst == null)
{
ReportError(parameter.Extent,
nameof(ParserStrings.ParameterRequiresArgument),
ParserStrings.ParameterRequiresArgument,
parameter.ParameterName);
return;
}
object argumentValue;
if (!IsConstantValueVisitor.IsConstant(argumentAst, out argumentValue, forRequires: true))
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresArgumentMustBeConstant),
ParserStrings.RequiresArgumentMustBeConstant);
return;
}
if (shellIDToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
if (requiredShellId != null)
{
ReportError(parameter.Extent,
nameof(ParameterBinderStrings.ParameterAlreadyBound),
ParameterBinderStrings.ParameterAlreadyBound,
null,
shellIDToken);
return;
}
if (argumentValue is not string)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresInvalidStringArgument),
ParserStrings.RequiresInvalidStringArgument,
shellIDToken);
return;
}
requiredShellId = (string)argumentValue;
}
else if (PSSnapinToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
if (argumentValue is not string)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresInvalidStringArgument),
ParserStrings.RequiresInvalidStringArgument,
PSSnapinToken);
return;
}
if (snapinName != null)
{
ReportError(parameter.Extent,
nameof(ParameterBinderStrings.ParameterAlreadyBound),
ParameterBinderStrings.ParameterAlreadyBound,
null,
PSSnapinToken);
return;
}
if (!PSSnapInInfo.IsPSSnapinIdValid((string)argumentValue))
{
ReportError(argumentAst.Extent,
nameof(MshSnapInCmdletResources.InvalidPSSnapInName),
MshSnapInCmdletResources.InvalidPSSnapInName);
return;
}
snapinName = (string)argumentValue;
}
else if (editionToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
if (requiredEditions != null)
{
ReportError(parameter.Extent,
nameof(ParameterBinderStrings.ParameterAlreadyBound),
ParameterBinderStrings.ParameterAlreadyBound,
null,
editionToken);
return;
}
if (argumentValue is string || argumentValue is not IEnumerable)
{
requiredEditions = HandleRequiresPSEditionArgument(argumentAst, argumentValue, ref requiredEditions);
}
else
{
foreach (var arg in (IEnumerable)argumentValue)
{
requiredEditions = HandleRequiresPSEditionArgument(argumentAst, arg, ref requiredEditions);
}
}
}
else if (versionToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
var argumentText = argumentValue as string ?? argumentAst.Extent.Text;
var version = Utils.StringToVersion(argumentText);
if (version == null)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresVersionInvalid),
ParserStrings.RequiresVersionInvalid);
return;
}
if (snapinSpecified)
{
if (snapinVersion != null)
{
ReportError(parameter.Extent,
nameof(ParameterBinderStrings.ParameterAlreadyBound),
ParameterBinderStrings.ParameterAlreadyBound,
null,
versionToken);
return;
}
snapinVersion = version;
}
else
{
if (requiredVersion != null && !requiredVersion.Equals(version))
{
ReportError(parameter.Extent,
nameof(ParameterBinderStrings.ParameterAlreadyBound),
ParameterBinderStrings.ParameterAlreadyBound,
null,
versionToken);
return;
}
requiredVersion = version;
}
}
else if (assemblyToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
if (argumentValue is string || argumentValue is not IEnumerable)
{
requiredAssemblies = HandleRequiresAssemblyArgument(argumentAst, argumentValue, requiredAssemblies);
}
else
{
foreach (var arg in (IEnumerable)argumentValue)
{
requiredAssemblies = HandleRequiresAssemblyArgument(argumentAst, arg, requiredAssemblies);
}
}
}
else if (modulesToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase))
{
var enumerable = argumentValue as object[] ?? new[] { argumentValue };
foreach (var arg in enumerable)
{
ModuleSpecification moduleSpecification;
try
{
moduleSpecification = LanguagePrimitives.ConvertTo<ModuleSpecification>(arg);
}
catch (InvalidCastException e)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresModuleInvalid),
ParserStrings.RequiresModuleInvalid,
e.Message);
return;
}
catch (ArgumentException e)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresModuleInvalid),
ParserStrings.RequiresModuleInvalid,
e.Message);
return;
}
requiredModules ??= new List<ModuleSpecification>();
requiredModules.Add(moduleSpecification);
}
}
else
{
ReportError(parameter.Extent,
nameof(DiscoveryExceptions.ScriptRequiresInvalidFormat),
DiscoveryExceptions.ScriptRequiresInvalidFormat);
}
}
private List<string> HandleRequiresAssemblyArgument(Ast argumentAst, object arg, List<string> requiredAssemblies)
{
if (arg is not string)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresInvalidStringArgument),
ParserStrings.RequiresInvalidStringArgument,
assemblyToken);
}
else
{
requiredAssemblies ??= new List<string>();
if (!requiredAssemblies.Contains((string)arg))
{
requiredAssemblies.Add((string)arg);
}
}
return requiredAssemblies;
}
private List<string> HandleRequiresPSEditionArgument(Ast argumentAst, object arg, ref List<string> requiredEditions)
{
if (arg is not string)
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresInvalidStringArgument),
ParserStrings.RequiresInvalidStringArgument,
editionToken);
}
else
{
requiredEditions ??= new List<string>();
var edition = (string)arg;
if (!Utils.IsValidPSEditionValue(edition))
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresPSEditionInvalid),
ParserStrings.RequiresPSEditionInvalid,
editionToken);
}
if (!requiredEditions.Contains(edition, StringComparer.OrdinalIgnoreCase))
{
requiredEditions.Add(edition);
}
else
{
ReportError(argumentAst.Extent,
nameof(ParserStrings.RequiresPSEditionValueIsAlreadySpecified),
ParserStrings.RequiresPSEditionValueIsAlreadySpecified,
editionToken);
}
}
return requiredEditions;
}
#endregion Requires
#endregion Comments
#region Strings
// When processing a verbatim command argument, read until the end
// of line completely ignoring all PowerShell semantics.
internal StringToken GetVerbatimCommandArgument()
{
SkipWhiteSpace();
_tokenStart = _currentIndex;
bool inQuotes = false;
while (true)
{
char c = GetChar();
if (c == '\r' || c == '\n' || (c == '\0' && AtEof()))
{
UngetChar();
break;
}
if (c.IsDoubleQuote())
{
inQuotes = !inQuotes;
continue;
}
if (!inQuotes && (c == '|' || (c == '&' && !AtEof() && PeekChar() == '&')))
{
UngetChar();
break;
}
}
InternalScriptExtent currentExtent = CurrentExtent();
string tokenValue = currentExtent.Text;
return NewStringLiteralToken(tokenValue, TokenKind.Generic, TokenFlags.None);
}
private TokenFlags ScanStringLiteral(StringBuilder sb)
{
int errorIndex = _currentIndex - 1;
TokenFlags flags = TokenFlags.None;
char c = GetChar();
while (c != '\0' || !AtEof())
{
if (c.IsSingleQuote())
{
// Check for 2 quotes in a row. If so, the first is the "escape"
// and append the second quote. Otherwise, we're done collecting.
if (!PeekChar().IsSingleQuote())
{
break;
}
c = GetChar();
}
sb.Append(c);
c = GetChar();
}
if (c == '\0')
{
// error - reached end of input without seeing terminator
UngetChar();
ReportIncompleteInput(errorIndex,
nameof(ParserStrings.TerminatorExpectedAtEndOfString),
ParserStrings.TerminatorExpectedAtEndOfString,
"'");
flags = TokenFlags.TokenInError;
}
return flags;
}
private Token ScanStringLiteral()
{
var sb = GetStringBuilder();
var flags = ScanStringLiteral(sb);
return NewStringLiteralToken(GetStringAndRelease(sb), TokenKind.StringLiteral, flags);
}
private Token ScanSubExpression(bool hereString)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
_tokenStart = _currentIndex - 2;
var sb = GetStringBuilder();
sb.Append("$(");
int parenCount = 1;
TokenFlags flags = TokenFlags.None;
bool scanning = true;
List<int> skippedCharOffsets = new List<int>();
while (scanning)
{
char c = GetChar();
switch (c)
{
case '(':
sb.Append(c);
++parenCount;
break;
case ')':
sb.Append(c);
if (--parenCount == 0)
{
scanning = false;
}
break;
case '`':
case '"':
case SpecialChars.QuoteDoubleLeft:
case SpecialChars.QuoteDoubleRight:
case SpecialChars.QuoteLowDoubleLeft:
char c1 = PeekChar();
if (!hereString && c1.IsDoubleQuote())
{
SkipChar();
sb.Append(c1);
skippedCharOffsets.Add(_currentIndex - 2 + _nestedTokensAdjustment);
}
else
{
sb.Append(c);
}
break;
case '\0':
if (!AtEof())
goto default;
UngetChar();
ReportIncompleteInput(_tokenStart,
nameof(ParserStrings.IncompleteDollarSubexpressionReference),
ParserStrings.IncompleteDollarSubexpressionReference);
flags = TokenFlags.TokenInError;
scanning = false;
break;
default:
sb.Append(c);
break;
}
}
BitArray skippedCharBitArray;
if (skippedCharOffsets.Count > 0)
{
skippedCharBitArray = new BitArray(skippedCharOffsets.Last() + 1);
foreach (int i in skippedCharOffsets)
{
skippedCharBitArray.Set(i, true);
}
}
else
{
skippedCharBitArray = _skippedCharOffsets;
}
var extent = CurrentExtent();
Diagnostics.Assert(
(extent.Text[0] == '$' && extent.Text[1] == '(' && extent.Text[extent.Text.Length - 1] == ')') || (flags & TokenFlags.TokenInError) != 0,
"Extent computed incorrectly.");
return new UnscannedSubExprToken(extent, flags, GetStringAndRelease(sb), skippedCharBitArray);
}
private TokenFlags ScanStringExpandable(StringBuilder sb, StringBuilder formatSb, List<Token> nestedTokens)
{
TokenFlags flags = TokenFlags.None;
int errorIndex = _currentIndex - 1;
char c = GetChar();
for (; c != '\0' || !AtEof(); c = GetChar())
{
if (c.IsDoubleQuote())
{
// Check for 2 quotes in a row. If so, the first is the "escape"
// and append the second quote. Otherwise, we're done collecting.
if (!PeekChar().IsDoubleQuote())
{
break;
}
c = GetChar();
}
else if (c == '$')
{
if (ScanDollarInStringExpandable(sb, formatSb, false, nestedTokens))
{
continue;
}
}
else if (c == '`')
{
// If end of input, go ahead and append the backtick and issue an error later
char c1 = PeekChar();
if (c1 != 0)
{
SkipChar();
c = Backtick(c1, out char surrogateCharacter);
if (surrogateCharacter != s_invalidChar)
{
sb.Append(c).Append(surrogateCharacter);
formatSb.Append(c).Append(surrogateCharacter);
continue;
}
}
}
if (c == '{' || c == '}')
{
// In the format string, we need to double up the curlies because we're
// replacing variable references and sub-expressions with the appropriate
// format expression for string.Format.
formatSb.Append(c);
}
sb.Append(c);
formatSb.Append(c);
}
if (c == '\0')
{
UngetChar();
ReportIncompleteInput(errorIndex,
nameof(ParserStrings.TerminatorExpectedAtEndOfString),
ParserStrings.TerminatorExpectedAtEndOfString,
"\"");
flags = TokenFlags.TokenInError;
}
return flags;
}
// Returns true if a variable or sub-expression is successfully scanned, false otherwise.
private bool ScanDollarInStringExpandable(StringBuilder sb, StringBuilder formatSb, bool hereString, List<Token> nestedTokens)
{
int dollarIndex = _currentIndex - 1;
char c1 = PeekChar();
int saveTokenStart = _tokenStart;
var oldTokenizerMode = Mode;
var oldTokenList = TokenList;
Token nestedToken = null;
try
{
// None of these tokens should be saved
TokenList = null;
Mode = TokenizerMode.Expression;
if (c1 == '(')
{
SkipChar();
nestedToken = ScanSubExpression(hereString);
}
else if (c1.IsVariableStart() || c1 == '{')
{
_tokenStart = _currentIndex - 1;
nestedToken = ScanVariable(false, true);
}
}
finally
{
TokenList = oldTokenList;
_tokenStart = saveTokenStart;
Mode = oldTokenizerMode;
}
if (nestedToken != null)
{
sb.Append(_script, dollarIndex, _currentIndex - dollarIndex);
formatSb.Append('{');
formatSb.Append(nestedTokens.Count);
formatSb.Append('}');
nestedTokens.Add(nestedToken);
return true;
}
// Make sure we didn't consume anything because we didn't find
// any nested tokens (no variable or subexpression.)
Diagnostics.Assert(PeekChar() == c1, "We accidentally consumed a character we shouldn't have.");
return false;
}
private Token ScanStringExpandable()
{
var sb = GetStringBuilder();
var formatSb = GetStringBuilder();
List<Token> nestedTokens = new List<Token>();
TokenFlags flags = ScanStringExpandable(sb, formatSb, nestedTokens);
return NewStringExpandableToken(GetStringAndRelease(sb), GetStringAndRelease(formatSb), TokenKind.StringExpandable, nestedTokens, flags);
}
private bool ScanAfterHereStringHeader(string header)
{
// On entry, we've see the header. We allow whitespace and require a newline before the actual string starts
int headerOffset = _currentIndex - 2;
char c;
do
{
c = GetChar();
} while (c.IsWhitespace());
if (c == '\r')
{
NormalizeCRLF(c);
}
else if (c != '\n')
{
if (c == '\0' && AtEof())
{
UngetChar();
ReportIncompleteInput(headerOffset,
nameof(ParserStrings.TerminatorExpectedAtEndOfString),
ParserStrings.TerminatorExpectedAtEndOfString,
string.Concat(header[1], '@'));
return false;
}
UngetChar();
// ErrorRecovery: just ignore the characters and look for a terminator. If no terminator is found, resume
// scanning at the end of the line. Don't skip the newline so we have a newline to terminate the current
// expression.
ReportError(_currentIndex,
nameof(ParserStrings.UnexpectedCharactersAfterHereStringHeader),
ParserStrings.UnexpectedCharactersAfterHereStringHeader);
while (true)
{
c = GetChar();
if (c == header[1] && (PeekChar() == '@'))
{
SkipChar();
break;
}
if (c == '\r' || c == '\n' || (c == '\0' && AtEof()))
{
UngetChar();
break;
}
}
return false;
}
return true;
}
private bool ScanPossibleHereStringFooter(Func<char, bool> test, Action<char> appendChar, ref int falseFooterOffset)
{
char c = GetChar();
// First, check if we found the real terminator.
if (test(c) && PeekChar() == '@')
{
SkipChar();
return true;
}
// Catch whitespace before the terminator so we can issue
// a better error message than "missing terminator".
while (c.IsWhitespace())
{
appendChar(c);
c = GetChar();
}
if (c == '\r' || c == '\n' || (c == '\0' && AtEof()))
{
UngetChar();
return false;
}
if (test(c) && PeekChar() == '@')
{
appendChar(c);
if (falseFooterOffset == -1)
{
// If we don't find a real footer, we'll use this position
// to give a helpful error message.
falseFooterOffset = _currentIndex - 1;
}
appendChar(GetChar()); // append the '@'
}
else
{
// Unget the character, it might be a '$' or '`' and if we're in a expandable here string, the caller must
// handle the character.
UngetChar();
}
return false;
}
private Token ScanHereStringLiteral()
{
// On entry, we've see @'. Remember the position in case we reach the end of file and want
// to use this position as the error position.
int headerOffset = _currentIndex - 2;
int falseFooterOffset = -1;
if (!ScanAfterHereStringHeader("@'"))
{
return NewStringLiteralToken(string.Empty, TokenKind.HereStringLiteral, TokenFlags.TokenInError);
}
TokenFlags flags = TokenFlags.None;
var sb = GetStringBuilder();
Action<char> appendChar = c => sb.Append(c);
if (!ScanPossibleHereStringFooter(CharExtensions.IsSingleQuote, appendChar, ref falseFooterOffset))
{
while (true)
{
char c = GetChar();
if (c == '\r' || c == '\n')
{
// Remember the length, we may remove this newline (which is 1 or 2 characters).
int length = sb.Length;
sb.Append(c);
if (c == '\r' && PeekChar() == '\n')
{
SkipChar();
sb.Append('\n');
}
if (ScanPossibleHereStringFooter(CharExtensions.IsSingleQuote, appendChar, ref falseFooterOffset))
{
// Remove the last newline appended.
sb.Length = length;
break;
}
}
else if (c != '\0' || !AtEof())
{
sb.Append(c);
}
else
{
UngetChar();
if (falseFooterOffset != -1)
{
ReportIncompleteInput(falseFooterOffset,
nameof(ParserStrings.WhitespaceBeforeHereStringFooter),
ParserStrings.WhitespaceBeforeHereStringFooter);
}
else
{
ReportIncompleteInput(headerOffset,
nameof(ParserStrings.TerminatorExpectedAtEndOfString),
ParserStrings.TerminatorExpectedAtEndOfString,
"'@");
}
flags = TokenFlags.TokenInError;
break;
}
}
}
return NewStringLiteralToken(GetStringAndRelease(sb), TokenKind.HereStringLiteral, flags);
}
private Token ScanHereStringExpandable()
{
// On entry, we've see @'. Remember the position in case we reach the end of file and want
// to use this position as the error position.
int headerOffset = _currentIndex - 2;
if (!ScanAfterHereStringHeader("@\""))
{
return NewStringExpandableToken(string.Empty, string.Empty, TokenKind.HereStringExpandable, null, TokenFlags.TokenInError);
}
TokenFlags flags = TokenFlags.None;
List<Token> nestedTokens = new List<Token>();
int falseFooterOffset = -1;
var sb = GetStringBuilder();
var formatSb = GetStringBuilder();
Action<char> appendChar = c => { sb.Append(c); formatSb.Append(c); };
if (!ScanPossibleHereStringFooter(CharExtensions.IsDoubleQuote, appendChar, ref falseFooterOffset))
{
while (true)
{
char c = GetChar();
if (c == '\r' || c == '\n')
{
// Remember the length, we may remove this newline (which is 1 or 2 characters).
int length = sb.Length;
int formatLength = formatSb.Length;
sb.Append(c);
formatSb.Append(c);
if (c == '\r' && PeekChar() == '\n')
{
SkipChar();
sb.Append('\n');
formatSb.Append('\n');
}
if (ScanPossibleHereStringFooter(CharExtensions.IsDoubleQuote, appendChar, ref falseFooterOffset))
{
// Remove the last newline appended.
sb.Length = length;
formatSb.Length = formatLength;
break;
}
continue;
}
if (c == '$')
{
if (ScanDollarInStringExpandable(sb, formatSb, true, nestedTokens))
{
continue;
}
}
else if (c == '`')
{
// If end of input, go ahead and append the backtick and issue an error later
char c1 = PeekChar();
if (c1 != 0)
{
SkipChar();
c = Backtick(c1, out char surrogateCharacter);
if (surrogateCharacter != s_invalidChar)
{
sb.Append(c).Append(surrogateCharacter);
formatSb.Append(c).Append(surrogateCharacter);
continue;
}
}
}
if (c == '{' || c == '}')
{
// In the format string, we need to double up the curlies because we're
// replacing variable references and sub-expressions with the appropriate
// format expression for string.Format.
formatSb.Append(c);
}
if (c != '\0' || !AtEof())
{
sb.Append(c);
formatSb.Append(c);
}
else
{
UngetChar();
if (falseFooterOffset != -1)
{
ReportIncompleteInput(falseFooterOffset,
nameof(ParserStrings.WhitespaceBeforeHereStringFooter),
ParserStrings.WhitespaceBeforeHereStringFooter);
}
else
{
ReportIncompleteInput(headerOffset,
nameof(ParserStrings.TerminatorExpectedAtEndOfString),
ParserStrings.TerminatorExpectedAtEndOfString,
"\"@");
}
flags = TokenFlags.TokenInError;
break;
}
}
}
return NewStringExpandableToken(GetStringAndRelease(sb), GetStringAndRelease(formatSb), TokenKind.HereStringExpandable, nestedTokens, flags);
}
#endregion Strings
#region Variables
// Scan a variable - the first character ($ or @) has been consumed already.
private Token ScanVariable(bool splatted, bool inStringExpandable)
{
int errorStartPosition = _currentIndex;
var sb = GetStringBuilder();
char c = GetChar();
VariablePath path;
if (c == '{')
{
// Braced variable
Diagnostics.Assert(!splatted, "Splatting is not supported with braced variables.");
while (true)
{
c = GetChar();
switch (c)
{
case '}':
goto end_braced_variable_scan;
case '`':
{
char c1 = GetChar();
if (c1 == '\0' && AtEof())
{
UngetChar();
goto end_braced_variable_scan;
}
c = Backtick(c1, out char surrogateCharacter);
if (surrogateCharacter != s_invalidChar)
{
sb.Append(c).Append(surrogateCharacter);
continue;
}
break;
}
case '"':
case SpecialChars.QuoteDoubleLeft:
case SpecialChars.QuoteDoubleRight:
case SpecialChars.QuoteLowDoubleLeft:
if (inStringExpandable)
{
char c1 = GetChar();
if (c1 == '\0' && AtEof())
{
UngetChar();
goto end_braced_variable_scan;
}
if (c1.IsDoubleQuote())
{
c = c1;
}
else
{
UngetChar();
}
}
break;
case '{':
ReportError(_currentIndex,
nameof(ParserStrings.OpenBraceNeedsToBeBackTickedInVariableName),
ParserStrings.OpenBraceNeedsToBeBackTickedInVariableName);
break;
case '\0':
if (AtEof())
{
UngetChar();
goto end_braced_variable_scan;
}
break;
}
sb.Append(c);
}
end_braced_variable_scan:
string name = GetStringAndRelease(sb);
if (c != '}')
{
ReportIncompleteInput(errorStartPosition,
nameof(ParserStrings.IncompleteDollarVariableReference),
ParserStrings.IncompleteDollarVariableReference);
}
if (name.Length == 0)
{
if (c == '}')
{
ReportError(_currentIndex - 1,
nameof(ParserStrings.EmptyVariableReference),
ParserStrings.EmptyVariableReference);
}
name = ":Error:";
}
if (InCommandMode())
{
char c1 = PeekChar();
// A '.' or '[' after the variable name in command mode is an operator, not part of the current token.
if (!c1.ForceStartNewToken() && c1 != '.' && c1 != '[')
{
// The simple way to get this variable included in the nested tokens is to just start
// scanning all over again, but from the context of scanning a generic token.
_currentIndex = _tokenStart;
return ScanGenericToken(GetStringBuilder());
}
}
path = new VariablePath(name);
if (string.IsNullOrEmpty(path.UnqualifiedPath))
{
// Enable if we decide we still need to support
// "${}" or "$var:"
// if (inStringExpandable)
// {
// return NewToken(TokenKind.Unknown);
// }
ReportError(NewScriptExtent(_tokenStart, _currentIndex),
nameof(ParserStrings.InvalidBracedVariableReference),
ParserStrings.InvalidBracedVariableReference);
}
return NewVariableToken(path, false);
}
if (!c.IsVariableStart())
{
UngetChar();
sb.Append('$');
return ScanGenericToken(sb);
}
// Normal variable, not braced.
sb.Append(c);
// $$, $?, and $^ can only be single character variables. Otherwise keep scanning.
if (!(c == '$' || c == '?' || c == '^'))
{
bool scanning = true;
while (scanning)
{
c = GetChar();
switch (c)
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '_':
case '?':
sb.Append(c);
break;
case ':':
if (PeekChar() == ':')
{
// Something like $a::b is static member access
UngetChar();
scanning = false;
}
else
{
sb.Append(c);
}
break;
case '\0':
case '\t':
case '\r':
case '\n':
case ' ':
case '&':
case '(':
case ')':
case ',':
case ';':
case '{':
case '}':
case '|':
// The above cases would also be handled correctly below in the default case,
// but we can avoid extra checks on some of these characters which commonly
// occur after a variable.
case '.':
case '[':
// Something like $a.b or $a[1].
case '=':
// Something like $a=
UngetChar();
scanning = false;
break;
default:
if (char.IsLetterOrDigit(c))
{
sb.Append(c);
}
else if (InCommandMode() && !c.ForceStartNewToken())
{
_currentIndex = _tokenStart;
sb.Clear();
return ScanGenericToken(sb);
}
else
{
UngetChar();
scanning = false;
}
break;
}
}
}
else if (InCommandMode() && !PeekChar().ForceStartNewToken())
{
_currentIndex = _tokenStart;
sb.Clear();
return ScanGenericToken(sb);
}
path = new VariablePath(GetStringAndRelease(sb));
if (string.IsNullOrEmpty(path.UnqualifiedPath))
{
string errorId;
string errorMsg;
if (path.IsDriveQualified)
{
errorId = nameof(ParserStrings.InvalidVariableReferenceWithDrive);
errorMsg = ParserStrings.InvalidVariableReferenceWithDrive;
}
else
{
errorId = nameof(ParserStrings.InvalidVariableReference);
errorMsg = ParserStrings.InvalidVariableReference;
}
ReportError(NewScriptExtent(_tokenStart, _currentIndex), errorId, errorMsg);
}
return NewVariableToken(path, splatted);
}
#endregion Variables
// Scan either a parameter or an operator, in either case it must start with a dash.
private Token ScanParameter()
{
var sb = GetStringBuilder();
bool scanning = true;
bool sawColonAtEnd = false;
while (scanning)
{
char c = GetChar();
if (c.IsWhitespace())
{
UngetChar();
break;
}
switch (c)
{
case '{':
case '}':
case '(':
case ')':
case ';':
case ',':
case '|':
case '&':
case '.':
case '[':
case '\r':
case '\n':
case '\0':
UngetChar();
scanning = false;
break;
case ':':
scanning = false;
sawColonAtEnd = true;
if (!InCommandMode())
{
UngetChar();
}
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
sb.Append(c);
break;
case '\'':
case SpecialChars.QuoteSingleLeft:
case SpecialChars.QuoteSingleRight:
case SpecialChars.QuoteSingleBase:
case SpecialChars.QuoteReversed:
case '"':
case SpecialChars.QuoteDoubleLeft:
case SpecialChars.QuoteDoubleRight:
case SpecialChars.QuoteLowDoubleLeft:
if (InCommandMode())
{
// Quotes are never part of a parameter. Treat the token as an argument.
UngetChar();
sb.Insert(0, _script[_tokenStart]); // Insert the '-' that we skipped.
return ScanGenericToken(sb);
}
UngetChar();
scanning = false;
break;
default:
if (InCommandMode())
{
sb.Append(c);
}
else
{
UngetChar();
scanning = false;
}
break;
}
}
var str = GetStringAndRelease(sb);
if (InExpressionMode())
{
TokenKind operatorKind;
if (s_operatorTable.TryGetValue(str, out operatorKind))
{
return NewToken(operatorKind);
}
}
if (str.Length == 0)
{
return NewToken(TokenKind.Minus);
}
return NewParameterToken(str, sawColonAtEnd);
}
private Token CheckOperatorInCommandMode(char c, TokenKind tokenKind)
{
if (InCommandMode() && !PeekChar().ForceStartNewToken())
{
return ScanGenericToken(c);
}
return NewToken(tokenKind);
}
private Token CheckOperatorInCommandMode(char c1, char c2, TokenKind tokenKind)
{
if (InCommandMode() && !PeekChar().ForceStartNewToken())
{
var sb = GetStringBuilder();
sb.Append(c1);
sb.Append(c2);
return ScanGenericToken(sb);
}
return NewToken(tokenKind);
}
private Token ScanGenericToken(char firstChar)
{
var sb = GetStringBuilder();
sb.Append(firstChar);
return ScanGenericToken(sb);
}
private Token ScanGenericToken(char firstChar, char surrogateCharacter)
{
var sb = GetStringBuilder();
sb.Append(firstChar);
if (surrogateCharacter != s_invalidChar)
{
sb.Append(surrogateCharacter);
}
return ScanGenericToken(sb);
}
private Token ScanGenericToken(StringBuilder sb)
{
// On entry, we've already scanned an unknown number of characters
// and found a character that didn't end the token, but made the
// token something other than what we thought it was. Examples:
// 77z <= it looks like a number, but the 'z' makes it an argument
// $+ <= it looks like a variable, but the '+' makes it an argument
//
// A generic token is typically either command name or command argument
// (though a generic token is accepted in other places, such as a hash key
// or function name.)
//
// A generic token can be taken literally or treated as an expandable
// string, depending on the context. A command argument would treat
// a generic token as an expandable string whereas a command name would
// not.
//
// We optimize for the command argument case - if we find anything expandable,
// we continue processing assuming the string is expandable, so we'll tokenize
// sub-expressions and variable names. This would be considered extra work
// if the token was a command name, so we assume that will happen rarely, and
// indeed, '$' is not commonly used in command names.
// Make sure our token does not start with any of these characters.
// Contract.Requires(Contract.ForAll("{}()@#;,|&\r\n\t ", c1 => sb[0] != c1));
List<Token> nestedTokens = new List<Token>();
var formatSb = GetStringBuilder();
formatSb.Append(sb);
char c = GetChar();
for (; !c.ForceStartNewToken(); c = GetChar())
{
if (c == '`')
{
// If end of input, we'll just append the backtick - there should be no error.
char c1 = PeekChar();
if (c1 != 0)
{
SkipChar();
c = Backtick(c1, out char surrogateCharacter);
if (surrogateCharacter != s_invalidChar)
{
sb.Append(c).Append(surrogateCharacter);
formatSb.Append(c).Append(surrogateCharacter);
continue;
}
}
}
else if (c.IsSingleQuote())
{
int len = sb.Length;
ScanStringLiteral(sb);
for (int i = len; i < sb.Length; ++i)
{
formatSb.Append(sb[i]);
}
continue;
}
else if (c.IsDoubleQuote())
{
ScanStringExpandable(sb, formatSb, nestedTokens);
continue;
}
else if (c == '$')
{
if (ScanDollarInStringExpandable(sb, formatSb, false, nestedTokens))
{
continue;
}
}
sb.Append(c);
formatSb.Append(c);
if (c == '{' || c == '}')
{
formatSb.Append(c);
}
}
UngetChar();
var str = GetStringAndRelease(sb);
if (nestedTokens.Count > 0)
{
return NewGenericExpandableToken(str, GetStringAndRelease(formatSb), nestedTokens);
}
Release(formatSb);
if (DynamicKeyword.ContainsKeyword(str) && !DynamicKeyword.IsHiddenKeyword(str))
{
return NewToken(TokenKind.DynamicKeyword);
}
return NewGenericToken(str);
}
#region Numbers
private void ScanHexDigits(StringBuilder sb)
{
char c = PeekChar();
while (c.IsHexDigit())
{
SkipChar();
sb.Append(c);
c = PeekChar();
}
}
private int ScanDecimalDigits(StringBuilder sb)
{
int countDigits = 0;
char c = PeekChar();
while (c.IsDecimalDigit())
{
countDigits += 1;
SkipChar();
sb.Append(c);
c = PeekChar();
}
return countDigits;
}
private void ScanBinaryDigits(StringBuilder sb)
{
char c = PeekChar();
while (c.IsBinaryDigit())
{
SkipChar();
sb.Append(c);
c = PeekChar();
}
}
private void ScanExponent(StringBuilder sb, ref int signIndex, ref bool notNumber)
{
char c = PeekChar();
if (c == '+' || c.IsDash())
{
SkipChar();
// Append the sign - but remember where it was appended. If we really
// do have a number, we'll replace en-dash/em-dash/horizontal-bar with dash,
// but if it's a generic token, we don't want to do the replacement.
signIndex = sb.Length;
sb.Append(c);
}
if (ScanDecimalDigits(sb) == 0)
{
notNumber = true;
}
}
private void ScanNumberAfterDot(StringBuilder sb, ref int signIndex, ref bool notNumber)
{
ScanDecimalDigits(sb);
// No need to verify we saw a digit here.
// 1.e1 is valid
// .e1 is not, but ScanDot ensures the next character is a digit
char c = PeekChar();
if (c == 'e' || c == 'E')
{
SkipChar();
sb.Append(c);
ScanExponent(sb, ref signIndex, ref notNumber);
}
}
private static bool TryGetNumberValue(
ReadOnlySpan<char> strNum,
NumberFormat format,
NumberSuffixFlags suffix,
bool real,
long multiplier,
out object result)
{
checked
{
try
{
NumberStyles style = NumberStyles.AllowLeadingSign
| NumberStyles.AllowDecimalPoint
| NumberStyles.AllowExponent;
if (real)
{
// Decimal parser does not accept hex literals, and 'd' is a valid hex character, so will
// never be read as Decimal literal
// e.g., 0x1d == 29
if (suffix == NumberSuffixFlags.Decimal)
{
if (decimal.TryParse(strNum, style, NumberFormatInfo.InvariantInfo, out decimal d))
{
result = d * multiplier;
return true;
}
result = null;
return false;
}
if (double.TryParse(strNum, style, NumberFormatInfo.InvariantInfo, out double doubleValue))
{
// TryParse incorrectly return +0 when the result should be -0, so check for that case
if (doubleValue == 0.0 && strNum[0] == '-')
{
doubleValue = -0.0;
}
doubleValue *= multiplier;
switch (suffix)
{
case NumberSuffixFlags.None:
result = doubleValue;
return true;
case NumberSuffixFlags.SignedByte:
if (Utils.TryCast(doubleValue.AsBigInt(), out sbyte sb))
{
result = sb;
return true;
}
break;
case NumberSuffixFlags.UnsignedByte:
if (Utils.TryCast(doubleValue.AsBigInt(), out byte b))
{
result = b;
return true;
}
break;
case NumberSuffixFlags.Short:
if (Utils.TryCast(doubleValue.AsBigInt(), out short s))
{
result = s;
return true;
}
break;
case NumberSuffixFlags.Long:
if (Utils.TryCast(doubleValue.AsBigInt(), out long l))
{
result = l;
return true;
}
break;
case NumberSuffixFlags.UnsignedShort:
if (Utils.TryCast(doubleValue.AsBigInt(), out ushort us))
{
result = us;
return true;
}
break;
case NumberSuffixFlags.Unsigned:
BigInteger testValue = doubleValue.AsBigInt();
if (Utils.TryCast(testValue, out uint u))
{
result = u;
return true;
}
else if (Utils.TryCast(testValue, out ulong ul))
{
result = ul;
return true;
}
break;
case NumberSuffixFlags.UnsignedLong:
if (Utils.TryCast(doubleValue.AsBigInt(), out ulong ulValue))
{
result = ulValue;
return true;
}
break;
case NumberSuffixFlags.BigInteger:
result = doubleValue.AsBigInt();
return true;
}
// Invalid NumberSuffixFlags combination, or outside bounds of specified type.
result = null;
return false;
}
// TryParse for real numeric literal failed
result = null;
return false;
}
BigInteger bigValue;
switch (format)
{
case NumberFormat.Hex:
if (!strNum[0].IsHexDigit())
{
if (strNum[0] == '-')
{
multiplier = -multiplier;
}
// Remove leading char (expected: - or +)
strNum = strNum.Slice(1);
}
// If we're expecting a sign bit, remove the leading 0 added in ScanNumberHelper
if (!suffix.HasFlag(NumberSuffixFlags.Unsigned))
{
var expectedLength = suffix switch
{
NumberSuffixFlags.SignedByte => 2,
NumberSuffixFlags.Short => 4,
NumberSuffixFlags.Long => 16,
// No suffix flag can mean int or long depending on input string length
_ => strNum.Length < 16 ? 8 : 16
};
if (strNum.Length == expectedLength + 1)
{
strNum = strNum.Slice(1);
}
}
style = NumberStyles.AllowHexSpecifier;
if (!BigInteger.TryParse(strNum, style, NumberFormatInfo.InvariantInfo, out bigValue))
{
result = null;
return false;
}
// If we have a hex literal denoting (u)int64, treat it as such, even if the value is low
if (strNum.Length == 16 && (suffix == NumberSuffixFlags.None || suffix == NumberSuffixFlags.Unsigned))
{
suffix |= NumberSuffixFlags.Long;
}
break;
case NumberFormat.Binary:
if (!strNum[0].IsBinaryDigit())
{
if (strNum[0] == '-')
{
multiplier = -multiplier;
}
// Remove leading char (expected: - or +)
strNum = strNum.Slice(1);
}
bigValue = Utils.ParseBinary(strNum, suffix.HasFlag(NumberSuffixFlags.Unsigned));
// If we have a binary literal denoting (u)int64, treat it as such
if (strNum.Length == 64 && (suffix == NumberSuffixFlags.None || suffix == NumberSuffixFlags.Unsigned))
{
suffix |= NumberSuffixFlags.Long;
}
break;
default:
style = NumberStyles.AllowLeadingSign;
if (!BigInteger.TryParse(strNum, style, NumberFormatInfo.InvariantInfo, out bigValue))
{
result = null;
return false;
}
break;
}
// Apply multiplier before attempting casting to prevent overflow
bigValue *= multiplier;
switch (suffix)
{
case NumberSuffixFlags.SignedByte:
if (Utils.TryCast(bigValue, out sbyte sb))
{
result = sb;
return true;
}
break;
case NumberSuffixFlags.UnsignedByte:
if (Utils.TryCast(bigValue, out byte b))
{
result = b;
return true;
}
break;
case NumberSuffixFlags.Short:
if (Utils.TryCast(bigValue, out short s))
{
result = s;
return true;
}
break;
case NumberSuffixFlags.Long:
if (Utils.TryCast(bigValue, out long l))
{
result = l;
return true;
}
break;
case NumberSuffixFlags.UnsignedShort:
if (Utils.TryCast(bigValue, out ushort us))
{
result = us;
return true;
}
break;
case NumberSuffixFlags.Unsigned:
if (Utils.TryCast(bigValue, out uint u))
{
result = u;
return true;
}
else if (Utils.TryCast(bigValue, out ulong ul))
{
result = ul;
return true;
}
break;
case NumberSuffixFlags.UnsignedLong:
if (Utils.TryCast(bigValue, out ulong ulValue))
{
result = ulValue;
return true;
}
break;
case NumberSuffixFlags.Decimal:
if (Utils.TryCast(bigValue, out decimal dm))
{
result = dm;
return true;
}
break;
case NumberSuffixFlags.BigInteger:
result = bigValue;
return true;
case NumberSuffixFlags.None:
// Type not specified; fit value into narrowest signed type available, int32 minimum
if (Utils.TryCast(bigValue, out int i))
{
result = i;
return true;
}
if (Utils.TryCast(bigValue, out long lValue))
{
result = lValue;
return true;
}
// Result is too big for anything else; fallback to decimal or double
if (format == NumberFormat.Decimal)
{
if (Utils.TryCast(bigValue, out decimal dmValue))
{
result = dmValue;
return true;
}
if (Utils.TryCast(bigValue, out double d))
{
result = d;
return true;
}
}
// Hex or Binary value, too big for generic non-suffixed parsing
result = null;
return false;
}
// Value cannot be contained in type specified by suffix, or invalid suffix flags.
result = null;
return false;
}
catch (Exception)
{
}
}
result = null;
return false;
}
private Token ScanNumber(char firstChar)
{
Diagnostics.Assert(
firstChar == '.' || (firstChar >= '0' && firstChar <= '9')
|| (AllowSignedNumbers && (firstChar == '+' || firstChar.IsDash())), "Number must start with '.', '-', or digit.");
string strNum = ScanNumberHelper(firstChar, out NumberFormat format, out NumberSuffixFlags suffix, out bool real, out long multiplier);
// the token is not a number. i.e. 77z.exe
if (strNum == null)
{
// Rescan the characters, this is simpler than keeping track of the suffix, multiplier, and 0x prefix.
_currentIndex = _tokenStart;
return ScanGenericToken(GetStringBuilder());
}
object value;
if (!TryGetNumberValue(strNum, format, suffix, real, multiplier, out value))
{
if (!InExpressionMode())
{
// Rescan the characters, this is simpler than keeping track of the dashes and the hex prefix.
_currentIndex = _tokenStart;
return ScanGenericToken(GetStringBuilder());
}
ReportError(
NewScriptExtent(_tokenStart, _currentIndex),
nameof(ParserStrings.BadNumericConstant),
ParserStrings.BadNumericConstant,
_script.Substring(_tokenStart, _currentIndex - _tokenStart));
}
return NewNumberToken(value);
}
/// <summary>
/// Scans a numeric string to determine its characteristics.
/// </summary>
/// <param name="firstChar">The first character.</param>
/// <param name="format">Indicate if it's a hex, binary, or decimal number.</param>
/// <param name="suffix">Indicate the format suffix.</param>
/// <param name="real">Indicate if the number is real (non-integer).</param>
/// <param name="multiplier">Indicate the specified multiplier.</param>
/// <returns>
/// Return null if the token is not a number
/// OR
/// Return the string format of the number.
/// </returns>
private string ScanNumberHelper(char firstChar, out NumberFormat format, out NumberSuffixFlags suffix, out bool real, out long multiplier)
{
format = NumberFormat.Decimal;
suffix = NumberSuffixFlags.None;
real = false;
multiplier = 1;
bool notNumber = false;
int signIndex = -1;
char c;
var sb = GetStringBuilder();
if (firstChar.IsDash() || firstChar == '+')
{
sb.Append(firstChar);
firstChar = GetChar();
}
if (firstChar == '.')
{
sb.Append('.');
ScanNumberAfterDot(sb, ref signIndex, ref notNumber);
real = true;
}
else
{
c = PeekChar();
bool isHexOrBinary = firstChar == '0' && (c == 'x' || c == 'X' || c == 'b' || c == 'B');
if (isHexOrBinary)
{
SkipChar();
switch (c)
{
case 'x':
case 'X':
sb.Append('0'); // Prepend a 0 to the number before any numeric digits are added
ScanHexDigits(sb);
if (sb.Length == 0)
{
notNumber = true;
}
format = NumberFormat.Hex;
break;
case 'b':
case 'B':
ScanBinaryDigits(sb);
if (sb.Length == 0)
{
notNumber = true;
}
format = NumberFormat.Binary;
break;
}
}
else
{
sb.Append(firstChar);
ScanDecimalDigits(sb);
c = PeekChar();
switch (c)
{
case '.':
SkipChar();
if (PeekChar() == '.')
{
// We just found the range operator, so unget the first dot so
// we can stop scanning as a number.
UngetChar();
}
else
{
sb.Append(c);
real = true;
ScanNumberAfterDot(sb, ref signIndex, ref notNumber);
}
break;
case 'E':
case 'e':
SkipChar();
sb.Append(c);
real = true;
ScanExponent(sb, ref signIndex, ref notNumber);
break;
}
}
}
c = PeekChar();
if (c.IsTypeSuffix())
{
SkipChar();
switch (c)
{
case 'u':
case 'U':
suffix |= NumberSuffixFlags.Unsigned;
break;
case 's':
case 'S':
suffix |= NumberSuffixFlags.Short;
break;
case 'l':
case 'L':
suffix |= NumberSuffixFlags.Long;
break;
case 'd':
case 'D':
suffix |= NumberSuffixFlags.Decimal;
break;
case 'y':
case 'Y':
suffix |= NumberSuffixFlags.SignedByte;
break;
case 'n':
case 'N':
suffix |= NumberSuffixFlags.BigInteger;
break;
default:
notNumber = true;
break;
}
c = PeekChar();
if (c.IsTypeSuffix())
{
SkipChar();
switch (suffix)
{
case NumberSuffixFlags.Unsigned:
switch (c)
{
case 'l':
case 'L':
suffix |= NumberSuffixFlags.Long;
break;
case 's':
case 'S':
suffix |= NumberSuffixFlags.Short;
break;
case 'y':
case 'Y':
suffix |= NumberSuffixFlags.SignedByte;
break;
default:
notNumber = true;
break;
}
break;
default:
notNumber = true;
break;
}
c = PeekChar();
}
}
if (c.IsMultiplierStart())
{
SkipChar();
switch (c)
{
case 'k':
case 'K':
multiplier = 1024;
break;
case 'm':
case 'M':
multiplier = 1024 * 1024;
break;
case 'g':
case 'G':
multiplier = 1024 * 1024 * 1024;
break;
case 't':
case 'T':
multiplier = 1024L * 1024 * 1024 * 1024;
break;
case 'p':
case 'P':
multiplier = 1024L * 1024 * 1024 * 1024 * 1024;
break;
}
char c1 = PeekChar();
if (c1 == 'b' || c1 == 'B')
{
SkipChar();
c = PeekChar();
}
else
{
notNumber = true;
}
}
if (!c.ForceStartNewToken())
{
if (!InExpressionMode() || !c.ForceStartNewTokenAfterNumber(ForceEndNumberOnTernaryOpChars))
{
notNumber = true;
}
}
if (notNumber)
{
Release(sb);
return null;
}
// TryParse won't accept odd dashes for a sign, so replace them.
if (signIndex != -1 && sb[signIndex] != '-' && sb[signIndex].IsDash())
{
sb[signIndex] = '-';
}
if (sb[0] != '-' && sb[0].IsDash())
{
sb[0] = '-';
}
return GetStringAndRelease(sb);
}
#endregion Numbers
internal Token GetMemberAccessOperator(bool allowLBracket)
{
// No skipping whitespace here - whitespace isn't allowed before member access operators.
// We do skip multi-line comments though, they are allowed (mostly for backwards compatibility.)
char c = PeekChar();
while (c == '<')
{
_tokenStart = _currentIndex;
SkipChar();
if (PeekChar() == '#')
{
SkipChar();
ScanBlockComment();
c = PeekChar();
}
else
{
UngetChar();
return null;
}
}
if (c == '.')
{
_tokenStart = _currentIndex;
SkipChar();
c = PeekChar();
if (c != '.')
{
if (InCommandMode() && (c.IsWhitespace() || c == '\0' || c == '\r' || c == '\n'))
{
UngetChar();
return null;
}
return NewToken(TokenKind.Dot);
}
UngetChar();
return null;
}
if (c == ':')
{
_tokenStart = _currentIndex;
SkipChar();
c = PeekChar();
if (c == ':')
{
SkipChar();
c = PeekChar();
if (InCommandMode() && (c.IsWhitespace() || c == '\0' || c == '\r' || c == '\n'))
{
UngetChar();
UngetChar();
return null;
}
return NewToken(TokenKind.ColonColon);
}
UngetChar();
return null;
}
if (c == '[' && allowLBracket)
{
_tokenStart = _currentIndex;
SkipChar();
return NewToken(TokenKind.LBracket);
}
if (c == '?')
{
_tokenStart = _currentIndex;
SkipChar();
c = PeekChar();
if (c == '.')
{
SkipChar();
return NewToken(TokenKind.QuestionDot);
}
else if (c == '[' && allowLBracket)
{
SkipChar();
return NewToken(TokenKind.QuestionLBracket);
}
UngetChar();
return null;
}
return null;
}
internal Token GetInvokeMemberOpenParen()
{
// No skipping whitespace here - whitespace isn't allowed before the open paren of a function invocation.
var c = PeekChar();
if (c == '(')
{
_tokenStart = _currentIndex;
SkipChar();
return NewToken(TokenKind.LParen);
}
if (c == '{')
{
_tokenStart = _currentIndex;
SkipChar();
return NewToken(TokenKind.LCurly);
}
return null;
}
internal Token GetLBracket()
{
// We know we want a '[' token or no token. We are in a context where we expect an attribute/type constraint
// and allow any whitespace/comments before the '[', but nothing else (the caller has already skipped newlines
// if appropriate.) This is handled specially because in command mode, a generic token may begin with '[', but
// we don't want anything more than the '['.
// Remember where we started. In some rare cases, we may need to sync back to make things a little
// simpler in the parser.
int resyncPoint = _currentIndex;
bool resyncIfMemberAccess = false;
again:
_tokenStart = _currentIndex;
char c = GetChar();
switch (c)
{
case ' ':
case '\t':
case '\f':
case '\v':
case SpecialChars.NoBreakSpace:
case SpecialChars.NextLine:
resyncIfMemberAccess = true;
SkipWhiteSpace();
goto again;
case '#':
resyncIfMemberAccess = true;
ScanLineComment();
goto again;
case '<':
if (PeekChar() == '#')
{
// We resync if we find any whitespace, but only if the whitespace occurs after a
// multi-line comment (rationale: backwards compatibility.)
resyncIfMemberAccess = false;
SkipChar();
ScanBlockComment();
goto again;
}
UngetChar();
break;
case '[':
return NewToken(TokenKind.LBracket);
case '.':
case ':':
// We don't call resync here unless we might have a member access token, in which case
// we want to rescan the comments to ensure there is no whitespace between the expression
// and the member access token. The resync here should rarely do much other than move
// the _currentIndex because there will rarely be any comment tokens after the closing ']'
// in an attribute and the member access token.
if (resyncIfMemberAccess)
{
Resync(resyncPoint);
}
else
{
UngetChar();
}
break;
default:
if (c.IsWhitespace())
{
resyncIfMemberAccess = true;
SkipWhiteSpace();
goto again;
}
UngetChar();
break;
}
return null;
}
private Token ScanDot()
{
char c = PeekChar();
if (c == '.')
{
SkipChar();
c = PeekChar();
if (InCommandMode() && !c.ForceStartNewToken())
{
UngetChar(); // Unget the second dot, let ScanGenericToken consume it.
return ScanGenericToken('.');
}
return NewToken(TokenKind.DotDot);
}
if (c.IsDecimalDigit())
{
return ScanNumber('.');
}
// The following are all dotting commands, not a command starting with dot:
// .$command
// ."command with spaces"
// .'command with spaces'
if (InCommandMode() && !c.ForceStartNewToken() && c != '$' && c != '"' && c != '\'')
{
return ScanGenericToken('.');
}
return NewToken(TokenKind.Dot);
}
// The first character is an ascii letter. We could be scanning a keyword,
// a command name or argument, or a method or property name.
private Token ScanIdentifier(char firstChar)
{
var sb = GetStringBuilder();
char c;
sb.Append(firstChar);
while (true)
{
c = GetChar();
if (c.IsIdentifierFollow())
{
sb.Append(c);
}
else
{
UngetChar();
break;
}
}
// In typename mode, we want, well, typenames.
if (InTypeNameMode())
{
Release(sb);
return ScanTypeName();
}
// In expression mode, we only want simple identifiers so we're done,
// but in command mode, we keep scanning if the current character
// doesn't terminate the token.
if (!WantSimpleName && InCommandMode() && !c.ForceStartNewToken())
{
return ScanGenericToken(sb);
}
if (!WantSimpleName && (InCommandMode() || InSignatureMode()))
{
TokenKind tokenKind;
var ident = GetStringAndRelease(sb);
sb = null;
if (s_keywordTable.TryGetValue(ident, out tokenKind))
{
if (tokenKind != TokenKind.InlineScript || InWorkflowContext)
return NewToken(tokenKind);
}
if (DynamicKeyword.ContainsKeyword(ident) && !DynamicKeyword.IsHiddenKeyword(ident))
{
return NewToken(TokenKind.DynamicKeyword);
}
}
if (sb != null)
Release(sb);
return NewToken(TokenKind.Identifier);
}
#region Type Names
private Token ScanTypeName()
{
while (true)
{
char c = GetChar();
switch (c)
{
case '.':
case '`':
case '_':
case '+':
case '#':
case '\\':
continue;
default:
if (char.IsLetterOrDigit(c))
{
continue;
}
break;
}
UngetChar();
break;
}
var result = NewToken(TokenKind.Identifier);
result.TokenFlags |= TokenFlags.TypeName;
return result;
}
private void ScanAssemblyNameSpecToken(StringBuilder sb)
{
// Whitespace, ',', '=', ']', and newlines terminate a token.
SkipWhiteSpace();
_tokenStart = _currentIndex;
while (true)
{
char c = GetChar();
if (c.ForceStartNewTokenInAssemblyNameSpec())
{
UngetChar();
break;
}
sb.Append(c);
}
var token = NewToken(TokenKind.Identifier);
token.TokenFlags |= TokenFlags.TypeName;
SkipWhiteSpace();
}
internal string GetAssemblyNameSpec()
{
// G assembly-name-spec:
// G assembly-name
// G assembly-name ',' assembly-properties
// G assembly-name:
// G assembly-token
// G assembly-properties:
// G assembly-property
// G assembly-properties ',' assembly-property
// G assembly-property:
// G assembly-property-name '=' assembly-property-value
// G assembly-property-name: one of
// G 'Version'
// G 'PublicKey'
// G 'PublicKeyToken'
// G 'Culture'
// G 'Custom'
// G assembly-property:
// G assembly-token
// G assembly-token:
// G any sequence of characters not ending in whitespace, newlines, ',', '=', or ']'.
// The above grammar is specified by the CLR (except assembly-token). We defer validation to the CLR, but
// use the above grammar to collect the name of the assembly.
var sb = GetStringBuilder();
// Assembly name first, followed by optional properties.
ScanAssemblyNameSpecToken(sb);
while (PeekChar() == ',')
{
_tokenStart = _currentIndex;
sb.Append(", ");
SkipChar();
NewToken(TokenKind.Comma);
ScanAssemblyNameSpecToken(sb);
if (PeekChar() == '=')
{
_tokenStart = _currentIndex;
sb.Append('=');
SkipChar();
NewToken(TokenKind.Equals);
ScanAssemblyNameSpecToken(sb);
}
// else error?
}
return GetStringAndRelease(sb);
}
#endregion Type Names
private Token ScanLabel()
{
var sb = GetStringBuilder();
char c = GetChar();
if (!c.IsIdentifierStart())
{
// Must be a generic token then
sb.Append(':');
if (c == '\0')
{
UngetChar();
return NewGenericToken(GetStringAndRelease(sb));
}
UngetChar();
return ScanGenericToken(sb);
}
while (c.IsIdentifierFollow())
{
sb.Append(c);
c = GetChar();
}
// In command mode, we keep scanning if the current character
// doesn't terminate the token.
if (InCommandMode() && !c.ForceStartNewToken())
{
sb.Insert(0, ':');
sb.Append(c);
return ScanGenericToken(sb);
}
UngetChar();
return NewLabelToken(GetStringAndRelease(sb));
}
internal Token NextToken()
{
char c1;
again:
_tokenStart = _currentIndex;
char c = GetChar();
switch (c)
{
case ' ':
case '\t':
case '\f':
case '\v':
case SpecialChars.NoBreakSpace:
case SpecialChars.NextLine:
SkipWhiteSpace();
goto again;
case '\'':
case SpecialChars.QuoteSingleLeft:
case SpecialChars.QuoteSingleRight:
case SpecialChars.QuoteSingleBase:
case SpecialChars.QuoteReversed:
return ScanStringLiteral();
case '"':
case SpecialChars.QuoteDoubleLeft:
case SpecialChars.QuoteDoubleRight:
case SpecialChars.QuoteLowDoubleLeft:
return ScanStringExpandable();
case '@':
// Could be start of hash literal, array operator, multi-line string, splatted variable
c1 = GetChar();
if (c1 == '{')
{
return NewToken(TokenKind.AtCurly);
}
if (c1 == '(')
{
return NewToken(TokenKind.AtParen);
}
if (c1.IsSingleQuote())
{
return ScanHereStringLiteral();
}
if (c1.IsDoubleQuote())
{
return ScanHereStringExpandable();
}
UngetChar();
if (c1.IsVariableStart())
{
return ScanVariable(true, false);
}
ReportError(_currentIndex - 1,
nameof(ParserStrings.UnrecognizedToken),
ParserStrings.UnrecognizedToken);
return NewToken(TokenKind.Unknown);
case '#':
ScanLineComment();
goto again;
case '\n':
return NewToken(TokenKind.NewLine);
case '\r':
NormalizeCRLF(c);
goto case '\n';
case '`':
c1 = GetChar();
if (c1 == '\r')
{
NormalizeCRLF(c1);
}
if (c1 == '\n' || c1 == '\r')
{
NewToken(TokenKind.LineContinuation);
goto again;
}
if (char.IsWhiteSpace(c1))
{
SkipWhiteSpace();
goto again;
}
if (c1 == '\0' && AtEof())
{
ReportIncompleteInput(_currentIndex,
nameof(ParserStrings.IncompleteString),
ParserStrings.IncompleteString);
// Unget the EOF so we can return an EOF token.
UngetChar();
goto again;
}
c = Backtick(c1, out char surrogateCharacter);
return ScanGenericToken(c, surrogateCharacter);
case '=':
return CheckOperatorInCommandMode(c, TokenKind.Equals);
case '+':
c1 = PeekChar();
if (c1 == '+')
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.PlusPlus);
}
if (c1 == '=')
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.PlusEquals);
}
if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.'))
{
return ScanNumber(c);
}
return CheckOperatorInCommandMode(c, TokenKind.Plus);
case '-':
case SpecialChars.EmDash:
case SpecialChars.EnDash:
case SpecialChars.HorizontalBar:
c1 = PeekChar();
if (c1.IsDash())
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.MinusMinus);
}
if (c1 == '=')
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.MinusEquals);
}
if (char.IsLetter(c1) || c1 == '_' || c1 == '?')
{
return ScanParameter();
}
if (AllowSignedNumbers && (char.IsDigit(c1) || c1 == '.'))
{
return ScanNumber(c);
}
return CheckOperatorInCommandMode(c, TokenKind.Minus);
case '*':
c1 = PeekChar();
if (c1 == '=')
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.MultiplyEquals);
}
if (c1 == '>')
{
SkipChar();
c1 = PeekChar();
if (c1 == '>')
{
SkipChar();
return NewFileRedirectionToken(0, append: true, fromSpecifiedExplicitly: false);
}
if (c1 == '&')
{
SkipChar();
c1 = PeekChar();
if (c1 == '1')
{
SkipChar();
return NewMergingRedirectionToken(0, 1);
}
UngetChar();
}
return NewFileRedirectionToken(0, append: false, fromSpecifiedExplicitly: false);
}
return CheckOperatorInCommandMode(c, TokenKind.Multiply);
case '/':
c1 = PeekChar();
if (c1 == '=')
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.DivideEquals);
}
return CheckOperatorInCommandMode(c, TokenKind.Divide);
case '%':
c1 = PeekChar();
if (c1 == '=')
{
SkipChar();
return CheckOperatorInCommandMode(c, c1, TokenKind.RemainderEquals);
}
return CheckOperatorInCommandMode(c, TokenKind.Rem);
case '$':
if (PeekChar() == '(')
{
SkipChar();
return NewToken(TokenKind.DollarParen);
}
return ScanVariable(false, false);
case '<':
if (PeekChar() == '#')
{
SkipChar();
ScanBlockComment();
goto again;
}
return NewInputRedirectionToken();
case '>':
if (PeekChar() == '>')
{
SkipChar();
return NewFileRedirectionToken(1, append: true, fromSpecifiedExplicitly: false);
}
return NewFileRedirectionToken(1, append: false, fromSpecifiedExplicitly: false);
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
return ScanIdentifier(c);
case '(':
return NewToken(TokenKind.LParen);
case ')':
return NewToken(TokenKind.RParen);
case '[':
if (InCommandMode() && !PeekChar().ForceStartNewToken())
{
return ScanGenericToken('[');
}
return NewToken(TokenKind.LBracket);
case ']':
return NewToken(TokenKind.RBracket);
case '{':
return NewToken(TokenKind.LCurly);
case '}':
return NewToken(TokenKind.RCurly);
case '.':
return ScanDot();
case ';':
return NewToken(TokenKind.Semi);
case ',':
return NewToken(TokenKind.Comma);
case '0':
case '7':
case '8':
case '9':
return ScanNumber(c);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
if (PeekChar() == '>')
{
SkipChar();
c1 = PeekChar();
if (c1 == '>')
{
SkipChar();
return NewFileRedirectionToken(c - '0', append: true, fromSpecifiedExplicitly: true);
}
if (c1 == '&')
{
SkipChar();
c1 = PeekChar();
if (c1 == '1' || c1 == '2')
{
SkipChar();
return NewMergingRedirectionToken(c - '0', c1 - '0');
}
UngetChar();
}
return NewFileRedirectionToken(c - '0', append: false, fromSpecifiedExplicitly: true);
}
return ScanNumber(c);
case '&':
if (PeekChar() == '&')
{
SkipChar();
return NewToken(TokenKind.AndAnd);
}
return NewToken(TokenKind.Ampersand);
case '|':
if (PeekChar() == '|')
{
SkipChar();
return NewToken(TokenKind.OrOr);
}
return NewToken(TokenKind.Pipe);
case '!':
c1 = PeekChar();
if ((InCommandMode() && !c1.ForceStartNewToken()) ||
(InExpressionMode() && c1.IsIdentifierStart()))
{
return ScanGenericToken(c);
}
if (InExpressionMode() && (char.IsDigit(c1) || c1 == '.'))
{
// check if the next token is actually a number
string strNum = ScanNumberHelper(c, out _, out _, out _, out _);
// rescan characters after the check
_currentIndex = _tokenStart;
c = GetChar();
if (strNum == null)
{
return ScanGenericToken(c);
}
}
return NewToken(TokenKind.Exclaim);
case ':':
if (PeekChar() == ':')
{
SkipChar();
if (InCommandMode() && !WantSimpleName && !PeekChar().ForceStartNewToken())
{
var sb = GetStringBuilder();
sb.Append("::");
return ScanGenericToken(sb);
}
return NewToken(TokenKind.ColonColon);
}
if (InCommandMode())
{
return ScanLabel();
}
return this.NewToken(TokenKind.Colon);
case '?' when InExpressionMode():
c1 = PeekChar();
if (c1 == '?')
{
SkipChar();
c1 = PeekChar();
if (c1 == '=')
{
SkipChar();
return this.NewToken(TokenKind.QuestionQuestionEquals);
}
return this.NewToken(TokenKind.QuestionQuestion);
}
return this.NewToken(TokenKind.QuestionMark);
case '\0':
if (AtEof())
{
return SaveToken(new Token(NewScriptExtent(_tokenStart + 1, _tokenStart + 1), TokenKind.EndOfInput, TokenFlags.None));
}
return ScanGenericToken(c);
default:
if (c.IsWhitespace())
{
SkipWhiteSpace();
goto again;
}
if (char.IsLetter(c))
{
return ScanIdentifier(c);
}
return ScanGenericToken(c);
}
}
}
}
|