Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,10 @@ static ExperimentalFeature()
description: "Enable `-CommandWithArgs` parameter for pwsh"),
new ExperimentalFeature(
name: PSNativeWindowsTildeExpansion,
description: "On windows, expand unquoted tilde (`~`) with the user's current home folder."
)
description: "On windows, expand unquoted tilde (`~`) with the user's current home folder."),
new ExperimentalFeature(
name: "PSNativeParameterParsing",
description: "Adjust how parameters are parsed and passed to better support native applications."),
};

EngineExperimentalFeatures = new ReadOnlyCollection<ExperimentalFeature>(engineFeatures);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO;
using System.Linq;
using System.Management.Automation.Internal;
using System.Reflection.Metadata;
using System.Text;

using Microsoft.PowerShell.Commands;
Expand Down Expand Up @@ -67,12 +68,97 @@ internal override object GetDefaultParameterValue(string name)
return null;
}

/// <summary>
/// Possibly create a new argument made up of two arguments that have no space between them.
/// </summary>
/// <param name="currentParameter">The current parameter being prepared for native execution.</param>
/// <param name="nextParameter">The next parameter to be inspected to determine whether it should be combined with the current.</param>
/// <returns>A composite CommandParameterInternal representing the two provided parameters.</returns>
internal CommandParameterInternal BuildCompositeArgument(CommandParameterInternal currentParameter, CommandParameterInternal nextParameter)
{
// if the end of the current parameter is the same as the start of the next parameter, then we want to combine them.
if (currentParameter.ParameterExtent.EndOffset == nextParameter.ArgumentExtent.StartOffset)
{
// if we get an EndOffset of 0, it means that the parameter was generated by the minishell code.
// In that case, we don't want to try to combine the parameters.
if (currentParameter.ParameterExtent.EndOffset == 0)
{
return null;
}

StringBuilder sb = new StringBuilder();
if (currentParameter.ParameterAst is not null)
{
sb.Append(currentParameter.ParameterText);
}

if (currentParameter.ArgumentAst is not null)
{
sb.Append(currentParameter.ArgumentValue);
}

// we want to take the value of the next parameter rather than the extent.
sb.Append(nextParameter.ArgumentValue);

// Re-parse the string to validate as valid as we need the AST to create the new composite argument.
// If it is, we will return that composite argument.
var stringAst = Parser.ParseInput('"' + sb.ToString() + '"', out _, out _).Find(ast => ast is StringConstantExpressionAst, searchNestedScriptBlocks: true);
if (stringAst is not null)
{
string compositeString = sb.ToString();
var ph = new PositionHelper(string.Empty, compositeString);
var startOffset = currentParameter.ParameterExtent.StartOffset;
var scriptExtent = new InternalScriptExtent(ph, startOffset, startOffset + compositeString.Length + 1);
var compositeAst = new StringConstantExpressionAst(scriptExtent, compositeString, StringConstantType.BareWord);
var compositeArgument = CommandParameterInternal.CreateArgument(compositeString, compositeAst, false);
return compositeArgument;
}
}

// It is also possible that the current parameter is an argument only, we still need to check to see if we can combine it with the next parameter.
if (currentParameter.ParameterAst is null && currentParameter.ArgumentExtent.EndOffset == nextParameter.ArgumentExtent.StartOffset)
{
StringBuilder sb = new StringBuilder();
sb.Append(currentParameter.ArgumentValue);
sb.Append(nextParameter.ArgumentValue);
var stringAst = Parser.ParseInput('"' + sb.ToString() + '"', out _, out _).Find(ast => ast is StringConstantExpressionAst, searchNestedScriptBlocks: true);
if (stringAst is not null)
{
string compositeString = sb.ToString();
var startPosition = new ScriptPosition(string.Empty, 0, 0, compositeString);
var endPosition = new ScriptPosition(string.Empty, 0, compositeString.Length, sb.ToString());
var scriptExtent = new ScriptExtent(startPosition, endPosition);
var compositeAst = new StringConstantExpressionAst(scriptExtent, compositeString, StringConstantType.BareWord);
var compositeArgument = CommandParameterInternal.CreateArgument(compositeString, compositeAst, false);
return compositeArgument;
}
}

return null;
}

internal void BindParameters(Collection<CommandParameterInternal> parameters)
{
bool sawVerbatimArgumentMarker = false;
bool first = true;
foreach (CommandParameterInternal parameter in parameters)
for (int i = 0; i < parameters.Count; i++)
{
CommandParameterInternal parameter = parameters[i];

// check to see if we have two parameters which have no spaces between them.
// This could also be a parameter followed by an argument with no space between them.
if (ExperimentalFeature.IsEnabled("PSNativeParameterParsing") && i < parameters.Count - 1)
{
CommandParameterInternal compositeParameter = BuildCompositeArgument(parameter, parameters[i + 1]);

// If we were able to build a composite parameter, use it but skip the next parameter as it was used to create the composite.
if (compositeParameter is not null)
{
parameter = compositeParameter;
i++;
}
}

if (!first)
{
_arguments.Append(' ');
Expand Down Expand Up @@ -161,7 +247,7 @@ internal string[] ArgumentList
/// <param name="argument">The value used with parameter.</param>
internal void AddToArgumentList(CommandParameterInternal parameter, string argument)
{
if (parameter.ParameterNameSpecified && parameter.ParameterText.EndsWith(":"))
if (parameter.ParameterNameSpecified && (parameter.ParameterText.EndsWith(":") || parameter.ParameterText.EndsWith("=")))
{
if (argument != parameter.ParameterText)
{
Expand Down Expand Up @@ -500,7 +586,7 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst,
afterPrev -= arrayExtent.StartOffset;
beforeNext -= arrayExtent.StartOffset;

if (arrayText[afterPrev] == ',')
if (arrayText[afterPrev] == ',')
{
return ", ";
}
Expand All @@ -509,7 +595,7 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst,
{
return " ,";
}

return " , ";
}

Expand Down
17 changes: 16 additions & 1 deletion src/System.Management.Automation/engine/parser/tokenizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3185,7 +3185,6 @@ private Token ScanVariable(bool splatted, bool inStringExpandable)
private Token ScanParameter()
{
var sb = GetStringBuilder();

bool scanning = true;
bool sawColonAtEnd = false;
while (scanning)
Expand Down Expand Up @@ -3217,6 +3216,22 @@ private Token ScanParameter()
scanning = false;
break;

case '=':
if (ExperimentalFeature.IsEnabled("PSWindowsNativeCommandArgPassing"))
{
// We have an '=' in the parameter which is highly unlikely to be a powershell
// construct. However, it is not uncommon that a native utility would have a
// parameter like -parm=value or -parm=$var or -parm="a b c" so in this case,
// just return an generic token.
// We need to insert the '-' that was skipped when we thought it was our parameter.
UngetChar();
sb.Insert(0, _script[_tokenStart]);
return ScanGenericToken(sb);
}

// if the experimental feature is not enabled, just treat is as default case
goto default;

case ':':
scanning = false;
sawColonAtEnd = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,72 @@ Describe "find.exe uses legacy behavior on Windows" -Tag 'CI' {
}
}

Describe "parameters are properly bound when complex" -Tag 'CI' {

BeforeAll {
$ef = get-experimentalfeature -name PSNativeParameterParsing
$enabled = $ef -eq $null ? $false : $ef.Enabled
$a = "STR STR"
$o = [pscustomobject]@{ one = 1; two = @{ three = 4 }}
$tests = @(
@{ sb = {testexe -echoargs -foo 'bar'""}; Expected = @("-foo","bar") }
@{ sb = {testexe -echoargs -foo ""'bar'}; Expected = @("-foo","bar") }
@{ sb = {testexe -echoargs -foo ""bar}; Expected = @("-foo","bar") }
@{ sb = {testexe -echoargs -foo " "ab" de "f}; Expected = @("-foo"," ab de f") }
@{ sb = {testexe -echoargs -foo:bar" "baz}; Expected = @("-foo:bar baz") }
@{ sb = {testexe -echoargs -foo:""bar}; Expected = @("-foo:bar") }
@{ sb = {testexe -echoargs -foo:""bar""}; Expected = @("-foo:bar") }
@{ sb = {testexe -echoargs -foo:'"bar"'}; Expected = @("-foo:""bar""") }
@{ sb = {testexe -echoargs -foo:$null..6}; Expected = @("-foo:..6") }
@{ sb = {testexe -echoargs -foo:6..$null}; Expected = @("-foo:6..") }
@{ sb = {testexe -echoargs -foo:$a..$a}; Expected = @("-foo:STR STR..STR STR") }
@{ sb = {testexe -echoargs -foo:$a..6}; Expected = @("-foo:${a}..6") }
@{ sb = {testexe -echoargs -foo:${a}..6}; Expected = @("-foo:${a}..6") }
@{ sb = {testexe -echoargs -foo:6..$a}; Expected = @("-foo:6..STR STR") }
@{ sb = {testexe -echoargs -foo:6..${a}}; Expected = @("-foo:6..STR STR") }
@{ sb = {testexe -echoargs -foo=bar" "baz}; Expected = @("-foo=bar baz") }
@{ sb = {testexe -echoargs -foo=""bar}; Expected = @("-foo=bar") }
@{ sb = {testexe -echoargs -foo=""bar""}; Expected = @("-foo=bar") }
@{ sb = {testexe -echoargs -foo='"bar"'}; Expected = @("-foo=""bar""") }
@{ sb = {testexe -echoargs -foo=$null..6}; Expected = @("-foo=..6") }
@{ sb = {testexe -echoargs -foo=6..$null}; Expected = @("-foo=6..") }
@{ sb = {testexe -echoargs -foo=$a..6}; Expected = @("-foo=STR STR..6") }
@{ sb = {testexe -echoargs -foo=$a..$a}; Expected = @("-foo=STR STR..STR STR") }
@{ sb = {testexe -echoargs -foo=${a}..6}; Expected = @("-foo=STR STR..6") }
@{ sb = {testexe -echoargs -foo=6..$a}; Expected = @("-foo=6..STR STR") }
@{ sb = {testexe -echoargs ""bar""}; Expected = @("bar") }
@{ sb = {testexe -echoargs ""$null""}; Expected = @("") }
@{ sb = {testexe -echoargs ""$a""}; Expected = @("STR STR") }
@{ sb = {testexe -echoargs ""$a}; Expected = @("STR STR") }
@{ sb = {testexe -echoargs $a""}; Expected = @("STR STR") }
@{ sb = {testexe -echoargs 1,2,3}; Expected = @("1,2,3") }
@{ sb = {testexe -echoargs bar" "baz}; Expected = @("bar baz") }
@{ sb = {testexe -echoargs ""bar}; Expected = @("bar") }
@{ sb = {testexe -echoargs ""bar""}; Expected = @("bar") }
@{ sb = {testexe -echoargs '"bar"'}; Expected = @("""bar""") }
@{ sb = {testexe -echoargs $null..6}; Expected = @("..6") }
@{ sb = {testexe -echoargs 6..$null}; Expected = @("6..") }
@{ sb = {testexe -echoargs $a..6}; Expected = @("STR STR..6") }
@{ sb = {testexe -echoargs 6..$a}; Expected = @("6..STR STR") }
@{ sb = {testexe -echoargs 6..${a} }; Expected = @("6..STR STR") }
@{ sb = {testexe -echoargs $a..$a}; Expected = @("STR STR..STR STR") }
@{ sb = {testexe -echoargs ${a}..${a} }; Expected = @("STR STR..STR STR") }
@{ sb = [scriptblock]::Create('testexe -echoargs --% 6..$a'); Expected = @('6..$a') }
@{ sb = [scriptblock]::Create('testexe -echoargs $a..6..$a --% 6..$a'); Expected = @('STR STR..6..STR STR', '6..$a') }
Comment thread
JamesWTruher marked this conversation as resolved.
Resolved
)
}

It "'<sb>' should be bound properly" -testcase $tests -skip:(-not $enabled) {
param ($sb, $expected)
$eStrings = @()
for($i = 0; $i -lt $expected.Count; $i++) {
$eStrings += "Arg {0} is <{1}>" -f $i, $expected[$i]
}
$r = invoke-expression $sb.ToString()
$r | Should -Be $eStrings
}
}

foreach ( $argumentListValue in "Standard","Legacy","Windows" ) {
$PSNativeCommandArgumentPassing = $argumentListValue
Describe "Native Command Arguments (${PSNativeCommandArgumentPassing})" -tags "CI" {
Expand Down
15 changes: 11 additions & 4 deletions test/powershell/Language/Scripting/ParameterBinding.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,14 @@ Describe "Tests for parameter binding" -Tags "CI" {
$b -join ',' | Should -BeExactly '10,20,30,40,50,60,70,80,90,100'
}

It 'Value from remaining arguments' {
It "Value from remaining arguments for '<scriptblock>' should be '<expected>'" -TestCases @(
@{ scriptblock = { get-foo a b c d }; Expected = 'b','c','d' }
@{ scriptblock = { get-foo a b -a c d }; Expected = 'a','b','d' }
@{ scriptblock = { get-foo a b -a c -q d }; Expected = 'a','b','-q','d' }
@{ scriptblock = { get-foo a -p1:bar -p1=bar }; Expected = '-p1:', 'bar', '-p1=bar' }
@{ scriptblock = { get-foo a -p1:bar -p1=$str..$str }; Expected = '-p1:', 'bar', '-p1=str str..str str' }
) {
param ([scriptblock]$scriptblock, [object]$expected)
function get-foo
{
param(
Expand All @@ -151,9 +158,9 @@ Describe "Tests for parameter binding" -Tags "CI" {
$foo
}

( get-foo a b c d ) -join ',' | Should -BeExactly 'b,c,d'
( get-foo a b -a c d ) -join ',' | Should -BeExactly 'a,b,d'
( get-foo a b -a c -q d ) -join ',' | Should -BeExactly 'a,b,-q,d'
$str = "str str"
& $scriptblock | Should -BeExactly $expected

}

It 'Multiple parameter sets with Value from remaining arguments' {
Expand Down