File size: 140,131 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Management.Automation.Subsystem;
using System.Management.Automation.Subsystem.DSC;
namespace System.Management.Automation
{
internal class CompletionContext
{
internal List<Ast> RelatedAsts { get; set; }
// Only one of TokenAtCursor or TokenBeforeCursor is set
// This is how we can tell if we're trying to complete part of something (like a member)
// or complete an argument, where TokenBeforeCursor could be a parameter name.
internal Token TokenAtCursor { get; set; }
internal Token TokenBeforeCursor { get; set; }
internal IScriptPosition CursorPosition { get; set; }
internal PowerShellExecutionHelper Helper { get; set; }
internal Hashtable Options { get; set; }
internal Dictionary<string, ScriptBlock> CustomArgumentCompleters { get; set; }
internal Dictionary<string, ScriptBlock> NativeArgumentCompleters { get; set; }
internal string WordToComplete { get; set; }
internal int ReplacementIndex { get; set; }
internal int ReplacementLength { get; set; }
internal ExecutionContext ExecutionContext { get; set; }
internal PseudoBindingInfo PseudoBindingInfo { get; set; }
internal TypeInferenceContext TypeInferenceContext { get; set; }
internal bool GetOption(string option, bool @default)
{
if (Options == null || !Options.ContainsKey(option))
{
return @default;
}
return LanguagePrimitives.ConvertTo<bool>(Options[option]);
}
}
internal class CompletionAnalysis
{
private readonly Ast _ast;
private readonly Token[] _tokens;
private readonly IScriptPosition _cursorPosition;
private readonly Hashtable _options;
internal CompletionAnalysis(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options)
{
_ast = ast;
_tokens = tokens;
_cursorPosition = cursorPosition;
_options = options;
}
private static bool IsInterestingToken(Token token)
{
return token.Kind != TokenKind.NewLine && token.Kind != TokenKind.EndOfInput;
}
private static bool IsCursorWithinOrJustAfterExtent(IScriptPosition cursor, IScriptExtent extent)
{
return cursor.Offset > extent.StartOffset && cursor.Offset <= extent.EndOffset;
}
private static bool IsCursorRightAfterExtent(IScriptPosition cursor, IScriptExtent extent)
{
return cursor.Offset == extent.EndOffset;
}
private static bool IsCursorAfterExtentAndInTheSameLine(IScriptPosition cursor, IScriptExtent extent)
{
return cursor.Offset >= extent.EndOffset && extent.EndLineNumber == cursor.LineNumber;
}
private static bool IsCursorBeforeExtent(IScriptPosition cursor, IScriptExtent extent)
{
return cursor.Offset < extent.StartOffset;
}
private static bool IsCursorAfterExtent(IScriptPosition cursor, IScriptExtent extent)
{
return extent.EndOffset < cursor.Offset;
}
private static bool IsCursorOutsideOfExtent(IScriptPosition cursor, IScriptExtent extent)
{
return cursor.Offset < extent.StartOffset || cursor.Offset > extent.EndOffset;
}
internal readonly struct AstAnalysisContext
{
internal AstAnalysisContext(Token tokenAtCursor, Token tokenBeforeCursor, List<Ast> relatedAsts, int replacementIndex)
{
TokenAtCursor = tokenAtCursor;
TokenBeforeCursor = tokenBeforeCursor;
RelatedAsts = relatedAsts;
ReplacementIndex = replacementIndex;
}
internal readonly Token TokenAtCursor;
internal readonly Token TokenBeforeCursor;
internal readonly List<Ast> RelatedAsts;
internal readonly int ReplacementIndex;
}
internal static AstAnalysisContext ExtractAstContext(Ast inputAst, Token[] inputTokens, IScriptPosition cursor)
{
bool adjustLineAndColumn = false;
IScriptPosition positionForAstSearch = cursor;
Token tokenBeforeCursor = null;
Token tokenAtCursor = InterstingTokenAtCursorOrDefault(inputTokens, cursor);
if (tokenAtCursor == null)
{
tokenBeforeCursor = InterstingTokenBeforeCursorOrDefault(inputTokens, cursor);
if (tokenBeforeCursor != null)
{
positionForAstSearch = tokenBeforeCursor.Extent.EndScriptPosition;
adjustLineAndColumn = true;
}
}
else
{
var stringExpandableToken = tokenAtCursor as StringExpandableToken;
if (stringExpandableToken?.NestedTokens != null)
{
tokenAtCursor = InterstingTokenAtCursorOrDefault(stringExpandableToken.NestedTokens, cursor) ?? stringExpandableToken;
}
}
int replacementIndex = adjustLineAndColumn ? cursor.Offset : 0;
List<Ast> relatedAsts = AstSearcher.FindAll(
inputAst,
ast => IsCursorWithinOrJustAfterExtent(positionForAstSearch, ast.Extent),
searchNestedScriptBlocks: true).ToList();
if (relatedAsts.Count == 0)
{
relatedAsts.Add(inputAst);
}
// If the last ast is an unnamed block that starts with "param" the cursor is inside a param block.
// To avoid adding special handling to all the completers that look at the last ast, we remove it here because it's not useful for completion.
if (relatedAsts[^1].Extent.Text.StartsWith("param", StringComparison.OrdinalIgnoreCase)
&& relatedAsts[^1] is NamedBlockAst namedBlock && namedBlock.Unnamed)
{
relatedAsts.RemoveAt(relatedAsts.Count - 1);
}
Diagnostics.Assert(tokenAtCursor == null || tokenBeforeCursor == null, "Only one of these tokens can be non-null");
return new AstAnalysisContext(tokenAtCursor, tokenBeforeCursor, relatedAsts, replacementIndex);
}
internal CompletionContext CreateCompletionContext(PowerShell powerShell)
{
var typeInferenceContext = new TypeInferenceContext(powerShell);
return InitializeCompletionContext(typeInferenceContext);
}
internal CompletionContext CreateCompletionContext(TypeInferenceContext typeInferenceContext)
{
return InitializeCompletionContext(typeInferenceContext);
}
private CompletionContext InitializeCompletionContext(TypeInferenceContext typeInferenceContext)
{
var astContext = ExtractAstContext(_ast, _tokens, _cursorPosition);
typeInferenceContext.CurrentTypeDefinitionAst ??= Ast.GetAncestorTypeDefinitionAst(astContext.RelatedAsts.Last());
ExecutionContext executionContext = typeInferenceContext.ExecutionContext;
return new CompletionContext
{
Options = _options,
CursorPosition = _cursorPosition,
TokenAtCursor = astContext.TokenAtCursor,
TokenBeforeCursor = astContext.TokenBeforeCursor,
RelatedAsts = astContext.RelatedAsts,
ReplacementIndex = astContext.ReplacementIndex,
ExecutionContext = executionContext,
TypeInferenceContext = typeInferenceContext,
Helper = typeInferenceContext.Helper,
CustomArgumentCompleters = executionContext.CustomArgumentCompleters,
NativeArgumentCompleters = executionContext.NativeArgumentCompleters,
};
}
private static Token InterstingTokenAtCursorOrDefault(IReadOnlyList<Token> tokens, IScriptPosition cursorPosition)
{
for (int i = tokens.Count - 1; i >= 0; --i)
{
Token token = tokens[i];
if (IsCursorWithinOrJustAfterExtent(cursorPosition, token.Extent) && IsInterestingToken(token))
{
return token;
}
}
return null;
}
private static Token InterstingTokenBeforeCursorOrDefault(IReadOnlyList<Token> tokens, IScriptPosition cursorPosition)
{
for (int i = tokens.Count - 1; i >= 0; --i)
{
Token token = tokens[i];
if (IsCursorAfterExtent(cursorPosition, token.Extent) && IsInterestingToken(token))
{
return token;
}
}
return null;
}
private static Ast GetLastAstAtCursor(ScriptBlockAst scriptBlockAst, IScriptPosition cursorPosition)
{
var asts = AstSearcher.FindAll(scriptBlockAst, ast => IsCursorRightAfterExtent(cursorPosition, ast.Extent), searchNestedScriptBlocks: true);
return asts.LastOrDefault();
}
#region Special Cases
/// <summary>
/// Check if we should complete file names for "switch -file"
/// </summary>
private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCursor)
{
Tuple<Token, Ast> fileConditionTuple;
if (lastAst is ErrorStatementAst errorStatement && errorStatement.Flags is not null && errorStatement.Kind is not null && tokenBeforeCursor is not null &&
errorStatement.Kind.Kind.Equals(TokenKind.Switch) && errorStatement.Flags.TryGetValue("file", out fileConditionTuple))
{
// Handle "switch -file <tab>"
return fileConditionTuple.Item1.Extent.EndOffset == tokenBeforeCursor.Extent.EndOffset;
}
if (lastAst.Parent is CommandExpressionAst)
{
// Handle "switch -file m<tab>" or "switch -file *.ps1<tab>"
if (lastAst.Parent.Parent is not PipelineAst pipeline)
{
return false;
}
if (pipeline.Parent is not ErrorStatementAst parentErrorStatement || parentErrorStatement.Kind is null || parentErrorStatement.Flags is null)
{
return false;
}
return (parentErrorStatement.Kind.Kind.Equals(TokenKind.Switch) &&
parentErrorStatement.Flags.TryGetValue("file", out fileConditionTuple) && fileConditionTuple.Item2 == pipeline);
}
return false;
}
/// <summary>
/// Check if we should complete parameter names for switch cases on $PSBoundParameters.Keys
/// </summary>
private static List<CompletionResult> CompleteAgainstSwitchCaseCondition(CompletionContext completionContext)
{
var lastAst = completionContext.RelatedAsts.Last();
PipelineAst conditionPipeline = null;
Ast switchAst = null;
// Check if we're in a switch statement (complete) or error statement (incomplete switch)
if (lastAst.Parent is SwitchStatementAst switchStatementAst)
{
// Verify that the lastAst is one of the clause conditions (not in the body)
bool isClauseCondition = switchStatementAst.Clauses.Any(clause => clause.Item1 == lastAst);
if (!isClauseCondition)
{
return null;
}
conditionPipeline = switchStatementAst.Condition as PipelineAst;
switchAst = switchStatementAst;
}
else
{
// Check for incomplete switch parsed as ErrorStatementAst
if (lastAst.Parent is not ErrorStatementAst errorStatementAst || errorStatementAst.Kind is null ||
errorStatementAst.Kind.Kind != TokenKind.Switch)
{
return null;
}
// For ErrorStatementAst, the case value is in Bodies, condition is in Conditions
bool isInBodies = errorStatementAst.Bodies != null && errorStatementAst.Bodies.Any(body => body == lastAst);
if (!isInBodies)
{
return null;
}
// Get the condition from ErrorStatementAst.Conditions
if (errorStatementAst.Conditions != null && errorStatementAst.Conditions.Count > 0)
{
conditionPipeline = errorStatementAst.Conditions[0] as PipelineAst;
}
switchAst = errorStatementAst;
}
if (conditionPipeline == null || conditionPipeline.PipelineElements.Count != 1)
{
return null;
}
if (conditionPipeline.PipelineElements[0] is not CommandExpressionAst commandExpressionAst)
{
return null;
}
// Check if the expression is a member access on $PSBoundParameters.Keys
if (commandExpressionAst.Expression is not MemberExpressionAst memberExpressionAst)
{
return null;
}
// Check if the target is $PSBoundParameters
if (memberExpressionAst.Expression is not VariableExpressionAst variableExpressionAst ||
!variableExpressionAst.VariablePath.UserPath.Equals("PSBoundParameters", StringComparison.OrdinalIgnoreCase))
{
return null;
}
// Check if the member is "Keys"
if (memberExpressionAst.Member is not StringConstantExpressionAst memberNameAst ||
!memberNameAst.Value.Equals("Keys", StringComparison.OrdinalIgnoreCase))
{
return null;
}
// Find the nearest param block by traversing up the AST
var paramBlockAst = FindNearestParamBlock(switchAst.Parent);
if (paramBlockAst == null || paramBlockAst.Parameters.Count == 0)
{
return null;
}
// Generate completion results from parameter names
var wordToComplete = completionContext.WordToComplete ?? string.Empty;
return CreateParameterCompletionResults(paramBlockAst, wordToComplete);
}
/// <summary>
/// Check if we should complete parameter names for $PSBoundParameters access patterns
/// Supports: $PSBoundParameters.ContainsKey('...'), $PSBoundParameters['...'], $PSBoundParameters.Remove('...')
/// </summary>
private static List<CompletionResult> CompleteAgainstPSBoundParametersAccess(CompletionContext completionContext)
{
var lastAst = completionContext.RelatedAsts.Last();
// Must be a string constant
if (lastAst is not StringConstantExpressionAst stringAst)
{
return null;
}
ExpressionAst targetAst = null;
// Check for method invocation: $PSBoundParameters.ContainsKey('...') or $PSBoundParameters.Remove('...')
if (lastAst.Parent is InvokeMemberExpressionAst invokeMemberAst)
{
if (invokeMemberAst.Member is StringConstantExpressionAst memberName &&
(memberName.Value.Equals("ContainsKey", StringComparison.OrdinalIgnoreCase) ||
memberName.Value.Equals("Remove", StringComparison.OrdinalIgnoreCase)))
{
targetAst = invokeMemberAst.Expression;
}
}
// Check for indexer: $PSBoundParameters['...']
else if (lastAst.Parent is IndexExpressionAst indexAst)
{
targetAst = indexAst.Target;
}
if (targetAst is null)
{
return null;
}
// Check if target is $PSBoundParameters
if (targetAst is not VariableExpressionAst variableAst ||
!variableAst.VariablePath.UserPath.Equals("PSBoundParameters", StringComparison.OrdinalIgnoreCase))
{
return null;
}
// Find the nearest param block
var paramBlockAst = FindNearestParamBlock(lastAst.Parent);
if (paramBlockAst == null || paramBlockAst.Parameters.Count == 0)
{
return null;
}
// Generate completion results from parameter names
var wordToComplete = completionContext.WordToComplete ?? string.Empty;
// Determine quote style based on the string constant type
string quoteChar = string.Empty;
if (stringAst.StringConstantType == StringConstantType.SingleQuoted)
{
quoteChar = "'";
}
else if (stringAst.StringConstantType == StringConstantType.DoubleQuoted)
{
quoteChar = "\"";
}
return CreateParameterCompletionResults(paramBlockAst, wordToComplete, quoteChar);
}
/// <summary>
/// Finds the nearest ParamBlockAst by traversing up the AST hierarchy.
/// </summary>
/// <param name="startAst">The AST node to start searching from.</param>
/// <returns>The nearest ParamBlockAst if found; otherwise, null.</returns>
private static ParamBlockAst FindNearestParamBlock(Ast startAst)
{
Ast current = startAst;
while (current != null)
{
if (current is FunctionDefinitionAst functionDefinitionAst)
{
return functionDefinitionAst.Body?.ParamBlock;
}
else if (current is ScriptBlockAst scriptBlockAst)
{
var paramBlock = scriptBlockAst.ParamBlock;
if (paramBlock != null)
{
return paramBlock;
}
}
current = current.Parent;
}
return null;
}
/// <summary>
/// Creates completion results from parameter names with optional quote wrapping.
/// </summary>
/// <param name="paramBlockAst">The parameter block containing parameters to complete.</param>
/// <param name="wordToComplete">The partial word to match against parameter names.</param>
/// <param name="quoteChar">Optional quote character to wrap completion text (empty string for no quotes).</param>
/// <returns>A list of completion results, or null if no matches found.</returns>
private static List<CompletionResult> CreateParameterCompletionResults(
ParamBlockAst paramBlockAst,
string wordToComplete,
string quoteChar = "")
{
var result = paramBlockAst.Parameters
.Select(parameter => parameter.Name.VariablePath.UserPath)
.Where(parameterName => parameterName.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))
.Select(parameterName =>
new CompletionResult(
quoteChar + parameterName + quoteChar,
parameterName,
CompletionResultType.ParameterValue,
parameterName))
.ToList();
return result.Count > 0 ? result : null;
}
private static bool CompleteOperator(Token tokenAtCursor, Ast lastAst)
{
if (tokenAtCursor.Kind == TokenKind.Minus)
{
return lastAst is BinaryExpressionAst;
}
else if (tokenAtCursor.Kind == TokenKind.Parameter)
{
if (lastAst is CommandParameterAst)
return lastAst.Parent is ExpressionAst;
}
return false;
}
private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, Token token, out TokenKind kind)
{
kind = TokenKind.Unknown;
// Handle "switch -f<tab>"
var errorStatement = lastAst as ErrorStatementAst;
if (errorStatement != null && errorStatement.Kind != null)
{
switch (errorStatement.Kind.Kind)
{
case TokenKind.Switch:
kind = TokenKind.Switch;
return true;
default:
break;
}
}
// Handle "switch -<tab>". Skip cases like "switch ($a) {} -<tab> "
var scriptBlockAst = scriptAst as ScriptBlockAst;
if (token != null && token.Kind == TokenKind.Minus && scriptBlockAst != null)
{
var asts = AstSearcher.FindAll(scriptBlockAst, ast => IsCursorAfterExtent(token.Extent.StartScriptPosition, ast.Extent), searchNestedScriptBlocks: true);
Ast last = asts.LastOrDefault();
errorStatement = null;
while (last != null)
{
errorStatement = last as ErrorStatementAst;
if (errorStatement != null) { break; }
last = last.Parent;
}
if (errorStatement != null && errorStatement.Kind != null)
{
switch (errorStatement.Kind.Kind)
{
case TokenKind.Switch:
Tuple<Token, Ast> value;
if (errorStatement.Flags != null && errorStatement.Flags.TryGetValue(Parser.VERBATIM_ARGUMENT, out value))
{
if (IsTokenTheSame(value.Item1, token))
{
kind = TokenKind.Switch;
return true;
}
}
break;
default:
break;
}
}
}
return false;
}
private static bool IsTokenTheSame(Token x, Token y)
{
if (x.Kind == y.Kind && x.TokenFlags == y.TokenFlags &&
x.Extent.StartLineNumber == y.Extent.StartLineNumber &&
x.Extent.StartColumnNumber == y.Extent.StartColumnNumber &&
x.Extent.EndLineNumber == y.Extent.EndLineNumber &&
x.Extent.EndColumnNumber == y.Extent.EndColumnNumber)
{
return true;
}
return false;
}
#endregion Special Cases
internal List<CompletionResult> GetResults(PowerShell powerShell, out int replacementIndex, out int replacementLength)
{
var completionContext = CreateCompletionContext(powerShell);
PSLanguageMode? previousLanguageMode = null;
try
{
// Tab expansion is called from a trusted function - we should apply ConstrainedLanguage if necessary.
if (completionContext.ExecutionContext.HasRunspaceEverUsedConstrainedLanguageMode)
{
previousLanguageMode = completionContext.ExecutionContext.LanguageMode;
completionContext.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
}
return GetResultHelper(completionContext, out replacementIndex, out replacementLength);
}
finally
{
if (previousLanguageMode.HasValue)
{
completionContext.ExecutionContext.LanguageMode = previousLanguageMode.Value;
}
}
}
internal List<CompletionResult> GetResultHelper(CompletionContext completionContext, out int replacementIndex, out int replacementLength)
{
replacementIndex = -1;
replacementLength = -1;
var tokenAtCursor = completionContext.TokenAtCursor;
var lastAst = completionContext.RelatedAsts.Last();
List<CompletionResult> result = null;
if (tokenAtCursor != null)
{
replacementIndex = tokenAtCursor.Extent.StartScriptPosition.Offset;
replacementLength = tokenAtCursor.Extent.EndScriptPosition.Offset - replacementIndex;
completionContext.ReplacementIndex = replacementIndex;
completionContext.ReplacementLength = replacementLength;
switch (tokenAtCursor.Kind)
{
case TokenKind.Variable:
case TokenKind.SplattedVariable:
completionContext.WordToComplete = ((VariableToken)tokenAtCursor).VariablePath.UserPath;
result = CompletionCompleters.CompleteVariable(completionContext);
break;
case TokenKind.Multiply:
case TokenKind.Generic:
case TokenKind.MinusMinus: // for native commands '--'
case TokenKind.Identifier:
if (!tokenAtCursor.TokenFlags.HasFlag(TokenFlags.TypeName))
{
result = CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength);
if (result is not null)
{
return result;
}
result = GetResultForIdentifier(completionContext, ref replacementIndex, ref replacementLength);
}
break;
case TokenKind.Parameter:
completionContext.WordToComplete = tokenAtCursor.Text;
var cmdAst = lastAst.Parent as CommandAst;
if (lastAst is StringConstantExpressionAst && cmdAst != null && cmdAst.CommandElements.Count == 1)
{
result = CompleteFileNameAsCommand(completionContext);
break;
}
TokenKind statementKind;
if (CompleteAgainstStatementFlags(null, lastAst, null, out statementKind))
{
result = CompletionCompleters.CompleteStatementFlags(statementKind, completionContext.WordToComplete);
break;
}
if (CompleteOperator(tokenAtCursor, lastAst))
{
result = CompletionCompleters.CompleteOperator(completionContext.WordToComplete);
break;
}
// Handle scenarios like this: dir -path:<tab>
if (completionContext.WordToComplete.EndsWith(':'))
{
replacementIndex = tokenAtCursor.Extent.EndScriptPosition.Offset;
replacementLength = 0;
completionContext.WordToComplete = string.Empty;
result = CompletionCompleters.CompleteCommandArgument(completionContext);
}
else
{
result = CompletionCompleters.CompleteCommandParameter(completionContext);
}
break;
case TokenKind.Dot:
case TokenKind.ColonColon:
case TokenKind.QuestionDot:
replacementIndex += tokenAtCursor.Text.Length;
replacementLength = 0;
result = CompletionCompleters.CompleteMember(completionContext, @static: tokenAtCursor.Kind == TokenKind.ColonColon, ref replacementLength);
break;
case TokenKind.Comment:
completionContext.WordToComplete = tokenAtCursor.Text;
result = CompletionCompleters.CompleteComment(completionContext, ref replacementIndex, ref replacementLength);
break;
case TokenKind.StringExpandable:
case TokenKind.StringLiteral:
// Search to see if we're looking at an assignment
if (lastAst.Parent is CommandExpressionAst
&& lastAst.Parent.Parent is AssignmentStatementAst assignmentAst)
{
// Handle scenarios like `$ErrorActionPreference = '<tab>`
if (TryGetCompletionsForVariableAssignment(completionContext, assignmentAst, out List<CompletionResult> completions))
{
return completions;
}
}
else if (lastAst.Parent is BinaryExpressionAst binaryExpression)
{
completionContext.WordToComplete = (tokenAtCursor as StringToken).Value;
result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left);
if (result.Count > 0)
{
return result;
}
}
else if (lastAst.Parent is IndexExpressionAst indexExpressionAst)
{
// Handles quoted string inside index expression like: $PSVersionTable["<Tab>"]
completionContext.WordToComplete = (tokenAtCursor as StringToken).Value;
// Check for $PSBoundParameters indexer first
var psBoundResult = CompleteAgainstPSBoundParametersAccess(completionContext);
if (psBoundResult != null && psBoundResult.Count > 0)
{
return psBoundResult;
}
return CompletionCompleters.CompleteIndexExpression(completionContext, indexExpressionAst.Target);
}
result = GetResultForString(completionContext, ref replacementIndex, ref replacementLength);
break;
case TokenKind.RBracket:
if (lastAst is TypeExpressionAst)
{
var targetExpr = (TypeExpressionAst)lastAst;
var memberResult = new List<CompletionResult>();
CompletionCompleters.CompleteMemberHelper(
true,
"*",
targetExpr,
completionContext, memberResult);
if (memberResult.Count > 0)
{
replacementIndex++;
replacementLength = 0;
result = (from entry in memberResult
let completionText = TokenKind.ColonColon.Text() + entry.CompletionText
select new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip)).ToList();
}
}
break;
case TokenKind.Comma:
// Handle array elements such as the followings:
// - `dir .\cd,<tab>`
// - `dir -Path: .\cd,<tab>`
// - `dir .\abc.txt,<tab> -File`
// - `dir -Path .\abc.txt,<tab> -File`
// - `dir -Path: .\abc.txt,<tab> -File`
if (lastAst is ErrorExpressionAst or ArrayLiteralAst &&
lastAst.Parent is CommandAst or CommandParameterAst)
{
replacementIndex += replacementLength;
replacementLength = 0;
result = CompletionCompleters.CompleteCommandArgument(completionContext);
}
else if (lastAst is AttributeAst)
{
completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length;
completionContext.ReplacementLength = replacementLength = 0;
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
}
else
{
//
// Handle auto completion for enum/dependson property of DSC resource,
// cursor is right after ','
//
// Configuration config
// {
// User test
// {
// DependsOn=@('[user]x',|)
//
result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _);
}
break;
case TokenKind.AtCurly:
// Handle scenarios such as 'Sort-Object @{<tab>' and 'gci | Format-Table @{'
result = GetResultForHashtable(completionContext);
replacementIndex += 2;
replacementLength = 0;
break;
case TokenKind.Semi:
// Handle scenarios such as 'gci | Format-Table @{Label=...;<tab>'
if (lastAst is HashtableAst)
{
result = GetResultForHashtable(completionContext);
replacementIndex += 1;
replacementLength = 0;
}
break;
case TokenKind.Number:
// Handle scenarios such as Get-Process -Id 5<tab> || Get-Process -Id 5210, 3<tab> || Get-Process -Id: 5210, 3<tab>
if (lastAst is ConstantExpressionAst &&
(lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst ||
(lastAst.Parent is ArrayLiteralAst &&
(lastAst.Parent.Parent is CommandAst || lastAst.Parent.Parent is CommandParameterAst))))
{
completionContext.WordToComplete = tokenAtCursor.Text;
result = CompletionCompleters.CompleteCommandArgument(completionContext);
replacementIndex = completionContext.ReplacementIndex;
replacementLength = completionContext.ReplacementLength;
}
else if (lastAst.Parent is CommandExpressionAst
&& lastAst.Parent.Parent is AssignmentStatementAst assignmentAst2)
{
// Handle scenarios like '[ValidateSet(11,22)][int]$i = 11; $i = 2<tab>'
if (TryGetCompletionsForVariableAssignment(completionContext, assignmentAst2, out List<CompletionResult> completions))
{
result = completions;
}
}
break;
case TokenKind.Redirection:
// Handle file name completion after the redirection operator: gps ><tab> || gps >><tab> || dir con 2><tab> || dir con 2>><tab>
if (lastAst is ErrorExpressionAst && lastAst.Parent is FileRedirectionAst)
{
completionContext.WordToComplete = string.Empty;
completionContext.ReplacementIndex = (replacementIndex += tokenAtCursor.Text.Length);
completionContext.ReplacementLength = replacementLength = 0;
result = new List<CompletionResult>(CompletionCompleters.CompleteFilename(completionContext));
}
break;
case TokenKind.Minus:
// Handle operator completion: 55 -<tab> || "string" -<tab> || (Get-Something) -<tab>
if (CompleteOperator(tokenAtCursor, lastAst))
{
result = CompletionCompleters.CompleteOperator(string.Empty);
break;
}
// Handle the flag completion for statements, such as the switch statement
if (CompleteAgainstStatementFlags(completionContext.RelatedAsts[0], null, tokenAtCursor, out statementKind))
{
completionContext.WordToComplete = tokenAtCursor.Text;
result = CompletionCompleters.CompleteStatementFlags(statementKind, completionContext.WordToComplete);
break;
}
break;
case TokenKind.DynamicKeyword:
{
DynamicKeywordStatementAst keywordAst;
ConfigurationDefinitionAst configureAst = GetAncestorConfigurationAstAndKeywordAst(
completionContext.CursorPosition, lastAst, out keywordAst);
Diagnostics.Assert(configureAst != null, "ConfigurationDefinitionAst should never be null");
bool matched = false;
completionContext.WordToComplete = tokenAtCursor.Text.Trim();
// Current token is within ConfigurationDefinitionAst or DynamicKeywordStatementAst
return GetResultForIdentifierInConfiguration(completionContext, configureAst, null, out matched);
}
case TokenKind.Equals:
case TokenKind.AtParen:
case TokenKind.LParen:
{
if (lastAst is AttributeAst)
{
completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length;
completionContext.ReplacementLength = replacementLength = 0;
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
}
else if (lastAst is HashtableAst hashTableAst && lastAst.Parent is not DynamicKeywordStatementAst && CheckForPendingAssignment(hashTableAst))
{
// Handle scenarios such as 'gci | Format-Table @{Label=<tab>' if incomplete parsing of the assignment.
return null;
}
else if (lastAst is AssignmentStatementAst assignmentAst2)
{
completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length;
completionContext.ReplacementLength = replacementLength = 0;
// Handle scenarios like '$ErrorActionPreference =<tab>'
if (TryGetCompletionsForVariableAssignment(completionContext, assignmentAst2, out List<CompletionResult> completions))
{
return completions;
}
}
else if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0)
{
foreach (AttributeBaseAst attribute in paramAst.Attributes)
{
if (IsCursorWithinOrJustAfterExtent(_cursorPosition, attribute.Extent))
{
completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length;
completionContext.ReplacementLength = replacementLength = 0;
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
break;
}
}
}
else
{
// Handle scenarios such as 'configuration foo { File ab { Attributes ='
// (auto completion for enum/dependson property of DSC resource),
// cursor is right after '=', '(' or '@('
//
// Configuration config
// {
// User test
// {
// DependsOn=|
// DependsOn=@(|)
// DependsOn=(|
//
result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _);
}
break;
}
case TokenKind.Format:
case TokenKind.Not:
case TokenKind.Bnot:
case TokenKind.And:
case TokenKind.Or:
case TokenKind.Xor:
case TokenKind.Band:
case TokenKind.Bor:
case TokenKind.Bxor:
case TokenKind.Join:
case TokenKind.Ieq:
case TokenKind.Ine:
case TokenKind.Ige:
case TokenKind.Igt:
case TokenKind.Ilt:
case TokenKind.Ile:
case TokenKind.Ilike:
case TokenKind.Inotlike:
case TokenKind.Imatch:
case TokenKind.Inotmatch:
case TokenKind.Ireplace:
case TokenKind.Icontains:
case TokenKind.Inotcontains:
case TokenKind.Iin:
case TokenKind.Inotin:
case TokenKind.Isplit:
case TokenKind.Ceq:
case TokenKind.Cne:
case TokenKind.Cge:
case TokenKind.Cgt:
case TokenKind.Clt:
case TokenKind.Cle:
case TokenKind.Clike:
case TokenKind.Cnotlike:
case TokenKind.Cmatch:
case TokenKind.Cnotmatch:
case TokenKind.Creplace:
case TokenKind.Ccontains:
case TokenKind.Cnotcontains:
case TokenKind.Cin:
case TokenKind.Cnotin:
case TokenKind.Csplit:
case TokenKind.Is:
case TokenKind.IsNot:
case TokenKind.As:
case TokenKind.Shl:
case TokenKind.Shr:
result = CompletionCompleters.CompleteOperator(tokenAtCursor.Text);
break;
case TokenKind.LBracket:
if (lastAst.Parent is IndexExpressionAst indexExpression)
{
// Handles index expression with cursor right after lbracket like: $PSVersionTable[<Tab>]
completionContext.WordToComplete = string.Empty;
result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target);
if (result.Count > 0)
{
replacementIndex++;
replacementLength--;
}
}
break;
default:
result = CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength);
if (result is not null)
{
return result;
}
if ((tokenAtCursor.TokenFlags & TokenFlags.Keyword) != 0)
{
completionContext.WordToComplete = tokenAtCursor.Text;
// Handle the file name completion
result = CompleteFileNameAsCommand(completionContext);
// Handle the command name completion
var commandNameResult = CompletionCompleters.CompleteCommand(completionContext);
if (commandNameResult != null && commandNameResult.Count > 0)
{
result.AddRange(commandNameResult);
}
}
else
{
replacementIndex = -1;
replacementLength = -1;
}
break;
}
}
else
{
IScriptPosition cursor = completionContext.CursorPosition;
bool isCursorLineEmpty = string.IsNullOrWhiteSpace(cursor.Line);
var tokenBeforeCursor = completionContext.TokenBeforeCursor;
bool isLineContinuationBeforeCursor = false;
if (tokenBeforeCursor != null)
{
//
// Handle following scenario, cursor is in next line and after a command call,
// we need to skip the command call autocompletion if there is no backtick character
// in the end of the previous line, since backtick means command call continues to the next line
//
// Configuration config
// {
// User test
// {
// DependsOn=zzz
// |
//
isLineContinuationBeforeCursor = completionContext.TokenBeforeCursor.Kind == TokenKind.LineContinuation;
}
bool skipAutoCompleteForCommandCall = isCursorLineEmpty && !isLineContinuationBeforeCursor;
bool lastAstIsExpressionAst = lastAst is ExpressionAst;
if (!skipAutoCompleteForCommandCall &&
(lastAst is CommandParameterAst || lastAst is CommandAst ||
(lastAstIsExpressionAst && lastAst.Parent is CommandAst) ||
(lastAstIsExpressionAst && lastAst.Parent is CommandParameterAst) ||
(lastAstIsExpressionAst && lastAst.Parent is ArrayLiteralAst &&
(lastAst.Parent.Parent is CommandAst || lastAst.Parent.Parent is CommandParameterAst))))
{
completionContext.WordToComplete = string.Empty;
var hashTableAst = lastAst as HashtableAst;
// Do not do any tab completion if we have a hash table
// and an assignment is pending. For cases like:
// new-object System.Drawing.Point -prop @{ X= -> Tab should not complete
// Note: This check works when all statements preceding the last are complete,
// but if a preceding statement is incomplete this test fails because
// the Ast mixes the statements due to incomplete parsing.
// e.g.,
// new-object System.Drawing.Point -prop @{ X = 100; Y = <- Incomplete line
// new-object new-object System.Drawing.Point -prop @{ X = <- Tab will yield hash properties.
if (hashTableAst != null &&
CheckForPendingAssignment(hashTableAst))
{
return result;
}
if (hashTableAst != null)
{
completionContext.ReplacementIndex = replacementIndex = completionContext.CursorPosition.Offset;
completionContext.ReplacementLength = replacementLength = 0;
result = CompletionCompleters.CompleteHashtableKey(completionContext, hashTableAst);
}
else
{
result = CompletionCompleters.CompleteCommandArgument(completionContext);
replacementIndex = completionContext.ReplacementIndex;
replacementLength = completionContext.ReplacementLength;
}
}
else
{
//
// Handle completion of empty line within configuration statement
// Ignore the auto completion if there is a backtick character in previous line
//
bool cursorAtLineContinuation;
if ((tokenAtCursor != null && tokenAtCursor.Kind == TokenKind.LineContinuation) ||
(tokenBeforeCursor != null && tokenBeforeCursor.Kind == TokenKind.LineContinuation))
cursorAtLineContinuation = true;
else
cursorAtLineContinuation = false;
if (isCursorLineEmpty && !cursorAtLineContinuation)
{
//
// Handle following scenario, both Configuration and DSC resource 'User' are not complete
// Check Hashtable first, and then fallback to configuration
//
// Configuration config
// {
// User test
// {
// DependsOn=''
// |
result = GetResultForHashtable(completionContext);
if (result == null || result.Count == 0)
{
DynamicKeywordStatementAst keywordAst;
ConfigurationDefinitionAst configAst = GetAncestorConfigurationAstAndKeywordAst(cursor, lastAst, out keywordAst);
if (configAst != null)
{
bool matched;
result = GetResultForIdentifierInConfiguration(completionContext, configAst, keywordAst, out matched);
}
}
// Handles following scenario where user is tab completing a member on an empty line:
// "Hello".
// <Tab>
if ((result is null || result.Count == 0) && tokenBeforeCursor is not null)
{
switch (completionContext.TokenBeforeCursor.Kind)
{
case TokenKind.Dot:
case TokenKind.ColonColon:
case TokenKind.QuestionDot:
replacementIndex = cursor.Offset;
replacementLength = 0;
result = CompletionCompleters.CompleteMember(completionContext, @static: completionContext.TokenBeforeCursor.Kind == TokenKind.ColonColon, ref replacementLength);
break;
case TokenKind.LParen:
case TokenKind.Comma:
if (lastAst is AttributeAst)
{
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
}
if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0)
{
foreach (AttributeBaseAst attribute in paramAst.Attributes)
{
if (IsCursorWithinOrJustAfterExtent(_cursorPosition, attribute.Extent))
{
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
break;
}
}
}
break;
case TokenKind.Ieq:
case TokenKind.Ceq:
case TokenKind.Ine:
case TokenKind.Cne:
case TokenKind.Ilike:
case TokenKind.Clike:
case TokenKind.Inotlike:
case TokenKind.Cnotlike:
case TokenKind.Imatch:
case TokenKind.Cmatch:
case TokenKind.Inotmatch:
case TokenKind.Cnotmatch:
if (lastAst is BinaryExpressionAst binaryExpression)
{
completionContext.WordToComplete = string.Empty;
result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left);
}
break;
case TokenKind.LBracket:
if (lastAst.Parent is IndexExpressionAst indexExpression)
{
// Handles index expression where cursor is on a new line after the lbracket like: $PSVersionTable[\n<Tab>]
completionContext.WordToComplete = string.Empty;
result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target);
}
break;
default:
break;
}
}
}
else if (completionContext.TokenAtCursor == null)
{
if (tokenBeforeCursor != null)
{
//
// Handle auto completion for enum/dependson property of DSC resource,
// cursor is after '=', ',', '(', or '@('
//
// Configuration config
// {
// User test
// {
// DependsOn= |
// DependsOn=@('[user]x', |)
// DependsOn=@( |)
// DependsOn=(|
//
switch (tokenBeforeCursor.Kind)
{
case TokenKind.Equals:
case TokenKind.Comma:
case TokenKind.AtParen:
case TokenKind.LParen:
{
if (lastAst is AssignmentStatementAst assignmentAst)
{
// Handle scenarios like '$ErrorActionPreference = <tab>'
if (TryGetCompletionsForVariableAssignment(completionContext, assignmentAst, out result))
{
break;
}
}
if (lastAst is AttributeAst)
{
completionContext.ReplacementLength = replacementLength = 0;
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
break;
}
if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0)
{
foreach (AttributeBaseAst attribute in paramAst.Attributes)
{
if (IsCursorWithinOrJustAfterExtent(_cursorPosition, attribute.Extent))
{
completionContext.ReplacementLength = replacementLength = 0;
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
break;
}
}
break;
}
result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _);
break;
}
case TokenKind.Break:
case TokenKind.Continue:
{
if ((lastAst is BreakStatementAst breakStatement && breakStatement.Label is null)
|| (lastAst is ContinueStatementAst continueStatement && continueStatement.Label is null))
{
result = CompleteLoopLabel(completionContext);
}
break;
}
case TokenKind.Using:
return CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength);
case TokenKind.Dot:
case TokenKind.ColonColon:
case TokenKind.QuestionDot:
// Handles following scenario with whitespace after member access token: "Hello". <Tab>
replacementIndex = cursor.Offset;
replacementLength = 0;
result = CompletionCompleters.CompleteMember(completionContext, @static: tokenBeforeCursor.Kind == TokenKind.ColonColon, ref replacementLength);
if (result is not null && result.Count > 0)
{
return result;
}
break;
case TokenKind.Ieq:
case TokenKind.Ceq:
case TokenKind.Ine:
case TokenKind.Cne:
case TokenKind.Ilike:
case TokenKind.Clike:
case TokenKind.Inotlike:
case TokenKind.Cnotlike:
case TokenKind.Imatch:
case TokenKind.Cmatch:
case TokenKind.Inotmatch:
case TokenKind.Cnotmatch:
if (lastAst is BinaryExpressionAst binaryExpression)
{
completionContext.WordToComplete = string.Empty;
result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left);
}
break;
case TokenKind.LBracket:
if (lastAst.Parent is IndexExpressionAst indexExpression)
{
// Handles index expression with whitespace between lbracket and cursor like: $PSVersionTable[ <Tab>]
completionContext.WordToComplete = string.Empty;
result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target);
}
break;
default:
break;
}
}
}
if (result != null && result.Count > 0)
{
completionContext.ReplacementIndex = replacementIndex = completionContext.CursorPosition.Offset;
completionContext.ReplacementLength = replacementLength = 0;
}
else
{
bool needFileCompletion = false;
if (lastAst is ErrorExpressionAst && lastAst.Parent is FileRedirectionAst)
{
// Handle file name completion after redirection operator: gps > <tab>
needFileCompletion = true;
}
else if (lastAst is ErrorStatementAst && CompleteAgainstSwitchFile(lastAst, completionContext.TokenBeforeCursor))
{
// Handle file name completion after "switch -file": switch -file <tab>
needFileCompletion = true;
}
if (needFileCompletion)
{
completionContext.WordToComplete = string.Empty;
result = new List<CompletionResult>(CompletionCompleters.CompleteFilename(completionContext));
replacementIndex = completionContext.ReplacementIndex;
replacementLength = completionContext.ReplacementLength;
}
}
}
}
if (result == null || result.Count == 0)
{
var typeAst = completionContext.RelatedAsts.OfType<TypeExpressionAst>().FirstOrDefault();
TypeName typeNameToComplete = null;
if (typeAst != null)
{
typeNameToComplete = FindTypeNameToComplete(typeAst.TypeName, _cursorPosition);
}
else
{
var typeConstraintAst = completionContext.RelatedAsts.OfType<TypeConstraintAst>().FirstOrDefault();
if (typeConstraintAst != null)
{
typeNameToComplete = FindTypeNameToComplete(typeConstraintAst.TypeName, _cursorPosition);
}
}
if (typeNameToComplete is null && tokenAtCursor?.TokenFlags.HasFlag(TokenFlags.TypeName) == true)
{
typeNameToComplete = new TypeName(tokenAtCursor.Extent, tokenAtCursor.Text);
}
if (typeNameToComplete != null)
{
// See if the typename to complete really is within the typename, and if so, which one, in the case of generics.
replacementIndex = typeNameToComplete.Extent.StartOffset;
replacementLength = typeNameToComplete.Extent.EndOffset - replacementIndex;
completionContext.WordToComplete = typeNameToComplete.FullName;
return CompletionCompleters.CompleteType(completionContext);
}
}
if (result == null || result.Count == 0)
{
result = GetResultForHashtable(completionContext);
// Handles the following scenario: [ipaddress]@{Address=""; <Tab> }
if (result?.Count > 0)
{
replacementIndex = completionContext.CursorPosition.Offset;
replacementLength = 0;
}
}
if (result == null || result.Count == 0)
{
// Handle special file completion scenarios: .\+file.txt -> +<tab>
string input = completionContext.RelatedAsts[0].Extent.Text;
if (Regex.IsMatch(input, @"^[\S]+$") && completionContext.RelatedAsts.Count > 0 && completionContext.RelatedAsts[0] is ScriptBlockAst)
{
replacementIndex = completionContext.RelatedAsts[0].Extent.StartScriptPosition.Offset;
replacementLength = completionContext.RelatedAsts[0].Extent.EndScriptPosition.Offset - replacementIndex;
completionContext.WordToComplete = input;
result = CompleteFileNameAsCommand(completionContext);
}
}
return result;
}
// Helper method to auto complete hashtable key
private static List<CompletionResult> GetResultForHashtable(CompletionContext completionContext)
{
Ast lastRelatedAst = null;
var cursorPosition = completionContext.CursorPosition;
// Enumeration is used over the LastAst pattern because empty lines following a key-value pair will set LastAst to the value.
// Example:
// @{
// Key1="Value1"
// <Tab>
// }
// In this case the last 3 Asts will be StringConstantExpression, CommandExpression, and Pipeline instead of the expected Hashtable
for (int i = completionContext.RelatedAsts.Count - 1; i >= 0; i--)
{
Ast ast = completionContext.RelatedAsts[i];
if (cursorPosition.Offset >= ast.Extent.StartOffset && cursorPosition.Offset <= ast.Extent.EndOffset)
{
lastRelatedAst = ast;
break;
}
}
if (lastRelatedAst is HashtableAst hashtableAst)
{
// Cursor is just after the hashtable: @{}<Tab>
if (completionContext.TokenAtCursor is not null && completionContext.TokenAtCursor.Kind == TokenKind.RCurly)
{
return null;
}
bool cursorIsWithinOrOnSameLineAsKeypair = false;
foreach (var pair in hashtableAst.KeyValuePairs)
{
if (cursorPosition.Offset >= pair.Item1.Extent.StartOffset
&& (cursorPosition.Offset <= pair.Item2.Extent.EndOffset || cursorPosition.LineNumber == pair.Item2.Extent.EndLineNumber))
{
cursorIsWithinOrOnSameLineAsKeypair = true;
break;
}
}
if (cursorIsWithinOrOnSameLineAsKeypair)
{
var tokenBeforeOrAtCursor = completionContext.TokenBeforeCursor ?? completionContext.TokenAtCursor;
if (tokenBeforeOrAtCursor.Kind != TokenKind.Semi)
{
return null;
}
}
completionContext.ReplacementIndex = completionContext.CursorPosition.Offset;
completionContext.ReplacementLength = 0;
return CompletionCompleters.CompleteHashtableKey(completionContext, hashtableAst);
}
return null;
}
// Helper method to look for an incomplete assignment pair in hash table.
private static bool CheckForPendingAssignment(HashtableAst hashTableAst)
{
foreach (var keyValue in hashTableAst.KeyValuePairs)
{
if (keyValue.Item2 is ErrorStatementAst)
{
// This indicates the assignment has not completed.
return true;
}
}
return false;
}
internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition cursor)
{
var typeName = type as TypeName;
if (typeName != null)
{
// If the cursor is at the start offset, it's not really inside, so return null.
// If the cursor is at the end offset, it's not really inside, but it's just before the cursor,
// we don want to complete it.
return (cursor.Offset > type.Extent.StartOffset && cursor.Offset <= type.Extent.EndOffset)
? typeName
: null;
}
var genericTypeName = type as GenericTypeName;
if (genericTypeName != null)
{
typeName = FindTypeNameToComplete(genericTypeName.TypeName, cursor);
if (typeName != null)
return typeName;
foreach (var t in genericTypeName.GenericArguments)
{
typeName = FindTypeNameToComplete(t, cursor);
if (typeName != null)
return typeName;
}
return null;
}
var arrayTypeName = type as ArrayTypeName;
if (arrayTypeName != null)
{
return FindTypeNameToComplete(arrayTypeName.ElementType, cursor) ?? null;
}
return null;
}
private static string GetFirstLineSubString(string stringToComplete, out bool hasNewLine)
{
hasNewLine = false;
if (!string.IsNullOrEmpty(stringToComplete))
{
var index = stringToComplete.AsSpan().IndexOfAny('\r', '\n');
if (index >= 0)
{
stringToComplete = stringToComplete.Substring(0, index);
hasNewLine = true;
}
}
return stringToComplete;
}
private static Tuple<ExpressionAst, StatementAst> GetHashEntryContainsCursor(
IScriptPosition cursor,
HashtableAst hashTableAst,
bool isCursorInString)
{
Tuple<ExpressionAst, StatementAst> keyValuePairWithCursor = null;
foreach (var kvp in hashTableAst.KeyValuePairs)
{
if (IsCursorWithinOrJustAfterExtent(cursor, kvp.Item2.Extent))
{
keyValuePairWithCursor = kvp;
break;
}
if (!isCursorInString)
{
//
// Handle following case, cursor is after '=' but before next key value pair,
// next key value pair will be treated as kvp.Item2 of 'Ensure' key
//
// configuration foo
// {
// File foo
// {
// DestinationPath = "\foo.txt"
// Ensure = |
// DependsOn =@("[User]x")
// }
// }
//
if (kvp.Item2.Extent.StartLineNumber > kvp.Item1.Extent.EndLineNumber &&
IsCursorAfterExtentAndInTheSameLine(cursor, kvp.Item1.Extent))
{
keyValuePairWithCursor = kvp;
break;
}
//
// If cursor is not within a string, then handle following two cases,
//
// #1) cursor is after '=', in the same line of previous key value pair
// configuration test{File testfile{DestinationPath='c:\test'; Ensure = |
//
// #2) cursor is after '=', in the separate line of previous key value pair
// configuration test{File testfile{DestinationPath='c:\test';
// Ensure = |
//
if (!IsCursorBeforeExtent(cursor, kvp.Item1.Extent) &&
IsCursorAfterExtentAndInTheSameLine(cursor, kvp.Item2.Extent))
{
keyValuePairWithCursor = kvp;
}
}
}
return keyValuePairWithCursor;
}
// Pulls the variable out of an assignment's LHS expression
// Also brings back the innermost type constraint if there is one
private static VariableExpressionAst GetVariableFromExpressionAst(
ExpressionAst expression,
ref Type typeConstraint,
ref ValidateSetAttribute setConstraint)
{
switch (expression)
{
// $x = ...
case VariableExpressionAst variableExpression:
return variableExpression;
// [type]$x = ...
case ConvertExpressionAst convertExpression:
typeConstraint = convertExpression.Type.TypeName.GetReflectionType();
return GetVariableFromExpressionAst(convertExpression.Child, ref typeConstraint, ref setConstraint);
// [attribute()][type]$x = ...
case AttributedExpressionAst attributedExpressionAst:
try
{
setConstraint = attributedExpressionAst.Attribute.GetAttribute() as ValidateSetAttribute;
}
catch
{
// Do nothing, just prevent fallout from an unsuccessful attribute conversion
}
return GetVariableFromExpressionAst(attributedExpressionAst.Child, ref typeConstraint, ref setConstraint);
// Something else, like `MemberExpressionAst` $a.p = <tab> which isn't currently handled
default:
return null;
}
}
// Gets any type constraints or validateset constraints on a given variable
private static bool TryGetTypeConstraintOnVariable(
CompletionContext completionContext,
string variableName,
out Type typeConstraint,
out ValidateSetAttribute setConstraint)
{
typeConstraint = null;
setConstraint = null;
PSVariable variable = completionContext.ExecutionContext.EngineSessionState.GetVariable(variableName);
if (variable == null || variable.Attributes.Count == 0)
{
return false;
}
foreach (Attribute attribute in variable.Attributes)
{
if (attribute is ArgumentTypeConverterAttribute typeConverterAttribute)
{
typeConstraint = typeConverterAttribute.TargetType;
continue;
}
if (attribute is ValidateSetAttribute validateSetAttribute)
{
setConstraint = validateSetAttribute;
}
}
return typeConstraint != null || setConstraint != null;
}
private static List<CompletionResult> CompletePropertyAssignment(MemberExpressionAst memberExpression, CompletionContext context)
{
if (SafeExprEvaluator.TrySafeEval(memberExpression, context.ExecutionContext, out var evalValue))
{
if (evalValue is not null)
{
Type type = evalValue.GetType();
if (type.IsEnum)
{
return GetResultForEnum(type, context);
}
return null;
}
}
_ = TryGetInferredCompletionsForAssignment(memberExpression, context, out List<CompletionResult> result);
return result;
}
private static bool TryGetInferredCompletionsForAssignment(Ast expression, CompletionContext context, out List<CompletionResult> result)
{
result = null;
IList<PSTypeName> inferredTypes;
if (expression.Parent is ConvertExpressionAst convertExpression)
{
inferredTypes = new PSTypeName[] { new(convertExpression.Type.TypeName) };
}
else if (expression is MemberExpressionAst)
{
inferredTypes = AstTypeInference.InferTypeOf(expression);
}
else if (expression is VariableExpressionAst varExpression)
{
PSTypeName typeConstraint = CompletionCompleters.GetLastDeclaredTypeConstraint(varExpression, context.TypeInferenceContext);
if (typeConstraint is null)
{
return false;
}
inferredTypes = new PSTypeName[] { typeConstraint };
}
else
{
return false;
}
if (inferredTypes.Count == 0)
{
return false;
}
var values = new SortedSet<string>();
foreach (PSTypeName type in inferredTypes)
{
Type loadedType = type.Type;
if (loadedType is not null)
{
if (loadedType.IsEnum)
{
foreach (string value in Enum.GetNames(loadedType))
{
_ = values.Add(value);
}
}
}
else if (type is not null && type.TypeDefinitionAst.IsEnum)
{
foreach (MemberAst member in type.TypeDefinitionAst.Members)
{
if (member is PropertyMemberAst property)
{
_ = values.Add(property.Name);
}
}
}
}
string wordToComplete;
if (string.IsNullOrEmpty(context.WordToComplete))
{
if (context.TokenAtCursor is not null && context.TokenAtCursor.Kind != TokenKind.Equals)
{
wordToComplete = context.TokenAtCursor.Text + "*";
}
else
{
wordToComplete = "*";
}
}
else
{
wordToComplete = context.WordToComplete + "*";
}
result = new List<CompletionResult>();
var pattern = new WildcardPattern(wordToComplete, WildcardOptions.IgnoreCase);
foreach (string name in values)
{
string quotedName = GetQuotedString(name, context);
if (pattern.IsMatch(quotedName))
{
result.Add(new CompletionResult(quotedName, name, CompletionResultType.Property, name));
}
}
if (result.Count == 0)
{
result = null;
return false;
}
return true;
}
private static bool TryGetCompletionsForVariableAssignment(
CompletionContext completionContext,
AssignmentStatementAst assignmentAst,
out List<CompletionResult> completions)
{
bool TryGetResultForEnum(Type typeConstraint, CompletionContext completionContext, out List<CompletionResult> completions)
{
completions = null;
if (typeConstraint != null && typeConstraint.IsEnum)
{
completions = GetResultForEnum(typeConstraint, completionContext);
return true;
}
return false;
}
bool TryGetResultForSet(Type typeConstraint, ValidateSetAttribute setConstraint, CompletionContext completionContext1, out List<CompletionResult> completions)
{
completions = null;
if (setConstraint?.ValidValues != null)
{
completions = GetResultForSet(typeConstraint, setConstraint.ValidValues, completionContext);
return true;
}
return false;
}
if (assignmentAst.Left is MemberExpressionAst member)
{
completions = CompletePropertyAssignment(member, completionContext);
return completions is not null;
}
completions = null;
// Try to get the variable from the assignment, plus any type constraint on it
Type typeConstraint = null;
ValidateSetAttribute setConstraint = null;
VariableExpressionAst variableAst = GetVariableFromExpressionAst(assignmentAst.Left, ref typeConstraint, ref setConstraint);
if (variableAst == null)
{
return false;
}
// Assignment constraints override any existing ones, so try them first
// Check any [ValidateSet()] constraint first since it's likely to be narrow
if (TryGetResultForSet(typeConstraint, setConstraint, completionContext, out completions))
{
return true;
}
// Then try to complete for an enum type
if (TryGetResultForEnum(typeConstraint, completionContext, out completions))
{
return true;
}
// If the assignment itself was unconstrained, the variable still might be
if (!TryGetTypeConstraintOnVariable(completionContext, variableAst.VariablePath.UserPath, out typeConstraint, out setConstraint))
{
return TryGetInferredCompletionsForAssignment(variableAst, completionContext, out completions);
}
// Again try the [ValidateSet()] constraint first
if (TryGetResultForSet(typeConstraint, setConstraint, completionContext, out completions))
{
return true;
}
// Then try to complete for an enum type again
if (TryGetResultForEnum(typeConstraint, completionContext, out completions))
{
return true;
}
return false;
}
private static List<CompletionResult> GetResultForSet(
Type typeConstraint,
IList<string> validValues,
CompletionContext completionContext)
{
var allValues = new List<string>();
foreach (string value in validValues)
{
if (typeConstraint != null && (typeConstraint == typeof(string) || typeConstraint.IsEnum))
{
allValues.Add(GetQuotedString(value, completionContext));
}
else
{
allValues.Add(value);
}
}
return GetMatchedResults(allValues, completionContext);
}
private static List<CompletionResult> GetMatchedResults(
List<string> allValues,
CompletionContext completionContext)
{
var stringToComplete = string.Empty;
if (completionContext.TokenAtCursor != null && completionContext.TokenAtCursor.Kind != TokenKind.Equals)
{
stringToComplete = completionContext.TokenAtCursor.Text;
}
IEnumerable<string> matchedResults = null;
if (!string.IsNullOrEmpty(stringToComplete))
{
string matchString = stringToComplete + "*";
var wildcardPattern = WildcardPattern.Get(matchString, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
matchedResults = allValues.Where(r => wildcardPattern.IsMatch(r));
}
else
{
matchedResults = allValues;
}
var result = new List<CompletionResult>();
foreach (var match in matchedResults)
{
result.Add(new CompletionResult(match));
}
return result;
}
private static string GetQuotedString(
string value,
CompletionContext completionContext)
{
var stringToComplete = string.Empty;
if (completionContext.TokenAtCursor != null)
{
stringToComplete = completionContext.TokenAtCursor.Text;
}
var quote = stringToComplete.StartsWith('"') ? "\"" : "'";
return quote + value + quote;
}
private static List<CompletionResult> GetResultForEnum(
Type type,
CompletionContext completionContext)
{
var allNames = new List<string>();
foreach (var name in Enum.GetNames(type))
{
allNames.Add(GetQuotedString(name, completionContext));
}
allNames.Sort();
return GetMatchedResults(allNames, completionContext);
}
private static List<CompletionResult> GetResultForEnumPropertyValueOfDSCResource(
CompletionContext completionContext,
string stringToComplete,
ref int replacementIndex,
ref int replacementLength,
out bool shouldContinue)
{
shouldContinue = true;
bool isCursorInString = completionContext.TokenAtCursor is StringToken;
List<CompletionResult> result = null;
var lastAst = completionContext.RelatedAsts.Last();
Ast lastChildofHashtableAst;
var hashTableAst = Ast.GetAncestorHashtableAst(lastAst, out lastChildofHashtableAst);
Diagnostics.Assert(stringToComplete != null, "stringToComplete should never be null");
// Check if the hashtable within a DynamicKeyword statement
if (hashTableAst != null)
{
var keywordAst = Ast.GetAncestorAst<DynamicKeywordStatementAst>(hashTableAst);
if (keywordAst != null)
{
IScriptPosition cursor = completionContext.CursorPosition;
var keyValuePairWithCursor = GetHashEntryContainsCursor(cursor, hashTableAst, isCursorInString);
if (keyValuePairWithCursor != null)
{
var propertyNameAst = keyValuePairWithCursor.Item1 as StringConstantExpressionAst;
if (propertyNameAst != null)
{
DynamicKeywordProperty property;
if (keywordAst.Keyword.Properties.TryGetValue(propertyNameAst.Value, out property))
{
List<string> existingValues = null;
WildcardPattern wildcardPattern = null;
bool isDependsOnProperty = string.Equals(property.Name, @"DependsOn", StringComparison.OrdinalIgnoreCase);
bool hasNewLine = false;
string stringQuote = (completionContext.TokenAtCursor is StringExpandableToken) ? "\"" : "'";
if ((property.ValueMap != null && property.ValueMap.Count > 0) || isDependsOnProperty)
{
shouldContinue = false;
existingValues = new List<string>();
if (string.Equals(property.TypeConstraint, "StringArray", StringComparison.OrdinalIgnoreCase))
{
var arrayAst = Ast.GetAncestorAst<ArrayLiteralAst>(lastAst);
if (arrayAst != null && arrayAst.Elements.Count > 0)
{
foreach (ExpressionAst expression in arrayAst.Elements)
{
//
// stringAst can be null in following case
// DependsOn='[user]x',|
//
var stringAst = expression as StringConstantExpressionAst;
if (stringAst != null && IsCursorOutsideOfExtent(cursor, expression.Extent))
{
existingValues.Add(stringAst.Value);
}
}
}
}
//
// Make sure only auto-complete string value in current line
//
stringToComplete = GetFirstLineSubString(stringToComplete, out hasNewLine);
completionContext.WordToComplete = stringToComplete;
replacementLength = completionContext.ReplacementLength = stringToComplete.Length;
//
// Calculate the replacementIndex based on cursor location (relative to the string token)
//
if (completionContext.TokenAtCursor is StringToken)
{
replacementIndex = completionContext.TokenAtCursor.Extent.StartOffset + 1;
}
else
{
replacementIndex = completionContext.CursorPosition.Offset - replacementLength;
}
completionContext.ReplacementIndex = replacementIndex;
string matchString = stringToComplete + "*";
wildcardPattern = WildcardPattern.Get(matchString, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
result = new List<CompletionResult>();
}
Diagnostics.Assert(isCursorInString || (!hasNewLine), "hasNoQuote and hasNewLine cannot be true at the same time");
if (property.ValueMap != null && property.ValueMap.Count > 0)
{
IEnumerable<string> orderedValues = property.ValueMap.Keys.Order().Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase));
var matchedResults = orderedValues.Where(v => wildcardPattern.IsMatch(v));
if (matchedResults == null || !matchedResults.Any())
{
// Fallback to all allowed values
matchedResults = orderedValues;
}
foreach (var value in matchedResults)
{
string completionText = isCursorInString ? value : stringQuote + value + stringQuote;
if (hasNewLine)
completionText += stringQuote;
result.Add(new CompletionResult(
completionText,
value,
CompletionResultType.Text,
value));
}
}
else if (isDependsOnProperty)
{
var configAst = Ast.GetAncestorAst<ConfigurationDefinitionAst>(keywordAst);
if (configAst != null)
{
var namedBlockAst = Ast.GetAncestorAst<NamedBlockAst>(keywordAst);
if (namedBlockAst != null)
{
List<string> allResources = new List<string>();
foreach (var statementAst in namedBlockAst.Statements)
{
var dynamicKeywordAst = statementAst as DynamicKeywordStatementAst;
if (dynamicKeywordAst != null &&
dynamicKeywordAst != keywordAst &&
!string.Equals(dynamicKeywordAst.Keyword.Keyword, @"Node", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(dynamicKeywordAst.ElementName))
{
StringBuilder sb = new StringBuilder("[", 50);
sb.Append(dynamicKeywordAst.Keyword.Keyword);
sb.Append(']');
sb.Append(dynamicKeywordAst.ElementName);
var resource = sb.ToString();
if (!existingValues.Contains(resource, StringComparer.OrdinalIgnoreCase) &&
!allResources.Contains(resource, StringComparer.OrdinalIgnoreCase))
{
allResources.Add(resource);
}
}
}
}
var matchedResults = allResources.Where(r => wildcardPattern.IsMatch(r));
if (matchedResults == null || !matchedResults.Any())
{
// Fallback to all allowed values
matchedResults = allResources;
}
foreach (var resource in matchedResults)
{
string completionText = isCursorInString ? resource : stringQuote + resource + stringQuote;
if (hasNewLine)
completionText += stringQuote;
result.Add(new CompletionResult(
completionText,
resource,
CompletionResultType.Text,
resource));
}
}
}
}
}
}
}
}
}
return result;
}
private static List<CompletionResult> GetResultForString(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength)
{
var lastAst = completionContext.RelatedAsts.Last();
var expandableString = lastAst as ExpandableStringExpressionAst;
var constantString = lastAst as StringConstantExpressionAst;
if (constantString == null && expandableString == null) { return null; }
string strValue = constantString != null ? constantString.Value : expandableString.Value;
// Check for switch case completion on $PSBoundParameters.Keys
completionContext.WordToComplete = strValue;
var switchCaseResult = CompleteAgainstSwitchCaseCondition(completionContext);
if (switchCaseResult != null && switchCaseResult.Count > 0)
{
return switchCaseResult;
}
// Check for $PSBoundParameters access patterns (ContainsKey, indexer, Remove)
var psBoundResult = CompleteAgainstPSBoundParametersAccess(completionContext);
if (psBoundResult != null && psBoundResult.Count > 0)
{
return psBoundResult;
}
bool shouldContinue;
List<CompletionResult> result = GetResultForEnumPropertyValueOfDSCResource(completionContext, strValue, ref replacementIndex, ref replacementLength, out shouldContinue);
if (!shouldContinue || (result != null && result.Count > 0))
{
return result;
}
var commandElementAst = lastAst as CommandElementAst;
string wordToComplete =
CompletionCompleters.ConcatenateStringPathArguments(commandElementAst, string.Empty, completionContext);
if (wordToComplete != null)
{
completionContext.WordToComplete = wordToComplete;
// Handle scenarios like this: cd 'c:\windows\win'<tab>
if (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst)
{
result = CompletionCompleters.CompleteCommandArgument(completionContext);
replacementIndex = completionContext.ReplacementIndex;
replacementLength = completionContext.ReplacementLength;
}
// Handle scenarios like this: "c:\wind"<tab>. Treat the StringLiteral/StringExpandable as path/command
else
{
// Handle path/commandname completion for quoted string
result = new List<CompletionResult>(CompletionCompleters.CompleteFilename(completionContext));
// Try command name completion only if the text contains '-'
if (wordToComplete.Contains('-'))
{
var commandNameResult = CompletionCompleters.CompleteCommand(completionContext);
if (commandNameResult != null && commandNameResult.Count > 0)
{
result.AddRange(commandNameResult);
}
}
}
}
return result;
}
/// <summary>
/// Find the configuration statement contains current cursor.
/// </summary>
/// <param name="cursorPosition"></param>
/// <param name="ast"></param>
/// <param name="keywordAst"></param>
/// <returns></returns>
private static ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst(
IScriptPosition cursorPosition,
Ast ast,
out DynamicKeywordStatementAst keywordAst)
{
ConfigurationDefinitionAst configureAst = Ast.GetAncestorConfigurationDefinitionAstAndDynamicKeywordStatementAst(ast, out keywordAst);
// Find the configuration statement contains current cursor
// Note: cursorPosition.Offset < configureAst.Extent.EndOffset means cursor locates inside the configuration
// cursorPosition.Offset = configureAst.Extent.EndOffset means cursor locates at the end of the configuration
while (configureAst != null && cursorPosition.Offset > configureAst.Extent.EndOffset)
{
configureAst = Ast.GetAncestorAst<ConfigurationDefinitionAst>(configureAst.Parent);
}
return configureAst;
}
/// <summary>
/// Generate auto complete results for identifier within configuration.
/// Results are generated based on DynamicKeywords matches given identifier.
/// For example, following "Fi" matches "File", and "Us" matches "User"
///
/// Configuration
/// {
/// Fi^
/// Node("TargetMachine")
/// {
/// Us^
/// }
/// }
/// </summary>
/// <param name="completionContext"></param>
/// <param name="configureAst"></param>
/// <param name="keywordAst"></param>
/// <param name="matched"></param>
/// <returns></returns>
private static List<CompletionResult> GetResultForIdentifierInConfiguration(
CompletionContext completionContext,
ConfigurationDefinitionAst configureAst,
DynamicKeywordStatementAst keywordAst,
out bool matched)
{
List<CompletionResult> results = null;
matched = false;
IEnumerable<DynamicKeyword> keywords = configureAst.DefinedKeywords.Where(
k => // Node is special case, legal in both Resource and Meta configuration
string.Equals(k.Keyword, @"Node", StringComparison.OrdinalIgnoreCase) ||
(
// Check compatibility between Resource and Configuration Type
k.IsCompatibleWithConfigurationType(configureAst.ConfigurationType) &&
!DynamicKeyword.IsHiddenKeyword(k.Keyword) &&
!k.IsReservedKeyword
)
);
if (keywordAst != null && completionContext.CursorPosition.Offset < keywordAst.Extent.EndOffset)
keywords = keywordAst.Keyword.GetAllowedKeywords(keywords);
if (keywords != null && keywords.Any())
{
string commandName = (completionContext.WordToComplete ?? string.Empty) + "*";
var wildcardPattern = WildcardPattern.Get(commandName, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
// Filter by name
var matchedResults = keywords.Where(k => wildcardPattern.IsMatch(k.Keyword));
if (matchedResults == null || !matchedResults.Any())
{
// Fallback to all legal keywords in the configuration statement
matchedResults = keywords;
}
else
{
matched = true;
}
foreach (var keyword in matchedResults)
{
string usageString = string.Empty;
ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem<ICrossPlatformDsc>();
if (dscSubsystem != null)
{
usageString = dscSubsystem.GetDSCResourceUsageString(keyword);
}
else
{
usageString = Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.GetDSCResourceUsageString(keyword);
}
results ??= new List<CompletionResult>();
results.Add(new CompletionResult(
keyword.Keyword,
keyword.Keyword,
CompletionResultType.DynamicKeyword,
usageString));
}
}
return results;
}
private static List<CompletionResult> GetResultForIdentifier(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength)
{
List<CompletionResult> result = null;
var tokenAtCursor = completionContext.TokenAtCursor;
var lastAst = completionContext.RelatedAsts.Last();
var tokenAtCursorText = tokenAtCursor.Text;
completionContext.WordToComplete = tokenAtCursorText;
// Check for switch case completion on $PSBoundParameters.Keys
var switchCaseResult = CompleteAgainstSwitchCaseCondition(completionContext);
if (switchCaseResult != null && switchCaseResult.Count > 0)
{
return switchCaseResult;
}
// Check for $PSBoundParameters access patterns (ContainsKey, indexer, Remove)
var psBoundResult = CompleteAgainstPSBoundParametersAccess(completionContext);
if (psBoundResult != null && psBoundResult.Count > 0)
{
return psBoundResult;
}
if (lastAst.Parent is BreakStatementAst || lastAst.Parent is ContinueStatementAst)
{
return CompleteLoopLabel(completionContext);
}
var strConst = lastAst as StringConstantExpressionAst;
if (strConst != null)
{
if (strConst.Value.Equals("$", StringComparison.Ordinal))
{
completionContext.WordToComplete = string.Empty;
return CompletionCompleters.CompleteVariable(completionContext);
}
else
{
UsingStatementAst usingState = strConst.Parent as UsingStatementAst;
if (usingState != null)
{
completionContext.ReplacementIndex = strConst.Extent.StartOffset;
completionContext.ReplacementLength = strConst.Extent.EndOffset - replacementIndex;
completionContext.WordToComplete = strConst.Extent.Text;
switch (usingState.UsingStatementKind)
{
case UsingStatementKind.Assembly:
HashSet<string> assemblyExtensions = new(StringComparer.OrdinalIgnoreCase)
{
StringLiterals.PowerShellILAssemblyExtension
};
return CompletionCompleters.CompleteFilename(completionContext, containerOnly: false, assemblyExtensions).ToList();
case UsingStatementKind.Command:
break;
case UsingStatementKind.Module:
var moduleExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
StringLiterals.PowerShellModuleFileExtension,
StringLiterals.PowerShellDataFileExtension,
StringLiterals.PowerShellNgenAssemblyExtension,
StringLiterals.PowerShellILAssemblyExtension,
StringLiterals.PowerShellILExecutableExtension,
StringLiterals.PowerShellCmdletizationFileExtension
};
result = CompletionCompleters.CompleteFilename(completionContext, false, moduleExtensions).ToList();
if (completionContext.WordToComplete.IndexOfAny(Utils.Separators.DirectoryOrDrive) != -1)
{
// The partial input is a path, then we don't iterate modules under $ENV:PSModulePath
return result;
}
var moduleResults = CompletionCompleters.CompleteModuleName(completionContext, false);
if (moduleResults != null && moduleResults.Count > 0)
result.AddRange(moduleResults);
return result;
case UsingStatementKind.Namespace:
result = CompletionCompleters.CompleteNamespace(completionContext);
return result;
case UsingStatementKind.Type:
break;
default:
throw new ArgumentOutOfRangeException("UsingStatementKind");
}
}
}
}
if (completionContext.TokenAtCursor.TokenFlags == TokenFlags.MemberName)
{
if (lastAst is NamedAttributeArgumentAst || lastAst.Parent is NamedAttributeArgumentAst)
{
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
}
else if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0)
{
foreach (AttributeBaseAst attribute in paramAst.Attributes)
{
if (IsCursorWithinOrJustAfterExtent(completionContext.CursorPosition, attribute.Extent))
{
result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength);
break;
}
}
}
if (result is not null)
{
return result;
}
}
if ((tokenAtCursor.TokenFlags & TokenFlags.CommandName) != 0)
{
// Handle completion for a path with variable, such as: $PSHOME\ty<tab>
if (completionContext.RelatedAsts.Count > 0 && completionContext.RelatedAsts[0] is ScriptBlockAst)
{
Ast cursorAst = completionContext.RelatedAsts[0].FindAll(
ast => ast.Extent.EndOffset <= tokenAtCursor.Extent.StartOffset
&& ast.Extent is not EmptyScriptExtent,
searchNestedScriptBlocks: true).LastOrDefault();
if (cursorAst is not null)
{
if (cursorAst.Extent.EndOffset == tokenAtCursor.Extent.StartOffset)
{
if (tokenAtCursorText.AsSpan().IndexOfAny('\\', '/') == 0)
{
string wordToComplete =
CompletionCompleters.ConcatenateStringPathArguments(cursorAst as CommandElementAst, tokenAtCursorText, completionContext);
if (wordToComplete != null)
{
completionContext.WordToComplete = wordToComplete;
result = new List<CompletionResult>(CompletionCompleters.CompleteFilename(completionContext));
if (result.Count > 0)
{
replacementIndex = cursorAst.Extent.StartScriptPosition.Offset;
replacementLength += cursorAst.Extent.Text.Length;
}
return result;
}
else
{
var variableAst = cursorAst as VariableExpressionAst;
string fullPath = variableAst != null
? CompletionCompleters.CombineVariableWithPartialPath(
variableAst: variableAst,
extraText: tokenAtCursorText,
executionContext: completionContext.ExecutionContext)
: null;
if (fullPath == null) { return result; }
// Continue trying the filename/commandname completion for scenarios like this: $aa\d<tab>
completionContext.WordToComplete = fullPath;
replacementIndex = cursorAst.Extent.StartScriptPosition.Offset;
replacementLength += cursorAst.Extent.Text.Length;
completionContext.ReplacementIndex = replacementIndex;
completionContext.ReplacementLength = replacementLength;
}
}
// Continue trying the filename/commandname completion for scenarios like this: $aa[get-<tab>
else if (cursorAst is not ErrorExpressionAst || cursorAst.Parent is not IndexExpressionAst)
{
return result;
}
}
if (cursorAst.Parent is IndexExpressionAst indexExpression && indexExpression.Index is ErrorExpressionAst)
{
if (completionContext.WordToComplete.EndsWith(']'))
{
completionContext.WordToComplete = completionContext.WordToComplete.Remove(completionContext.WordToComplete.Length - 1);
}
// Handles index expression with unquoted word like: $PSVersionTable[psver<Tab>]
return CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target);
}
}
}
// Handle the StringExpandableToken;
var strToken = tokenAtCursor as StringExpandableToken;
if (strToken != null && strToken.NestedTokens != null && strConst != null)
{
try
{
string expandedString = null;
var expandableStringAst = new ExpandableStringExpressionAst(strConst.Extent, strConst.Value, StringConstantType.BareWord);
if (CompletionCompleters.IsPathSafelyExpandable(expandableStringAst: expandableStringAst,
extraText: string.Empty,
executionContext: completionContext.ExecutionContext,
expandedString: out expandedString))
{
completionContext.WordToComplete = expandedString;
}
else
{
return result;
}
}
catch (Exception)
{
return result;
}
}
//
// Handle completion of DSC resources within Configuration
//
DynamicKeywordStatementAst keywordAst;
ConfigurationDefinitionAst configureAst = GetAncestorConfigurationAstAndKeywordAst(completionContext.CursorPosition, lastAst, out keywordAst);
bool matched = false;
List<CompletionResult> keywordResult = null;
if (configureAst != null)
{
// Current token is within ConfigurationDefinitionAst or DynamicKeywordStatementAst
keywordResult = GetResultForIdentifierInConfiguration(completionContext, configureAst, keywordAst, out matched);
}
// Handle the file completion before command name completion
result = CompleteFileNameAsCommand(completionContext);
// Handle the command name completion
var commandNameResult = CompletionCompleters.CompleteCommand(completionContext);
if (commandNameResult != null && commandNameResult.Count > 0)
{
result.AddRange(commandNameResult);
}
if (matched && keywordResult != null)
{
result.InsertRange(0, keywordResult);
}
else if (!matched && keywordResult != null && commandNameResult.Count == 0)
{
result.AddRange(keywordResult);
}
return result;
}
var isSingleDash = tokenAtCursorText.Length == 1 && tokenAtCursorText[0].IsDash();
var isDoubleDash = tokenAtCursorText.Length == 2 && tokenAtCursorText[0].IsDash() && tokenAtCursorText[1].IsDash();
var isParentCommandOrDynamicKeyword = (lastAst.Parent is CommandAst || lastAst.Parent is DynamicKeywordStatementAst);
if ((isSingleDash || isDoubleDash) && isParentCommandOrDynamicKeyword)
{
// When it's the content of a quoted string, we only handle variable/member completion
if (isSingleDash)
{
var res = CompletionCompleters.CompleteCommandParameter(completionContext);
if (res.Count != 0)
{
return res;
}
}
return CompletionCompleters.CompleteCommandArgument(completionContext);
}
TokenKind memberOperator = TokenKind.Unknown;
bool isMemberCompletion = lastAst.Parent is MemberExpressionAst;
bool isStatic = false;
if (isMemberCompletion)
{
var currentExpression = (MemberExpressionAst)lastAst.Parent;
// Handles following scenario with an incomplete member access token at the end of the statement:
// [System.IO.FileInfo]::new<Tab>().Directory.BaseName.Length.
// Traverses up the expressions until it finds one under at the cursor
while (currentExpression.Extent.EndOffset >= completionContext.CursorPosition.Offset
&& currentExpression.Expression is MemberExpressionAst memberExpression
&& memberExpression.Member.Extent.EndOffset >= completionContext.CursorPosition.Offset)
{
currentExpression = memberExpression;
}
isStatic = currentExpression.Static;
}
bool isWildcard = false;
if (!isMemberCompletion)
{
// Still might be member completion, something like: echo $member.
// We need to know if the previous element before the token is adjacent because
// we don't have a MemberExpressionAst, we might have 2 command arguments.
if (tokenAtCursorText.Equals(TokenKind.Dot.Text(), StringComparison.Ordinal))
{
memberOperator = TokenKind.Dot;
isMemberCompletion = true;
}
else if (tokenAtCursorText.Equals(TokenKind.ColonColon.Text(), StringComparison.Ordinal))
{
memberOperator = TokenKind.ColonColon;
isMemberCompletion = true;
}
else if (tokenAtCursor.Kind.Equals(TokenKind.Multiply) && lastAst is BinaryExpressionAst)
{
// Handle member completion with wildcard(wildcard is at the end): $a.p*
var binaryExpressionAst = (BinaryExpressionAst)lastAst;
var memberExpressionAst = binaryExpressionAst.Left as MemberExpressionAst;
var errorPosition = binaryExpressionAst.ErrorPosition;
if (memberExpressionAst != null && binaryExpressionAst.Operator == TokenKind.Multiply &&
errorPosition.StartOffset == memberExpressionAst.Member.Extent.EndOffset)
{
isStatic = memberExpressionAst.Static;
memberOperator = isStatic ? TokenKind.ColonColon : TokenKind.Dot;
isMemberCompletion = true;
isWildcard = true;
// Member completion will add back the '*', so pretend it wasn't there, at least from the "related asts" point of view,
// but add the member expression that we are really completing.
completionContext.RelatedAsts.Remove(binaryExpressionAst);
completionContext.RelatedAsts.Add(memberExpressionAst);
var memberAst = memberExpressionAst.Member as StringConstantExpressionAst;
if (memberAst != null)
{
replacementIndex = memberAst.Extent.StartScriptPosition.Offset;
replacementLength += memberAst.Extent.Text.Length;
}
}
}
}
if (isMemberCompletion)
{
result = CompletionCompleters.CompleteMember(completionContext, @static: (isStatic || memberOperator == TokenKind.ColonColon), ref replacementLength);
// If the last token was just a '.', we tried to complete members. That may
// have failed because it wasn't really an attempt to complete a member, in
// which case we should try to complete as an argument.
if (result.Count > 0)
{
if (!isWildcard && memberOperator != TokenKind.Unknown)
{
replacementIndex += tokenAtCursorText.Length;
replacementLength = 0;
}
return result;
}
}
if (lastAst.Parent is HashtableAst)
{
result = CompletionCompleters.CompleteHashtableKey(completionContext, (HashtableAst)lastAst.Parent);
if (result != null && result.Count > 0)
{
return result;
}
}
bool needFileCompletion = false;
if (lastAst.Parent is FileRedirectionAst || CompleteAgainstSwitchFile(lastAst, completionContext.TokenBeforeCursor))
{
string wordToComplete =
CompletionCompleters.ConcatenateStringPathArguments(lastAst as CommandElementAst, string.Empty, completionContext);
if (wordToComplete != null)
{
needFileCompletion = true;
completionContext.WordToComplete = wordToComplete;
}
}
else if (tokenAtCursorText.AsSpan().IndexOfAny('\\', '/') == 0)
{
var command = lastAst.Parent as CommandBaseAst;
if (command != null && command.Redirections.Count > 0)
{
var fileRedirection = command.Redirections[0] as FileRedirectionAst;
if (fileRedirection != null &&
fileRedirection.Extent.EndLineNumber == lastAst.Extent.StartLineNumber &&
fileRedirection.Extent.EndColumnNumber == lastAst.Extent.StartColumnNumber)
{
string wordToComplete =
CompletionCompleters.ConcatenateStringPathArguments(fileRedirection.Location, tokenAtCursorText, completionContext);
if (wordToComplete != null)
{
needFileCompletion = true;
completionContext.WordToComplete = wordToComplete;
replacementIndex = fileRedirection.Location.Extent.StartScriptPosition.Offset;
replacementLength += fileRedirection.Location.Extent.EndScriptPosition.Offset - replacementIndex;
completionContext.ReplacementIndex = replacementIndex;
completionContext.ReplacementLength = replacementLength;
}
}
}
}
if (needFileCompletion)
{
return new List<CompletionResult>(CompletionCompleters.CompleteFilename(completionContext));
}
else
{
string wordToComplete =
CompletionCompleters.ConcatenateStringPathArguments(lastAst as CommandElementAst, string.Empty, completionContext);
if (wordToComplete != null)
{
completionContext.WordToComplete = wordToComplete;
}
}
result = CompletionCompleters.CompleteCommandArgument(completionContext);
replacementIndex = completionContext.ReplacementIndex;
replacementLength = completionContext.ReplacementLength;
return result;
}
private static List<CompletionResult> GetResultForAttributeArgument(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength)
{
// Attribute member arguments
Type attributeType = null;
string argName = string.Empty;
Ast argAst = completionContext.RelatedAsts.Find(static ast => ast is NamedAttributeArgumentAst);
AttributeAst attAst;
if (argAst is NamedAttributeArgumentAst namedArgAst)
{
attAst = (AttributeAst)namedArgAst.Parent;
attributeType = attAst.TypeName.GetReflectionAttributeType();
argName = namedArgAst.ArgumentName;
replacementIndex = namedArgAst.Extent.StartOffset;
replacementLength = argName.Length;
}
else
{
Ast astAtt = completionContext.RelatedAsts.Find(static ast => ast is AttributeAst);
attAst = astAtt as AttributeAst;
if (attAst is not null)
{
attributeType = attAst.TypeName.GetReflectionAttributeType();
}
}
if (attributeType is not null)
{
int cursorPosition = completionContext.CursorPosition.Offset;
var existingArguments = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var namedArgument in attAst.NamedArguments)
{
if (cursorPosition < namedArgument.Extent.StartOffset || cursorPosition > namedArgument.Extent.EndOffset)
{
existingArguments.Add(namedArgument.ArgumentName);
}
}
PropertyInfo[] propertyInfos = attributeType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
List<CompletionResult> result = new List<CompletionResult>();
foreach (PropertyInfo property in propertyInfos)
{
// Ignore getter-only properties and properties that have already been set.
if (!property.CanWrite || existingArguments.Contains(property.Name))
{
continue;
}
if (property.Name.StartsWith(argName, StringComparison.OrdinalIgnoreCase))
{
result.Add(new CompletionResult(property.Name, property.Name, CompletionResultType.Property,
property.PropertyType.ToString() + " " + property.Name));
}
}
return result;
}
return null;
}
/// <summary>
/// Complete file name as command.
/// </summary>
/// <param name="completionContext"></param>
/// <returns></returns>
private static List<CompletionResult> CompleteFileNameAsCommand(CompletionContext completionContext)
{
var addAmpersandIfNecessary = CompletionCompleters.IsAmpersandNeeded(completionContext, true);
var result = new List<CompletionResult>();
var clearLiteralPathsKey = false;
if (completionContext.Options == null)
{
completionContext.Options = new Hashtable { { "LiteralPaths", true } };
}
else if (!completionContext.Options.ContainsKey("LiteralPaths"))
{
// Dont escape '[',']','`' when the file name is treated as command name
completionContext.Options.Add("LiteralPaths", true);
clearLiteralPathsKey = true;
}
try
{
var fileNameResult = CompletionCompleters.CompleteFilename(completionContext);
foreach (var entry in fileNameResult)
{
// Add '&' to file names that are quoted
var completionText = entry.CompletionText;
var len = completionText.Length;
if (addAmpersandIfNecessary && len > 2 && completionText[0].IsSingleQuote() && completionText[len - 1].IsSingleQuote())
{
completionText = "& " + completionText;
result.Add(new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip));
}
else
{
result.Add(entry);
}
}
}
finally
{
if (clearLiteralPathsKey)
completionContext.Options.Remove("LiteralPaths");
}
return result;
}
/// <summary>
/// Complete loop labels after labeled control flow statements such as Break and Continue.
/// </summary>
private static List<CompletionResult> CompleteLoopLabel(CompletionContext completionContext)
{
var result = new List<CompletionResult>();
foreach (Ast ast in completionContext.RelatedAsts)
{
if (ast is LabeledStatementAst labeledStatement
&& labeledStatement.Label is not null
&& (completionContext.WordToComplete is null || labeledStatement.Label.StartsWith(completionContext.WordToComplete, StringComparison.OrdinalIgnoreCase)))
{
result.Add(new CompletionResult(labeledStatement.Label, labeledStatement.Label, CompletionResultType.Text, labeledStatement.Extent.Text));
}
else if (ast is ErrorStatementAst errorStatement)
{
// Handles incomplete do/switch loops (other labeled statements do not need this special treatment)
// The regex looks for the loopLabel of errorstatements that look like do/switch loops
// For example in ":Label do " it will find "Label".
var labelMatch = Regex.Match(errorStatement.Extent.Text, @"(?<=^:)\w+(?=\s+(do|switch)\b(?!-))", RegexOptions.IgnoreCase);
if (labelMatch.Success)
{
result.Add(new CompletionResult(labelMatch.Value, labelMatch.Value, CompletionResultType.Text, errorStatement.Extent.Text));
}
}
}
if (result.Count == 0)
{
return null;
}
return result;
}
private static List<CompletionResult> CompleteUsingKeywords(int cursorOffset, Token[] tokens, ref int replacementIndex, ref int replacementLength)
{
var result = new List<CompletionResult>();
Token tokenBeforeCursor = null;
Token tokenAtCursor = null;
for (int i = tokens.Length - 1; i >= 0; i--)
{
if (tokens[i].Extent.EndOffset < cursorOffset && tokens[i].Kind != TokenKind.LineContinuation)
{
tokenBeforeCursor = tokens[i];
break;
}
else if (tokens[i].Extent.StartOffset <= cursorOffset && tokens[i].Extent.EndOffset >= cursorOffset && tokens[i].Kind != TokenKind.LineContinuation)
{
tokenAtCursor = tokens[i];
}
}
if (tokenBeforeCursor is not null && tokenBeforeCursor.Kind == TokenKind.Using)
{
string wordToComplete = null;
if (tokenAtCursor is not null)
{
replacementIndex = tokenAtCursor.Extent.StartOffset;
replacementLength = tokenAtCursor.Extent.Text.Length;
wordToComplete = tokenAtCursor.Text;
}
else
{
replacementIndex = cursorOffset;
replacementLength = 0;
}
foreach (var keyword in s_usingKeywords)
{
if (string.IsNullOrEmpty(wordToComplete) || keyword.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))
{
result.Add(new CompletionResult(keyword, keyword, CompletionResultType.Keyword, GetUsingKeywordToolTip(keyword)));
}
}
}
if (result.Count > 0)
{
return result;
}
return null;
}
private static string GetUsingKeywordToolTip(string keyword)
{
switch (keyword)
{
case "assembly":
return TabCompletionStrings.AssemblyKeywordDescription;
case "module":
return TabCompletionStrings.ModuleKeywordDescription;
case "namespace":
return TabCompletionStrings.NamespaceKeywordDescription;
case "type":
return TabCompletionStrings.TypeKeywordDescription;
default:
return null;
}
}
private static readonly string[] s_usingKeywords = new string[]
{
"assembly",
"module",
"namespace",
"type"
};
}
}
|