File size: 89,328 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Text;
namespace System.Management.Automation.Language
{
#region "AstArgumentPair"
/// <summary>
/// The types for AstParameterArgumentPair.
/// </summary>
internal enum AstParameterArgumentType
{
AstPair = 0,
Switch = 1,
Fake = 2,
AstArray = 3,
PipeObject = 4
}
/// <summary>
/// The base class for parameter argument pair.
/// </summary>
internal abstract class AstParameterArgumentPair
{
/// <summary>
/// The parameter Ast.
/// </summary>
public CommandParameterAst Parameter { get; protected set; }
/// <summary>
/// The argument type.
/// </summary>
public AstParameterArgumentType ParameterArgumentType { get; protected set; }
/// <summary>
/// Indicate if the parameter is specified.
/// </summary>
public bool ParameterSpecified { get; protected set; } = false;
/// <summary>
/// Indicate if the parameter is specified.
/// </summary>
public bool ArgumentSpecified { get; protected set; } = false;
/// <summary>
/// The parameter name.
/// </summary>
public string ParameterName { get; protected set; }
/// <summary>
/// The parameter text.
/// </summary>
public string ParameterText { get; protected set; }
/// <summary>
/// The argument type.
/// </summary>
public Type ArgumentType { get; protected set; }
}
/// <summary>
/// Represent a parameter argument pair. The argument is a pipeline input object.
/// </summary>
internal sealed class PipeObjectPair : AstParameterArgumentPair
{
internal PipeObjectPair(string parameterName, Type pipeObjType)
{
if (parameterName == null)
throw PSTraceSource.NewArgumentNullException(nameof(parameterName));
Parameter = null;
ParameterArgumentType = AstParameterArgumentType.PipeObject;
ParameterSpecified = true;
ArgumentSpecified = true;
ParameterName = parameterName;
ParameterText = parameterName;
ArgumentType = pipeObjType;
}
}
/// <summary>
/// Represent a parameter argument pair. The argument is an array of ExpressionAst (remaining
/// arguments)
/// </summary>
internal sealed class AstArrayPair : AstParameterArgumentPair
{
internal AstArrayPair(string parameterName, ICollection<ExpressionAst> arguments)
{
if (parameterName == null)
throw PSTraceSource.NewArgumentNullException(nameof(parameterName));
if (arguments == null || arguments.Count == 0)
throw PSTraceSource.NewArgumentNullException(nameof(arguments));
Parameter = null;
ParameterArgumentType = AstParameterArgumentType.AstArray;
ParameterSpecified = true;
ArgumentSpecified = true;
ParameterName = parameterName;
ParameterText = parameterName;
ArgumentType = typeof(Array);
Argument = arguments.ToArray();
}
/// <summary>
/// Get the argument.
/// </summary>
public ExpressionAst[] Argument { get; } = null;
}
/// <summary>
/// Represent a parameter argument pair. The argument is a fake object.
/// </summary>
internal sealed class FakePair : AstParameterArgumentPair
{
internal FakePair(CommandParameterAst parameterAst)
{
if (parameterAst == null)
throw PSTraceSource.NewArgumentNullException(nameof(parameterAst));
Parameter = parameterAst;
ParameterArgumentType = AstParameterArgumentType.Fake;
ParameterSpecified = true;
ArgumentSpecified = true;
ParameterName = parameterAst.ParameterName;
ParameterText = parameterAst.ParameterName;
ArgumentType = typeof(object);
}
}
/// <summary>
/// Represent a parameter argument pair. The parameter is a switch parameter.
/// </summary>
internal sealed class SwitchPair : AstParameterArgumentPair
{
internal SwitchPair(CommandParameterAst parameterAst)
{
if (parameterAst == null)
throw PSTraceSource.NewArgumentNullException(nameof(parameterAst));
Parameter = parameterAst;
ParameterArgumentType = AstParameterArgumentType.Switch;
ParameterSpecified = true;
ArgumentSpecified = true;
ParameterName = parameterAst.ParameterName;
ParameterText = parameterAst.ParameterName;
ArgumentType = typeof(bool);
}
/// <summary>
/// Get the argument.
/// </summary>
public bool Argument
{
get { return true; }
}
}
/// <summary>
/// Represent a parameter argument pair. It could be a pure argument (no parameter, only argument available);
/// it could be a CommandParameterAst that contains its argument; it also could be a CommandParameterAst with
/// another CommandParameterAst as the argument.
/// </summary>
internal sealed class AstPair : AstParameterArgumentPair
{
internal AstPair(CommandParameterAst parameterAst)
{
if (parameterAst == null || parameterAst.Argument == null)
throw PSTraceSource.NewArgumentException(nameof(parameterAst));
Parameter = parameterAst;
ParameterArgumentType = AstParameterArgumentType.AstPair;
ParameterSpecified = true;
ArgumentSpecified = true;
ParameterName = parameterAst.ParameterName;
ParameterText = "-" + ParameterName + ":";
ArgumentType = parameterAst.Argument.StaticType;
ParameterContainsArgument = true;
Argument = parameterAst.Argument;
}
internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst)
{
if (parameterAst != null && parameterAst.Argument != null)
throw PSTraceSource.NewArgumentException(nameof(parameterAst));
if (parameterAst == null && argumentAst == null)
throw PSTraceSource.NewArgumentNullException(nameof(argumentAst));
Parameter = parameterAst;
ParameterArgumentType = AstParameterArgumentType.AstPair;
ParameterSpecified = parameterAst != null;
ArgumentSpecified = argumentAst != null;
ParameterName = parameterAst?.ParameterName;
ParameterText = parameterAst?.ParameterName;
ArgumentType = argumentAst?.StaticType;
ParameterContainsArgument = false;
Argument = argumentAst;
}
internal AstPair(CommandParameterAst parameterAst, CommandElementAst argumentAst)
{
if (parameterAst != null && parameterAst.Argument != null)
throw PSTraceSource.NewArgumentException(nameof(parameterAst));
if (parameterAst == null || argumentAst == null)
throw PSTraceSource.NewArgumentNullException(nameof(argumentAst));
Parameter = parameterAst;
ParameterArgumentType = AstParameterArgumentType.AstPair;
ParameterSpecified = true;
ArgumentSpecified = true;
ParameterName = parameterAst.ParameterName;
ParameterText = parameterAst.ParameterName;
ArgumentType = typeof(string);
ParameterContainsArgument = false;
Argument = argumentAst;
ArgumentIsCommandParameterAst = true;
}
/// <summary>
/// Indicate if the argument is contained in the CommandParameterAst.
/// </summary>
public bool ParameterContainsArgument { get; } = false;
/// <summary>
/// Indicate if the argument is of type CommandParameterAst.
/// </summary>
public bool ArgumentIsCommandParameterAst { get; } = false;
/// <summary>
/// Get the argument.
/// </summary>
public CommandElementAst Argument { get; } = null;
}
#endregion "AstArgumentPair"
/// <summary>
/// Runs the PowerShell parameter binding algorithm against a CommandAst,
/// returning information about which parameters were bound.
/// </summary>
public static class StaticParameterBinder
{
/// <summary>
/// Bind a CommandAst to one of PowerShell's built-in commands.
/// </summary>
/// <param name="commandAst">The CommandAst that represents the command invocation.</param>
/// <returns>The StaticBindingResult that represents the binding.</returns>
public static StaticBindingResult BindCommand(CommandAst commandAst)
{
return BindCommand(commandAst, resolve: true);
}
/// <summary>
/// Bind a CommandAst to the specified command.
/// </summary>
/// <param name="commandAst">The CommandAst that represents the command invocation.</param>
/// <param name="resolve">Boolean to determine whether binding should be syntactic, or should attempt
/// to resolve against an existing command.
/// </param>
/// <returns>The StaticBindingResult that represents the binding.</returns>
public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolve)
{
return BindCommand(commandAst, resolve, null);
}
/// <summary>
/// Bind a CommandAst to the specified command.
/// </summary>
/// <param name="commandAst">The CommandAst that represents the command invocation.</param>
/// <param name="resolve">Boolean to determine whether binding should be syntactic, or should attempt
/// to resolve against an existing command.
/// </param>
/// <param name="desiredParameters">
/// A string array that represents parameter names of interest. If any of these are specified,
/// then full binding is done.
/// </param>
/// <returns>The StaticBindingResult that represents the binding.</returns>
public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolve, string[] desiredParameters)
{
// If they specified any desired parameters, first quickly check if they are found
if ((desiredParameters != null) && (desiredParameters.Length > 0))
{
bool possiblyHadDesiredParameter = false;
foreach (CommandParameterAst commandParameter in commandAst.CommandElements.OfType<CommandParameterAst>())
{
string actualParameterName = commandParameter.ParameterName;
foreach (string actualParameter in desiredParameters)
{
if (actualParameter.StartsWith(actualParameterName, StringComparison.OrdinalIgnoreCase))
{
possiblyHadDesiredParameter = true;
break;
}
}
if (possiblyHadDesiredParameter)
{
break;
}
}
// Quick exit if the desired parameter was not present
if (!possiblyHadDesiredParameter)
{
return null;
}
}
if (!resolve)
{
return new StaticBindingResult(commandAst, null);
}
PseudoBindingInfo pseudoBinding = null;
if (Runspace.DefaultRunspace == null)
{
// Handle static binding from a non-PowerShell / C# application
// DefaultRunspace is a thread static field, so race condition will not happen because different threads will access different instances of "DefaultRunspace"
if (t_bindCommandRunspace == null)
{
// Create a mini runspace by remove the types and formats
InitialSessionState minimalState = InitialSessionState.CreateDefault2();
minimalState.Types.Clear();
minimalState.Formats.Clear();
t_bindCommandRunspace = RunspaceFactory.CreateRunspace(minimalState);
t_bindCommandRunspace.Open();
}
Runspace.DefaultRunspace = t_bindCommandRunspace;
// Static binding always does argument binding (not argument or parameter completion).
pseudoBinding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentBinding);
Runspace.DefaultRunspace = null;
}
else
{
// Static binding always does argument binding (not argument or parameter completion).
pseudoBinding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentBinding);
}
return new StaticBindingResult(commandAst, pseudoBinding);
}
[ThreadStatic]
private static Runspace t_bindCommandRunspace = null;
}
/// <summary>
/// Represents the results of the PowerShell parameter binding process.
/// </summary>
public class StaticBindingResult
{
internal StaticBindingResult(CommandAst commandAst, PseudoBindingInfo bindingInfo)
{
BoundParameters = new Dictionary<string, ParameterBindingResult>(StringComparer.OrdinalIgnoreCase);
BindingExceptions = new Dictionary<string, StaticBindingError>(StringComparer.OrdinalIgnoreCase);
if (bindingInfo == null)
{
CreateBindingResultForSyntacticBind(commandAst);
}
else
{
CreateBindingResultForSuccessfulBind(commandAst, bindingInfo);
}
}
private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoBindingInfo bindingInfo)
{
_bindingInfo = bindingInfo;
// Check if there is exactly one parameter set valid. In that case,
// ValidParameterSetFlags is exactly a power of two. Otherwise,
// add to the binding exceptions.
bool parameterSetSpecified = bindingInfo.ValidParameterSetsFlags != UInt32.MaxValue;
bool remainingParameterSetIncludesDefault =
(bindingInfo.DefaultParameterSetFlag != 0) &&
((bindingInfo.ValidParameterSetsFlags & bindingInfo.DefaultParameterSetFlag) ==
bindingInfo.DefaultParameterSetFlag);
// (x & (x -1 ) == 0) is a bit hack to determine if something is
// exactly a power of two.
bool onlyOneRemainingParameterSet =
(bindingInfo.ValidParameterSetsFlags != 0) &&
(bindingInfo.ValidParameterSetsFlags &
(bindingInfo.ValidParameterSetsFlags - 1)) == 0;
if (parameterSetSpecified &&
(!remainingParameterSetIncludesDefault) &&
(!onlyOneRemainingParameterSet))
{
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
null,
null,
null,
null,
null,
ParameterBinderStrings.AmbiguousParameterSet,
"AmbiguousParameterSet");
BindingExceptions.Add(commandAst.CommandElements[0].Extent.Text,
new StaticBindingError(commandAst.CommandElements[0], bindingException));
}
// Add error for duplicate parameters
if (bindingInfo.DuplicateParameters != null)
{
foreach (AstParameterArgumentPair duplicateParameter in bindingInfo.DuplicateParameters)
{
AddDuplicateParameterBindingException(duplicateParameter.Parameter);
}
}
// Add error for parameters not found
if (bindingInfo.ParametersNotFound != null)
{
foreach (CommandParameterAst parameterNotFound in bindingInfo.ParametersNotFound)
{
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
null,
parameterNotFound.ErrorPosition,
parameterNotFound.ParameterName,
null,
null,
ParameterBinderStrings.NamedParameterNotFound,
"NamedParameterNotFound");
BindingExceptions.Add(parameterNotFound.ParameterName, new StaticBindingError(parameterNotFound, bindingException));
}
}
// Add error for ambiguous parameters
if (bindingInfo.AmbiguousParameters != null)
{
foreach (CommandParameterAst ambiguousParameter in bindingInfo.AmbiguousParameters)
{
ParameterBindingException bindingException = bindingInfo.BindingExceptions[ambiguousParameter];
BindingExceptions.Add(ambiguousParameter.ParameterName, new StaticBindingError(ambiguousParameter, bindingException));
}
}
// Add error for unbound positional parameters
if (bindingInfo.UnboundArguments != null)
{
foreach (AstParameterArgumentPair unboundArgument in bindingInfo.UnboundArguments)
{
AstPair argument = unboundArgument as AstPair;
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
null,
argument.Argument.Extent,
argument.Argument.Extent.Text,
null,
null,
ParameterBinderStrings.PositionalParameterNotFound,
"PositionalParameterNotFound");
BindingExceptions.Add(argument.Argument.Extent.Text, new StaticBindingError(argument.Argument, bindingException));
}
}
// Process the bound parameters
if (bindingInfo.BoundParameters != null)
{
foreach (KeyValuePair<string, MergedCompiledCommandParameter> item in bindingInfo.BoundParameters)
{
CompiledCommandParameter parameter = item.Value.Parameter;
CommandElementAst value = null;
object constantValue = null;
// This is a single argument
AstPair argumentAstPair = bindingInfo.BoundArguments[item.Key] as AstPair;
if (argumentAstPair != null)
{
value = argumentAstPair.Argument;
}
// This is a parameter that took an argument, as well as ValueFromRemainingArguments.
// Merge the arguments into a single fake argument.
AstArrayPair argumentAstArrayPair = bindingInfo.BoundArguments[item.Key] as AstArrayPair;
if (argumentAstArrayPair != null)
{
List<ExpressionAst> arguments = new List<ExpressionAst>();
foreach (ExpressionAst expression in argumentAstArrayPair.Argument)
{
ArrayLiteralAst expressionArray = expression as ArrayLiteralAst;
if (expressionArray != null)
{
foreach (ExpressionAst newExpression in expressionArray.Elements)
{
arguments.Add((ExpressionAst)newExpression.Copy());
}
}
else
{
arguments.Add((ExpressionAst)expression.Copy());
}
}
// Define the virtual extent and virtual ArrayLiteral.
IScriptExtent fakeExtent = arguments[0].Extent;
ArrayLiteralAst fakeArguments = new ArrayLiteralAst(fakeExtent, arguments);
value = fakeArguments;
}
// Special handling of switch parameters
if (parameter.Type == typeof(SwitchParameter))
{
if ((value != null) &&
(string.Equals("$false", value.Extent.Text, StringComparison.OrdinalIgnoreCase)))
{
continue;
}
constantValue = true;
}
// We got a parameter and a value
if ((value != null) || (constantValue != null))
{
BoundParameters.Add(item.Key, new ParameterBindingResult(parameter, value, constantValue));
}
else
{
bool takesValueFromPipeline = false;
foreach (ParameterSetSpecificMetadata parameterSet in parameter.GetMatchingParameterSetData(bindingInfo.ValidParameterSetsFlags))
{
if (parameterSet.ValueFromPipeline)
{
takesValueFromPipeline = true;
break;
}
}
if (!takesValueFromPipeline)
{
// We have a parameter with no value that isn't a switch parameter, or input parameter
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
null,
commandAst.CommandElements[0].Extent,
parameter.Name,
parameter.Type,
null,
ParameterBinderStrings.MissingArgument,
"MissingArgument");
BindingExceptions.Add(commandAst.CommandElements[0].Extent.Text,
new StaticBindingError(commandAst.CommandElements[0], bindingException));
}
}
}
}
}
private void AddDuplicateParameterBindingException(CommandParameterAst duplicateParameter)
{
if (duplicateParameter == null)
{
return;
}
ParameterBindingException bindingException =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
null,
duplicateParameter.ErrorPosition,
duplicateParameter.ParameterName,
null,
null,
ParameterBinderStrings.ParameterAlreadyBound,
nameof(ParameterBinderStrings.ParameterAlreadyBound));
// if the duplicated Parameter Name appears more than twice, we will ignore as we already have similar bindingException.
if (!BindingExceptions.ContainsKey(duplicateParameter.ParameterName))
{
BindingExceptions.Add(duplicateParameter.ParameterName, new StaticBindingError(duplicateParameter, bindingException));
}
}
private PseudoBindingInfo _bindingInfo = null;
private void CreateBindingResultForSyntacticBind(CommandAst commandAst)
{
bool foundCommand = false;
CommandParameterAst currentParameter = null;
int position = 0;
ParameterBindingResult bindingResult = new ParameterBindingResult();
foreach (CommandElementAst commandElement in commandAst.CommandElements)
{
// Skip the command name
if (!foundCommand)
{
foundCommand = true;
continue;
}
CommandParameterAst parameter = commandElement as CommandParameterAst;
if (parameter != null)
{
if (currentParameter != null)
{
// Assume it was a switch
AddSwitch(currentParameter.ParameterName, bindingResult);
ResetCurrentParameter(ref currentParameter, ref bindingResult);
}
// If this is an actual parameter, get its name.
string parameterName = parameter.ParameterName;
bindingResult.Value = parameter;
// If it's a parameter with argument, add them both to the dictionary
if (parameter.Argument != null)
{
bindingResult.Value = parameter.Argument;
AddBoundParameter(parameter, parameterName, bindingResult);
ResetCurrentParameter(ref currentParameter, ref bindingResult);
}
// Otherwise, it's just a parameter and the argument is to follow.
else
{
// Store our current parameter
currentParameter = parameter;
}
}
else
{
// This isn't a parameter, it's a value for the previous parameter
if (currentParameter != null)
{
bindingResult.Value = commandElement;
AddBoundParameter(currentParameter, currentParameter.ParameterName, bindingResult);
}
else
{
// Assume positional
bindingResult.Value = commandElement;
AddBoundParameter(null, position.ToString(CultureInfo.InvariantCulture), bindingResult);
position++;
}
ResetCurrentParameter(ref currentParameter, ref bindingResult);
}
}
// Catch any extra parameters at the end of the command
if (currentParameter != null)
{
// Assume it was a switch
AddSwitch(currentParameter.ParameterName, bindingResult);
}
}
private void AddBoundParameter(CommandParameterAst parameter, string parameterName, ParameterBindingResult bindingResult)
{
if (BoundParameters.ContainsKey(parameterName))
{
AddDuplicateParameterBindingException(parameter);
}
else
{
BoundParameters.Add(parameterName, bindingResult);
}
}
private static void ResetCurrentParameter(ref CommandParameterAst currentParameter, ref ParameterBindingResult bindingResult)
{
currentParameter = null;
bindingResult = new ParameterBindingResult();
}
private void AddSwitch(string currentParameter, ParameterBindingResult bindingResult)
{
bindingResult.ConstantValue = true;
AddBoundParameter(null, currentParameter, bindingResult);
}
/// <summary>
/// </summary>
public Dictionary<string, ParameterBindingResult> BoundParameters { get; }
/// <summary>
/// </summary>
public Dictionary<string, StaticBindingError> BindingExceptions { get; }
}
/// <summary>
/// Represents the binding of a parameter to its argument.
/// </summary>
public class ParameterBindingResult
{
internal ParameterBindingResult(CompiledCommandParameter parameter, CommandElementAst value, object constantValue)
{
this.Parameter = new ParameterMetadata(parameter);
this.Value = value;
this.ConstantValue = constantValue;
}
internal ParameterBindingResult()
{
}
/// <summary>
/// </summary>
public ParameterMetadata Parameter { get; internal set; }
/// <summary>
/// </summary>
public object ConstantValue
{
get
{
return _constantValue;
}
internal set
{
if (value != null)
{
_constantValue = value;
}
}
}
private object _constantValue;
/// <summary>
/// </summary>
public CommandElementAst Value
{
get
{
return _value;
}
internal set
{
_value = value;
ConstantExpressionAst constantValueAst = value as ConstantExpressionAst;
if (constantValueAst != null)
{
this.ConstantValue = constantValueAst.Value;
}
}
}
private CommandElementAst _value;
}
/// <summary>
/// Represents the exception generated by the static parameter binding process.
/// </summary>
public class StaticBindingError
{
/// <summary>
/// Creates a StaticBindingException.
/// </summary>
/// <param name="commandElement">The element associated with the exception.</param>
/// <param name="exception">The parameter binding exception that got raised.</param>
internal StaticBindingError(CommandElementAst commandElement, ParameterBindingException exception)
{
this.CommandElement = commandElement;
this.BindingException = exception;
}
/// <summary>
/// The command element associated with the exception.
/// </summary>
public CommandElementAst CommandElement { get; }
/// <summary>
/// The ParameterBindingException that this command element caused.
/// </summary>
public ParameterBindingException BindingException { get; }
}
#region "PseudoBindingInfo"
internal enum PseudoBindingInfoType
{
PseudoBindingFail = 0,
PseudoBindingSucceed = 1,
}
internal sealed class PseudoBindingInfo
{
/// <summary>
/// The pseudo binding succeeded.
/// </summary>
/// <param name="commandInfo"></param>
/// <param name="validParameterSetsFlags"></param>
/// <param name="defaultParameterSetFlag"></param>
/// <param name="boundParameters"></param>
/// <param name="unboundParameters"></param>
/// <param name="boundArguments"></param>
/// <param name="boundPositionalParameter"></param>
/// <param name="allParsedArguments"></param>
/// <param name="parametersNotFound"></param>
/// <param name="ambiguousParameters"></param>
/// <param name="bindingExceptions"></param>
/// <param name="duplicateParameters"></param>
/// <param name="unboundArguments"></param>
internal PseudoBindingInfo(
CommandInfo commandInfo,
uint validParameterSetsFlags,
uint defaultParameterSetFlag,
Dictionary<string, MergedCompiledCommandParameter> boundParameters,
List<MergedCompiledCommandParameter> unboundParameters,
Dictionary<string, AstParameterArgumentPair> boundArguments,
Collection<string> boundPositionalParameter,
Collection<AstParameterArgumentPair> allParsedArguments,
Collection<CommandParameterAst> parametersNotFound,
Collection<CommandParameterAst> ambiguousParameters,
Dictionary<CommandParameterAst, ParameterBindingException> bindingExceptions,
Collection<AstParameterArgumentPair> duplicateParameters,
Collection<AstParameterArgumentPair> unboundArguments)
{
CommandInfo = commandInfo;
InfoType = PseudoBindingInfoType.PseudoBindingSucceed;
ValidParameterSetsFlags = validParameterSetsFlags;
DefaultParameterSetFlag = defaultParameterSetFlag;
BoundParameters = boundParameters;
UnboundParameters = unboundParameters;
BoundArguments = boundArguments;
BoundPositionalParameter = boundPositionalParameter;
AllParsedArguments = allParsedArguments;
ParametersNotFound = parametersNotFound;
AmbiguousParameters = ambiguousParameters;
BindingExceptions = bindingExceptions;
DuplicateParameters = duplicateParameters;
UnboundArguments = unboundArguments;
}
/// <summary>
/// The pseudo binding failed with parameter set confliction.
/// </summary>
/// <param name="commandInfo"></param>
/// <param name="defaultParameterSetFlag"></param>
/// <param name="allParsedArguments"></param>
/// <param name="unboundParameters"></param>
internal PseudoBindingInfo(
CommandInfo commandInfo,
uint defaultParameterSetFlag,
Collection<AstParameterArgumentPair> allParsedArguments,
List<MergedCompiledCommandParameter> unboundParameters)
{
CommandInfo = commandInfo;
InfoType = PseudoBindingInfoType.PseudoBindingFail;
DefaultParameterSetFlag = defaultParameterSetFlag;
AllParsedArguments = allParsedArguments;
UnboundParameters = unboundParameters;
}
internal string CommandName
{
get { return CommandInfo.Name; }
}
internal CommandInfo CommandInfo { get; }
internal PseudoBindingInfoType InfoType { get; }
internal uint ValidParameterSetsFlags { get; }
internal uint DefaultParameterSetFlag { get; }
internal Dictionary<string, MergedCompiledCommandParameter> BoundParameters { get; }
internal List<MergedCompiledCommandParameter> UnboundParameters { get; }
internal Dictionary<string, AstParameterArgumentPair> BoundArguments { get; }
internal Collection<AstParameterArgumentPair> UnboundArguments { get; }
internal Collection<string> BoundPositionalParameter { get; }
internal Collection<AstParameterArgumentPair> AllParsedArguments { get; }
internal Collection<CommandParameterAst> ParametersNotFound { get; }
internal Collection<CommandParameterAst> AmbiguousParameters { get; }
internal Dictionary<CommandParameterAst, ParameterBindingException> BindingExceptions { get; }
internal Collection<AstParameterArgumentPair> DuplicateParameters { get; }
}
#endregion "PseudoBindingInfo"
internal class PseudoParameterBinder
{
/*
/// <summary>
/// Get the parameter binding metadata.
/// </summary>
/// <param name="possibleParameterSets"></param>
/// <returns></returns>
public Dictionary<ParameterMetadata, ExpressionAst> GetPseudoParameterBinding(out Collection<ParameterSetMetadata> possibleParameterSets)
{
ExecutionContext contextFromTls =
System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS();
return GetPseudoParameterBinding(out possibleParameterSets, contextFromTls, null);
}
*/
internal enum BindingType
{
/// <summary>
/// Caller is binding a parameter argument.
/// </summary>
ArgumentBinding = 0,
/// <summary>
/// Caller is performing completion on a parameter argument.
/// </summary>
ArgumentCompletion,
/// <summary>
/// Caller is performing completion on a parameter name.
/// </summary>
ParameterCompletion
}
/// <summary>
/// Get the parameter binding metadata.
/// </summary>
/// <param name="command"></param>
/// <param name="pipeArgumentType">Indicate the type of the piped-in argument.</param>
/// <param name="paramAstAtCursor">The CommandParameterAst the cursor is pointing at.</param>
/// <param name="bindingType">Indicates whether pseudo binding is for argument binding, argument completion, or parameter completion.</param>
/// <param name="bindPositional">Indicates if the pseudo binding should bind positional parameters</param>
/// <returns>PseudoBindingInfo.</returns>
internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pipeArgumentType, CommandParameterAst paramAstAtCursor, BindingType bindingType, bool bindPositional = true)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(command));
}
// initialize/reset the private members
InitializeMembers();
_commandAst = command;
_commandElements = command.CommandElements;
Collection<AstParameterArgumentPair> unboundArguments = new Collection<AstParameterArgumentPair>();
// analyze the command and reparse the arguments
{
ExecutionContext executionContext = LocalPipeline.GetExecutionContextFromTLS();
if (executionContext != null)
{
// WinBlue: 324316. This limits the interaction of pseudoparameterbinder with the actual host.
SetTemporaryDefaultHost(executionContext);
PSLanguageMode? previousLanguageMode = null;
try
{
// Tab expansion is called from a trusted function - we should apply ConstrainedLanguage if necessary.
if (executionContext.HasRunspaceEverUsedConstrainedLanguageMode)
{
previousLanguageMode = executionContext.LanguageMode;
executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
}
_bindingEffective = PrepareCommandElements(executionContext, paramAstAtCursor);
}
finally
{
if (previousLanguageMode.HasValue)
{
executionContext.LanguageMode = previousLanguageMode.Value;
}
RestoreHost(executionContext);
}
}
}
if (_bindingEffective && (_isPipelineInputExpected || pipeArgumentType != null))
{
_pipelineInputType = pipeArgumentType;
}
_bindingEffective = ParseParameterArguments(paramAstAtCursor);
if (_bindingEffective)
{
// named binding
unboundArguments = BindNamedParameters();
_bindingEffective = _currentParameterSetFlag != 0;
if (bindPositional)
{
// positional binding
unboundArguments = BindPositionalParameter(
unboundArguments,
_currentParameterSetFlag,
_defaultParameterSetFlag,
bindingType);
}
// VFRA/pipeline binding if the given command is a binary cmdlet or a script cmdlet
if (!_function)
{
unboundArguments = BindRemainingParameters(unboundArguments);
BindPipelineParameters();
}
// Update available parameter sets based on bound arguments
// (x & (x -1 ) == 0) is a bit hack to determine if something is
// exactly a power of two.
bool parameterSetSpecified = (_currentParameterSetFlag != 0) &&
(_currentParameterSetFlag != UInt32.MaxValue);
bool onlyOneRemainingParameterSet = (_currentParameterSetFlag != 0) &&
(_currentParameterSetFlag & (_currentParameterSetFlag - 1)) == 0;
if ((bindingType != BindingType.ParameterCompletion) && parameterSetSpecified && (!onlyOneRemainingParameterSet))
{
CmdletParameterBinderController.ResolveParameterSetAmbiguityBasedOnMandatoryParameters(
_boundParameters,
_unboundParameters,
null,
ref _currentParameterSetFlag,
null);
}
}
// Binding failed
if (!_bindingEffective)
{
// The command is not a cmdlet, not a script cmdlet, and not a function
if (_bindableParameters == null)
return null;
// get all bindable parameters
_unboundParameters.Clear();
_unboundParameters.AddRange(_bindableParameters.BindableParameters.Values);
return new PseudoBindingInfo(
_commandInfo,
_defaultParameterSetFlag,
_arguments,
_unboundParameters);
}
return new PseudoBindingInfo(
_commandInfo,
_currentParameterSetFlag,
_defaultParameterSetFlag,
_boundParameters,
_unboundParameters,
_boundArguments,
_boundPositionalParameter,
_arguments,
_parametersNotFound,
_ambiguousParameters,
_bindingExceptions,
_duplicateParameters,
unboundArguments
);
}
/// <summary>
/// Sets a temporary default host on the ExecutionContext.
/// </summary>
/// <param name="executionContext">ExecutionContext.</param>
private void SetTemporaryDefaultHost(ExecutionContext executionContext)
{
if (executionContext.EngineHostInterface.IsHostRefSet)
{
// A temporary host is already set so we need to track and restore here, because
// setting the host again will overwrite the current one.
_restoreHost = executionContext.EngineHostInterface.ExternalHost;
// Revert host back to its original state.
executionContext.EngineHostInterface.RevertHostRef();
}
// Temporarily set host to default.
executionContext.EngineHostInterface.SetHostRef(new Microsoft.PowerShell.DefaultHost(
CultureInfo.CurrentCulture,
CultureInfo.CurrentUICulture));
}
/// <summary>
/// Restores original ExecutionContext host state.
/// </summary>
/// <param name="executionContext">ExecutionContext.</param>
private void RestoreHost(ExecutionContext executionContext)
{
// Remove temporary host and revert to original.
executionContext.EngineHostInterface.RevertHostRef();
// Re-apply saved host if any.
if (_restoreHost != null)
{
executionContext.EngineHostInterface.SetHostRef(_restoreHost);
_restoreHost = null;
}
}
// Host to restore.
private PSHost _restoreHost;
// command ast related states
private CommandAst _commandAst;
private ReadOnlyCollection<CommandElementAst> _commandElements;
// binding related states
private bool _function = false;
private string _commandName = null;
private CommandInfo _commandInfo = null;
private uint _currentParameterSetFlag = uint.MaxValue;
private uint _defaultParameterSetFlag = 0;
private MergedCommandParameterMetadata _bindableParameters = null;
private Dictionary<string, MergedCompiledCommandParameter> _boundParameters;
private Dictionary<string, AstParameterArgumentPair> _boundArguments;
private Collection<AstParameterArgumentPair> _arguments;
private Collection<string> _boundPositionalParameter;
private List<MergedCompiledCommandParameter> _unboundParameters;
// tab expansion related states
private Type _pipelineInputType = null;
private bool _bindingEffective = true;
private bool _isPipelineInputExpected = false;
private Collection<CommandParameterAst> _parametersNotFound;
private Collection<CommandParameterAst> _ambiguousParameters;
private Collection<AstParameterArgumentPair> _duplicateParameters;
private Dictionary<CommandParameterAst, ParameterBindingException> _bindingExceptions;
/// <summary>
/// Initialize collection/dictionary members when it's necessary.
/// </summary>
private void InitializeMembers()
{
// Initializing binding related members
_function = false;
_commandName = null;
_currentParameterSetFlag = uint.MaxValue;
_defaultParameterSetFlag = 0;
_bindableParameters = null;
// reuse the collections/dictionaries
_arguments ??= new Collection<AstParameterArgumentPair>();
_boundParameters ??= new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
_boundArguments ??= new Dictionary<string, AstParameterArgumentPair>(StringComparer.OrdinalIgnoreCase);
_unboundParameters ??= new List<MergedCompiledCommandParameter>();
_boundPositionalParameter ??= new Collection<string>();
_bindingExceptions ??= new Dictionary<CommandParameterAst, ParameterBindingException>();
_arguments.Clear();
_boundParameters.Clear();
_unboundParameters.Clear();
_boundArguments.Clear();
_boundPositionalParameter.Clear();
_bindingExceptions.Clear();
// Initializing tab expansion related members
_pipelineInputType = null;
_bindingEffective = true;
_isPipelineInputExpected = false;
// reuse the collections
_parametersNotFound ??= new Collection<CommandParameterAst>();
_ambiguousParameters ??= new Collection<CommandParameterAst>();
_duplicateParameters ??= new Collection<AstParameterArgumentPair>();
_parametersNotFound.Clear();
_ambiguousParameters.Clear();
_duplicateParameters.Clear();
}
private bool PrepareCommandElements(ExecutionContext context, CommandParameterAst paramAtCursor)
{
int commandIndex = 0;
bool dotSource = _commandAst.InvocationOperator == TokenKind.Dot;
CommandProcessorBase processor = null;
string commandName = null;
try
{
processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource, forCompletion:true);
}
catch (RuntimeException)
{
// Failed to create the CommandProcessor;
return false;
}
var commandProcessor = processor as CommandProcessor;
var scriptProcessor = processor as ScriptCommandProcessorBase;
bool implementsDynamicParameters = commandProcessor != null &&
commandProcessor.CommandInfo.ImplementsDynamicParameters;
if (commandProcessor != null || scriptProcessor != null)
{
// Pre-processing the arguments -- command arguments
for (commandIndex++; commandIndex < _commandElements.Count; commandIndex++)
{
if (implementsDynamicParameters && _commandElements[commandIndex] == paramAtCursor)
{
// Commands with dynamic parameters will try to bind the command elements.
// A partially complete parameter will most likely cause a binding error and negatively affect the results.
continue;
}
var parameter = _commandElements[commandIndex] as CommandParameterAst;
if (parameter != null)
{
if (implementsDynamicParameters)
{
CommandParameterInternal paramToAdd;
if (parameter.Argument is null)
{
paramToAdd = CommandParameterInternal.CreateParameter(parameter.ParameterName, parameter.Extent.Text);
}
else
{
object value;
if (!SafeExprEvaluator.TrySafeEval(parameter.Argument, context, out value))
{
value = parameter.Argument.Extent.Text;
}
paramToAdd = CommandParameterInternal.CreateParameterWithArgument(
parameterAst: null,
parameterName: parameter.ParameterName,
parameterText: parameter.Extent.Text,
argumentAst: null,
value: value,
spaceAfterParameter: false);
}
commandProcessor.AddParameter(paramToAdd);
}
AstPair parameterArg = parameter.Argument != null
? new AstPair(parameter)
: new AstPair(parameter, (ExpressionAst)null);
_arguments.Add(parameterArg);
}
else
{
object valueToAdd;
ExpressionAst expressionToAdd;
if (_commandElements[commandIndex] is ConstantExpressionAst constant)
{
if (constant.Extent.Text.Equals("-", StringComparison.Ordinal))
{
// A value of "-" is most likely the user trying to tab here,
// and we don't want it be treated as an argument
continue;
}
valueToAdd = constant.Value;
expressionToAdd = constant;
}
else if (_commandElements[commandIndex] is ExpressionAst expression)
{
if (!SafeExprEvaluator.TrySafeEval(expression, context, out valueToAdd))
{
valueToAdd = expression.Extent.Text;
}
expressionToAdd = expression;
}
else
{
continue;
}
if (implementsDynamicParameters)
{
commandProcessor.AddParameter(CommandParameterInternal.CreateArgument(valueToAdd));
}
_arguments.Add(new AstPair(null, expressionToAdd));
}
}
}
if (commandProcessor != null)
{
_function = false;
if (implementsDynamicParameters)
{
bool retryWithNoArgs = false, alreadyRetried = false;
do
{
CommandProcessorBase oldCurrentCommandProcessor = context.CurrentCommandProcessor;
try
{
context.CurrentCommandProcessor = commandProcessor;
commandProcessor.SetCurrentScopeToExecutionScope();
// Run method "BindCommandLineParametersNoValidation" to get all available parameters, including the dynamic
// parameters (some of them, not necessarily all. Since we don't do the actual binding, some dynamic parameters
// might not be retrieved).
if (!retryWithNoArgs)
{
// Win8 345299: First try with all unbounded arguments
commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments);
}
else
{
// Win8 345299: If the first try ended with ParameterBindingException, try again with no arguments
alreadyRetried = true;
commandProcessor.CmdletParameterBinderController.ClearUnboundArguments();
commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection<CommandParameterInternal>());
}
}
catch (ParameterBindingException e)
{
// Catch the parameter binding exception thrown when Reparsing the argument.
// "MissingArgument" - a single parameter is matched, but no argument is present
// "AmbiguousParameter" - multiple parameters are matched
// When such exceptions are caught, retry again without arguments, so as to get dynamic parameters
// based on the current provider
if (e.ErrorId == "MissingArgument" || e.ErrorId == "AmbiguousParameter")
retryWithNoArgs = true;
}
catch (Exception)
{
}
finally
{
context.CurrentCommandProcessor = oldCurrentCommandProcessor;
commandProcessor.RestorePreviousScope();
}
} while (retryWithNoArgs && !alreadyRetried);
}
// Get all bindable parameters and initialize the _unboundParameters
_commandInfo = commandProcessor.CommandInfo;
_commandName = commandProcessor.CommandInfo.Name;
_bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters;
_defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag;
}
else if (scriptProcessor != null)
{
_function = true;
_commandInfo = scriptProcessor.CommandInfo;
_commandName = scriptProcessor.CommandInfo.Name;
_bindableParameters = scriptProcessor.ScriptParameterBinderController.BindableParameters;
_defaultParameterSetFlag = 0;
}
else
{
// The command is not a function, cmdlet and script cmdlet
return false;
}
_unboundParameters.AddRange(_bindableParameters.BindableParameters.Values);
// Pre-processing the arguments -- pipeline input
// Check if there is pipeline input
CommandBaseAst preCmdBaseAst = null;
var pipe = _commandAst.Parent as PipelineAst;
Diagnostics.Assert(pipe != null, "CommandAst should has a PipelineAst parent");
if (pipe.PipelineElements.Count > 1)
{
foreach (CommandBaseAst cmdBase in pipe.PipelineElements)
{
if (cmdBase.GetHashCode() == _commandAst.GetHashCode())
{
_isPipelineInputExpected = preCmdBaseAst != null;
if (_isPipelineInputExpected)
_pipelineInputType = typeof(object);
break;
}
preCmdBaseAst = cmdBase;
}
}
return true;
}
private CommandProcessorBase PrepareFromAst(ExecutionContext context, out string resolvedCommandName)
{
// Analyze the Ast
var exportVisitor = new ExportVisitor(forCompletion: true);
Ast ast = _commandAst;
while (ast.Parent != null)
{
ast = ast.Parent;
}
ast.Visit(exportVisitor);
CommandProcessorBase commandProcessor = null;
resolvedCommandName = _commandAst.GetCommandName();
if (resolvedCommandName != null)
{
string alias;
int resolvedAliasCount = 0;
while (exportVisitor.DiscoveredAliases.TryGetValue(resolvedCommandName, out alias))
{
resolvedAliasCount += 1;
if (resolvedAliasCount > 5)
break; // give up, assume it's recursive
resolvedCommandName = alias;
}
FunctionDefinitionAst functionDefinitionAst;
if (exportVisitor.DiscoveredFunctions.TryGetValue(resolvedCommandName, out functionDefinitionAst))
{
var scriptBlock = new ScriptBlock(functionDefinitionAst, functionDefinitionAst.IsFilter);
commandProcessor = CommandDiscovery.CreateCommandProcessorForScript(scriptBlock, context, true, context.EngineSessionState);
}
}
return commandProcessor;
}
/// <summary>
/// Parse the arguments to process switch parameters and parameters without a value
/// specified. We always eat the error (such as parameter without value) and continue
/// to do the binding.
/// </summary>
/// <param name="paramAstAtCursor">
/// For parameter completion, if the cursor is pointing at a CommandParameterAst, we
/// should not try exact matching for that CommandParameterAst. This is to handle the
/// following case:
/// Add-Computer -domain(tab)
/// Add-Computer has an alias "Domain" that can exactly match this partial input, but
/// since the user is typing 'tab', the partial input 'domain' should not be considered
/// as an exact match. In this case, we don't try exact matching when calling
/// GetMatchingParameter(..) so as to preserve other possibilities.
/// </param>
private bool ParseParameterArguments(CommandParameterAst paramAstAtCursor)
{
if (!_bindingEffective)
return _bindingEffective;
var result = new Collection<AstParameterArgumentPair>();
for (int index = 0; index < _arguments.Count; index++)
{
AstParameterArgumentPair argument = _arguments[index];
if (!argument.ParameterSpecified || argument.ArgumentSpecified)
{
// Add the positional/named arguments back
result.Add(argument);
continue;
}
Diagnostics.Assert(argument.ParameterSpecified && !argument.ArgumentSpecified,
"At this point, the parameters should have no arguments");
// Now check the parameter name with the bindable parameters
string parameterName = argument.ParameterName;
MergedCompiledCommandParameter matchingParameter = null;
try
{
bool tryExactMatching = argument.Parameter != paramAstAtCursor;
matchingParameter = _bindableParameters.GetMatchingParameter(parameterName, false, tryExactMatching, null);
}
catch (ParameterBindingException e)
{
// The parameterName is resolved to multiple parameters. The most possible scenario for this
// would be the user typing tab to complete a parameter. In this case, we can ignore this
// parameter safely.
// If the next item is a pure argument, we skip it so that it doesn't get bound
// positionally.
if (index < _arguments.Count - 1)
{
AstParameterArgumentPair nextArg = _arguments[index + 1];
if (!nextArg.ParameterSpecified && nextArg.ArgumentSpecified)
{
index++;
}
}
_ambiguousParameters.Add(argument.Parameter);
_bindingExceptions[argument.Parameter] = e;
continue;
}
if (matchingParameter == null)
{
// The parameter cannot be found. The reason could be:
// 1. It's a bynamic parameter, and we cannot retrieve the ParameterMetadata for it
// at this point, since it's pseudo binding.
// 2. The spelling of this parameter is wrong.
// We can simply ignore this parameter, but the issue is what to do with the argument
// following this parameter (if there is an argument following it). There are two cases:
// 1. This parameter is supposed to be a switch parameter. Then the argument following it
// should NOT be ignored.
// 2. This parameter is supposed to take an argument. Then the following argument should
// also be ignored
// We check the next item. If it's a pure argument, we give up the binding, because we don't
// know how to deal with it (ignore it? keep it?), and it will affect the accuracy of our
// parameter set resolution.
if (index < _arguments.Count - 1)
{
AstParameterArgumentPair nextArg = _arguments[index + 1];
// If the next item is a pure argument, we give up the pseudo binding.
if (!nextArg.ParameterSpecified && nextArg.ArgumentSpecified)
{
// Testing paramsAstAtCursor ensures we only give up during tab completion,
// otherwise we know this is a missing parameter.
if (paramAstAtCursor != null)
{
// Do not use the parsed arguments
_arguments = null;
return false;
}
else
{
// Otherwise, skip the next argument
index++;
_parametersNotFound.Add(argument.Parameter);
continue;
}
}
}
// If the next item is not a pure argument, or the current parameter is the last item,
// ignore this parameter and carry on with the binding
_parametersNotFound.Add(argument.Parameter);
continue;
}
// Check if it's SwitchParameter
if (matchingParameter.Parameter.Type == typeof(SwitchParameter))
{
SwitchPair newArg = new SwitchPair(argument.Parameter);
result.Add(newArg);
continue;
}
// It's not a switch parameter, we need to check the next argument
if (index < _arguments.Count - 1)
{
AstParameterArgumentPair nextArg = _arguments[index + 1];
if (nextArg.ParameterSpecified)
{
try
{
MergedCompiledCommandParameter nextMatchingParameter =
_bindableParameters.GetMatchingParameter(nextArg.ParameterName, false, true, null);
// The next parameter doesn't exist. We use it as an argument
if (nextMatchingParameter == null)
{
AstPair newArg = new AstPair(argument.Parameter, nextArg.Parameter);
result.Add(newArg);
index++;
}
else
{
// It's possible the user is typing tab for argument completion.
// We set a fake argument for the current parameter in this case.
FakePair newArg = new FakePair(argument.Parameter);
result.Add(newArg);
}
}
catch (ParameterBindingException)
{
// The next parameter name is ambiguous. We just set
// a fake argument for the current parameter.
FakePair newArg = new FakePair(argument.Parameter);
result.Add(newArg);
}
}
else
{
// The next item is a pure argument.
AstPair nextArgument = nextArg as AstPair;
Diagnostics.Assert(nextArgument != null, "the next item should be a pure argument here");
Diagnostics.Assert(nextArgument.ArgumentSpecified && !nextArgument.ArgumentIsCommandParameterAst, "the next item should be a pure argument here");
AstPair newArg = new AstPair(argument.Parameter, (ExpressionAst)nextArgument.Argument);
result.Add(newArg);
index++;
}
}
else
{
// The current parameter is the last item. Set a fake argument for it
FakePair newArg = new FakePair(argument.Parameter);
result.Add(newArg);
}
}
_arguments = result;
return true;
}
private Collection<AstParameterArgumentPair> BindNamedParameters()
{
Collection<AstParameterArgumentPair> result = new Collection<AstParameterArgumentPair>();
if (!_bindingEffective)
return result;
foreach (AstParameterArgumentPair argument in _arguments)
{
if (!argument.ParameterSpecified)
{
result.Add(argument);
continue;
}
MergedCompiledCommandParameter parameter = null;
try
{
parameter = _bindableParameters.GetMatchingParameter(argument.ParameterName, false, true, null);
}
catch (ParameterBindingException)
{
// The parameter name is ambiguous. It's not processed in ParseParameterArguments. Otherwise we
// should detect it early. So this argument comes from a CommandParameterAst with argument. We
// ignore it and carry on with our binding
_ambiguousParameters.Add(argument.Parameter);
continue;
}
if (parameter == null)
{
// Cannot find a matching parameter. It's not processed in ParseParameterArguments. It comes from
// a CommandParameterAst with argument. We ignore it and carry on with our binding
_parametersNotFound.Add(argument.Parameter);
continue;
}
if (_boundParameters.ContainsKey(parameter.Parameter.Name))
{
// This parameter is already bound. We ignore it and carry on with the binding.
_duplicateParameters.Add(argument);
continue;
}
// The parameter exists and is not bound yet. We assume the binding will always succeed.
if (parameter.Parameter.ParameterSetFlags != 0)
{
_currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
}
_unboundParameters.Remove(parameter);
if (!_boundParameters.ContainsKey(parameter.Parameter.Name))
{
_boundParameters.Add(parameter.Parameter.Name, parameter);
}
if (!_boundArguments.ContainsKey(parameter.Parameter.Name))
{
_boundArguments.Add(parameter.Parameter.Name, argument);
}
}
return result;
}
private Collection<AstParameterArgumentPair> BindPositionalParameter(
Collection<AstParameterArgumentPair> unboundArguments,
uint validParameterSetFlags,
uint defaultParameterSetFlag,
BindingType bindingType)
{
Collection<AstParameterArgumentPair> result = new Collection<AstParameterArgumentPair>();
if (_bindingEffective && unboundArguments.Count > 0)
{
List<AstParameterArgumentPair> unboundArgumentsCollection = new List<AstParameterArgumentPair>(unboundArguments);
// Get the unbound positional parameters
SortedDictionary<int, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter>> positionalParameterDictionary;
try
{
positionalParameterDictionary =
ParameterBinderController.EvaluateUnboundPositionalParameters(_unboundParameters, validParameterSetFlags);
}
catch (InvalidOperationException)
{
// This exception is thrown because the binder found two positional parameters
// from the same parameter set with the same position defined. The parameter definition
// is ambiguous. We give up binding in this case
_bindingEffective = false;
return result;
}
// No positional parameter available
if (positionalParameterDictionary.Count == 0)
return unboundArguments;
int unboundArgumentsIndex = 0;
foreach (Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters in positionalParameterDictionary.Values)
{
if (nextPositionalParameters.Count == 0)
{
continue;
}
AstParameterArgumentPair argument = GetNextPositionalArgument(
unboundArgumentsCollection,
result,
ref unboundArgumentsIndex);
if (argument == null)
{
break;
}
// The positional pseudo binding is processed in two different approaches for parameter completion and parameter argument completion.
// - For parameter completion, we do NOT honor the default parameter set, so we can preserve potential parameters as many as possible.
// Example:
// Where-Object PropertyA -<tab>
// If the default parameter is honored, the completion results only contain EQ, because it's locked to the default set
//
// - For parameter argument completion, however, we want to honor the default parameter set some times, especially when the argument
// can be bound to the positional parameter from the default set WITHOUT type coercion.
// Example:
// Set-Location c:\win<tab>
// In this scenario, the user actually intends to use -Path implicitly, and we should not preserve the -LiteralPath. But if we fail
// on the attempt with the (default set + no coercion), we should fall back to the (all valid set + with coercion) to preserve possibilities.
// Example:
// Add-Member notep<tab>
// We need presever the -MemberType along with the -NotePropertyName in this case.
//
// So the algorithm for positional binding is:
// - With bindingType == ParameterCompletion
// Skip the attempt with the default set, as well as the attempt with all sets but no coercion.
// Do the positional binding with the (all valid set + with coercion) directly.
//
// - With bindingType == ArgumentCompletion (parameter argument completion)
// First try to do positional binding with (default set + no coercion)
// If the first attempt fails, do positional binding with (all valid set + with coercion)
//
// - With bindingType == ArgumentBinding (parameter argument binding, no completion)
// First try to do positional binding with (default set + no coercion)
// If the first attempt fails, do positional binding with (all valid set + without coercion)
// If the second attempt fails, do positional binding with (all valid set + with coercion)
bool aParameterGetBound = false;
if ((bindingType != BindingType.ParameterCompletion) && ((validParameterSetFlags & defaultParameterSetFlag) != 0))
{
// Default set, no coercion.
aParameterGetBound =
BindPseudoPositionalParameterInSet(
defaultParameterSetFlag,
nextPositionalParameters,
argument,
false);
}
if (!aParameterGetBound && (bindingType == BindingType.ArgumentBinding))
{
// All valid sets, no coercion.
aParameterGetBound =
BindPseudoPositionalParameterInSet(
validParameterSetFlags,
nextPositionalParameters,
argument,
false);
}
if (!aParameterGetBound)
{
// All valid sets, with coercion.
aParameterGetBound =
BindPseudoPositionalParameterInSet(
validParameterSetFlags,
nextPositionalParameters,
argument,
true);
}
if (!aParameterGetBound)
{
result.Add(argument);
}
else
{
// Update the parameter sets if necessary
if (validParameterSetFlags != _currentParameterSetFlag)
{
validParameterSetFlags = _currentParameterSetFlag;
ParameterBinderController.UpdatePositionalDictionary(positionalParameterDictionary, validParameterSetFlags);
}
}
}
for (int index = unboundArgumentsIndex; index < unboundArgumentsCollection.Count; ++index)
{
result.Add(unboundArgumentsCollection[index]);
}
}
return result;
}
private bool BindPseudoPositionalParameterInSet(
uint validParameterSetFlag,
Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters,
AstParameterArgumentPair argument,
bool typeConversion)
{
bool bindingSuccessful = false;
uint localParameterSetFlag = 0;
foreach (PositionalCommandParameter parameter in nextPositionalParameters.Values)
{
foreach (ParameterSetSpecificMetadata parameterSetData in parameter.ParameterSetData)
{
// Skip it if it's not in the specified parameter set
if ((validParameterSetFlag & parameterSetData.ParameterSetFlag) == 0 &&
!parameterSetData.IsInAllSets)
{
continue;
}
bool result = false;
string parameterName = parameter.Parameter.Parameter.Name;
Type parameterType = parameter.Parameter.Parameter.Type;
Type argumentType = argument.ArgumentType;
// 1. the argument type is not known(typeof(object)). we assume the binding always succeeds
// 2. the argument type is the same as parameter type, we assume the binding succeeds
// 3. the types are not the same, but we allow conversion, we assume the binding succeeds
// 4. the types are not the same, and conversion is not allowed, we assume the binding fails
if (argumentType == typeof(object))
bindingSuccessful = result = true;
else if (IsTypeEquivalent(argumentType, parameterType))
bindingSuccessful = result = true;
else if (typeConversion)
bindingSuccessful = result = true;
if (result)
{
localParameterSetFlag |= parameter.Parameter.Parameter.ParameterSetFlags;
_unboundParameters.Remove(parameter.Parameter);
if (!_boundParameters.ContainsKey(parameterName))
{
_boundParameters.Add(parameterName, parameter.Parameter);
_boundPositionalParameter.Add(parameterName);
}
if (!_boundArguments.ContainsKey(parameterName))
{
_boundArguments.Add(parameterName, argument);
}
break;
}
}
}
// We preserve all possibilities
if (bindingSuccessful && localParameterSetFlag != 0)
_currentParameterSetFlag &= localParameterSetFlag;
return bindingSuccessful;
}
private static bool IsTypeEquivalent(Type argType, Type paramType)
{
bool result = false;
if (argType == paramType)
{
result = true;
}
else if (argType.IsSubclassOf(paramType))
{
result = true;
}
else if (argType == paramType.GetElementType())
{
result = true;
}
else if (argType.IsSubclassOf(typeof(Array)) && paramType.IsSubclassOf(typeof(Array)))
{
result = true;
}
return result;
}
private static AstParameterArgumentPair GetNextPositionalArgument(
List<AstParameterArgumentPair> unboundArgumentsCollection,
Collection<AstParameterArgumentPair> nonPositionalArguments,
ref int unboundArgumentsIndex)
{
// Find the next positional parameter. An argument without the parameter being
// specified is considered to be a positional argument
AstParameterArgumentPair result = null;
while (unboundArgumentsIndex < unboundArgumentsCollection.Count)
{
AstParameterArgumentPair argument = unboundArgumentsCollection[unboundArgumentsIndex++];
if (argument is AstPair astPair
&& astPair.Argument is VariableExpressionAst argumentVariable
&& argumentVariable.Splatted)
{
continue;
}
if (!argument.ParameterSpecified)
{
result = argument;
break;
}
nonPositionalArguments.Add(argument);
}
return result;
}
private Collection<AstParameterArgumentPair> BindRemainingParameters(Collection<AstParameterArgumentPair> unboundArguments)
{
bool result = false;
uint localParameterSetFlag = 0;
if (!_bindingEffective || unboundArguments.Count == 0)
return unboundArguments;
Collection<ExpressionAst> argList = new Collection<ExpressionAst>();
foreach (AstParameterArgumentPair arg in unboundArguments)
{
AstPair realArg = arg as AstPair;
Diagnostics.Assert(realArg != null && !realArg.ParameterSpecified && !realArg.ArgumentIsCommandParameterAst,
"all unbound arguments left should be pure ExpressionAst arguments");
argList.Add((ExpressionAst)realArg.Argument);
}
var unboundParametersCopy = new List<MergedCompiledCommandParameter>(_unboundParameters);
foreach (MergedCompiledCommandParameter unboundParam in unboundParametersCopy)
{
bool isInParameterSet = (unboundParam.Parameter.ParameterSetFlags & _currentParameterSetFlag) != 0 ||
unboundParam.Parameter.IsInAllSets;
if (!isInParameterSet)
{
continue;
}
var parameterSetDataCollection = unboundParam.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag);
foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection)
{
if (!parameterSetData.ValueFromRemainingArguments)
{
continue;
}
localParameterSetFlag |= unboundParam.Parameter.ParameterSetFlags;
string parameterName = unboundParam.Parameter.Name;
_unboundParameters.Remove(unboundParam);
if (!_boundParameters.ContainsKey(parameterName))
{
_boundParameters.Add(parameterName, unboundParam);
}
if (!_boundArguments.ContainsKey(parameterName))
{
_boundArguments.Add(parameterName, new AstArrayPair(parameterName, argList));
unboundArguments.Clear();
}
result = true;
break;
}
}
if (result && localParameterSetFlag != 0)
_currentParameterSetFlag &= localParameterSetFlag;
return unboundArguments;
}
private void BindPipelineParameters()
{
bool result = false;
uint localParameterSetFlag = 0;
if (!_bindingEffective || !_isPipelineInputExpected)
{
return;
}
var unboundParametersCopy = new List<MergedCompiledCommandParameter>(_unboundParameters);
foreach (MergedCompiledCommandParameter unboundParam in unboundParametersCopy)
{
if (!unboundParam.Parameter.IsPipelineParameterInSomeParameterSet)
continue;
bool isInParameterSet = (unboundParam.Parameter.ParameterSetFlags & _currentParameterSetFlag) != 0 ||
unboundParam.Parameter.IsInAllSets;
if (!isInParameterSet)
{
continue;
}
var parameterSetDataCollection = unboundParam.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag);
foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection)
{
// We don't assume the 'ValueFromPipelineByPropertyName' parameters get bound
if (!parameterSetData.ValueFromPipeline)
{
continue;
}
localParameterSetFlag |= unboundParam.Parameter.ParameterSetFlags;
string parameterName = unboundParam.Parameter.Name;
_unboundParameters.Remove(unboundParam);
if (!_boundParameters.ContainsKey(parameterName))
{
_boundParameters.Add(parameterName, unboundParam);
}
if (!_boundArguments.ContainsKey(parameterName))
{
_boundArguments.Add(parameterName, new PipeObjectPair(parameterName, _pipelineInputType));
}
result = true;
break;
}
}
if (result && localParameterSetFlag != 0)
_currentParameterSetFlag &= localParameterSetFlag;
}
}
}
|