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
18 changes: 18 additions & 0 deletions src/System.Management.Automation/engine/parser/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,18 @@ internal static class CachedReflectionInfo
internal static readonly MethodInfo EnumerableOps_GetSlice =
typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetSlice), StaticFlags);

internal static readonly MethodInfo EnumerableOps_GetTupleSlice =
typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetTupleSlice), StaticFlags);

internal static readonly MethodInfo EnumerableOps_GetDeconstructMethod =
typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetDeconstructMethod), StaticFlags);

internal static readonly MethodInfo EnumerableOps_InvokeDeconstruct =
typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.InvokeDeconstruct), StaticFlags);

internal static readonly MethodInfo EnumerableOps_GetDeconstructSlice =
typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetDeconstructSlice), StaticFlags);

internal static readonly MethodInfo EnumerableOps_MethodInvoker =
typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.MethodInvoker), StaticFlags);

Expand Down Expand Up @@ -285,6 +297,12 @@ internal static class CachedReflectionInfo
internal static readonly MethodInfo IList_get_Item =
typeof(IList).GetMethod("get_Item");

internal static readonly PropertyInfo ITuple_Length =
typeof(ITuple).GetProperty(nameof(ITuple.Length));

internal static readonly MethodInfo ITuple_get_Item =
typeof(ITuple).GetMethod("get_Item");

internal static readonly MethodInfo InterpreterError_NewInterpreterException =
typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterException), StaticFlags);

Expand Down
119 changes: 119 additions & 0 deletions src/System.Management.Automation/engine/runtime/Binding/Binders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,125 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje
restrictions)).WriteToDebugLog(this);
}

if (target.Value is ITuple iTuple)
{
// Handle ITuple types (System.Tuple, System.ValueTuple, etc.)
// 3 possibilities - too few, exact, or too many elements.

var getTupleLengthExpr = Expression.Property(target.Expression.Cast(typeof(ITuple)), CachedReflectionInfo.ITuple_Length);

var restrictions = target.PSGetTypeRestriction().Merge(
BindingRestrictions.GetExpressionRestriction(Expression.Equal(getTupleLengthExpr,
ExpressionCache.Constant(iTuple.Length))));

int i;
Expression[] newArrayElements = new Expression[_elements];
var temp = Expression.Variable(typeof(ITuple));
if (iTuple.Length <= _elements)
{
// Too few or exact, create an array with the correct number assigned, fill in null for the extras

for (i = 0; i < iTuple.Length; ++i)
{
newArrayElements[i] =
Expression.Call(temp, CachedReflectionInfo.ITuple_get_Item, ExpressionCache.Constant(i));
}

for (; i < _elements; ++i)
{
newArrayElements[i] = ExpressionCache.NullConstant;
}
}
else
{
// Too many, create an array with the correct number assigned, and the last element contains
// all the extras.
for (i = 0; i < _elements - 1; ++i)
{
newArrayElements[i] =
Expression.Call(temp, CachedReflectionInfo.ITuple_get_Item, ExpressionCache.Constant(i));
}

newArrayElements[_elements - 1] =
Expression.Call(CachedReflectionInfo.EnumerableOps_GetTupleSlice, temp, ExpressionCache.Constant(_elements - 1)).Cast(typeof(object));
}

return (new DynamicMetaObject(
Expression.Block(
new[] { temp },
Expression.Assign(temp, target.Expression.Cast(typeof(ITuple))),
Expression.NewArrayInit(typeof(object), newArrayElements)),
restrictions)).WriteToDebugLog(this);
}

// Handle types with Deconstruct method (DictionaryEntry, KeyValuePair<,>, etc.)
var deconstructMethod = EnumerableOps.GetDeconstructMethod(target.Value.GetType());
if (deconstructMethod is not null)
{
var paramCount = deconstructMethod.GetParameters().Length;
var restrictions = target.PSGetTypeRestriction();

Expression[] newArrayElements = new Expression[_elements];
var methodExpr = Expression.Constant(deconstructMethod, typeof(MethodInfo));

if (paramCount <= _elements)
{
// Fewer or exact deconstructed values than variables
// Call InvokeDeconstruct and extract each element, fill extras with null
var tempArray = Expression.Variable(typeof(object[]), "deconstructed");
var invokeExpr = Expression.Call(
CachedReflectionInfo.EnumerableOps_InvokeDeconstruct,
target.Expression.Cast(typeof(object)),
methodExpr);

for (int i = 0; i < paramCount; i++)
{
newArrayElements[i] = Expression.ArrayIndex(tempArray, ExpressionCache.Constant(i));
}

for (int i = paramCount; i < _elements; i++)
{
newArrayElements[i] = ExpressionCache.NullConstant;
}

return (new DynamicMetaObject(
Expression.Block(
new[] { tempArray },
Expression.Assign(tempArray, invokeExpr),
Expression.NewArrayInit(typeof(object), newArrayElements)),
restrictions)).WriteToDebugLog(this);
}
else
{
// More deconstructed values than variables
// First N-1 get individual values, last gets remaining as array
// Note: GetDeconstructSlice takes the already-deconstructed array (tempArray)
// to avoid calling Deconstruct() multiple times.
var tempArray = Expression.Variable(typeof(object[]), "deconstructed");
var invokeExpr = Expression.Call(
CachedReflectionInfo.EnumerableOps_InvokeDeconstruct,
target.Expression.Cast(typeof(object)),
methodExpr);

for (int i = 0; i < _elements - 1; i++)
{
newArrayElements[i] = Expression.ArrayIndex(tempArray, ExpressionCache.Constant(i));
}

newArrayElements[_elements - 1] = Expression.Call(
CachedReflectionInfo.EnumerableOps_GetDeconstructSlice,
tempArray,
ExpressionCache.Constant(_elements - 1)).Cast(typeof(object));

return (new DynamicMetaObject(
Expression.Block(
new[] { tempArray },
Expression.Assign(tempArray, invokeExpr),
Expression.NewArrayInit(typeof(object), newArrayElements)),
restrictions)).WriteToDebugLog(this);
}
}

// We have a single element, the rest must be null.
return (new DynamicMetaObject(
Expression.NewArrayInit(typeof(object), Enumerable.Repeat(ExpressionCache.NullConstant, _elements - 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3640,6 +3640,93 @@ internal static object[] GetSlice(IList list, int startIndex)

return result;
}

/// <summary>
/// Gets a slice of elements from an ITuple starting at the specified index.
/// Used for array assignment when there are more tuple elements than variables.
/// </summary>
/// <param name="tuple">The tuple to slice.</param>
/// <param name="startIndex">The starting index.</param>
/// <returns>An array containing the remaining elements.</returns>
internal static object[] GetTupleSlice(ITuple tuple, int startIndex)
{
int countElements = tuple.Length - startIndex;
object[] result = new object[countElements];

int i = startIndex;
int j = 0;
while (j < countElements)
{
result[j++] = tuple[i++];
}

return result;
}

/// <summary>
/// Attempts to find a Deconstruct method on the given type.
/// </summary>
/// <param name="type">The type to search.</param>
/// <returns>The Deconstruct method info, or null if not found.</returns>
internal static MethodInfo GetDeconstructMethod(Type type)
{
// Look for a public instance method named "Deconstruct" with all out parameters
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
if (method.Name != "Deconstruct" || method.ReturnType != typeof(void))
{
continue;
}

var parameters = method.GetParameters();
if (parameters.Length == 0)
{
continue;
}

if (parameters.All(param => param.IsOut))
{
return method;
}
}

return null;
}

/// <summary>
/// Invokes the Deconstruct method on the given object and returns the deconstructed values.
/// </summary>
/// <param name="obj">The object to deconstruct.</param>
/// <param name="method">The Deconstruct method to invoke.</param>
/// <returns>An array containing the deconstructed values.</returns>
internal static object[] InvokeDeconstruct(object obj, MethodInfo method)
{
var parameters = method.GetParameters();
var args = new object[parameters.Length];
method.Invoke(obj, args);
return args;
}

/// <summary>
/// Gets a slice of values starting at the specified index.
/// Used for array assignment when there are more deconstructed values than variables.
/// This method takes the already-deconstructed array to avoid calling Deconstruct() multiple times.
/// </summary>
/// <param name="allValues">The array of all deconstructed values.</param>
/// <param name="startIndex">The starting index.</param>
/// <returns>An array containing the remaining values.</returns>
internal static object[] GetDeconstructSlice(object[] allValues, int startIndex)
{
int countElements = allValues.Length - startIndex;
object[] result = new object[countElements];

for (int i = 0; i < countElements; i++)
{
result[i] = allValues[startIndex + i];
}

return result;
}
}

internal static class MemberInvocationLoggingOps
Expand Down
136 changes: 136 additions & 0 deletions test/powershell/Language/Scripting/Indexer.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,140 @@ Describe 'Tests for indexers' -Tags "CI" {
$tuple = [Tuple]::Create(10, 'Hello')
$tuple[-1] | Should -BeExactly 'Hello'
}

It 'ITuple can be assigned to multiple variables with exact element count' {
$tuple = [Tuple]::Create(1, 2)
$a, $b = $tuple
$a | Should -Be 1
$b | Should -Be 2
}

It 'Single element Tuple can be assigned to multiple variables' {
$tuple = [Tuple]::Create(1)
$a, $b = $tuple
$a | Should -Be 1
$b | Should -BeNullOrEmpty
}

It 'Tuple with 7 elements can be assigned to multiple variables' {
$tuple = [Tuple]::Create(1, 2, 3, 4, 5, 6, 7)
$a, $b, $c, $d, $e, $f, $g = $tuple
$a | Should -Be 1
$b | Should -Be 2
$c | Should -Be 3
$d | Should -Be 4
$e | Should -Be 5
$f | Should -Be 6
$g | Should -Be 7
}

It 'Tuple with 8 elements can be assigned to multiple variables' {
$tuple = [Tuple]::Create(1, 2, 3, 4, 5, 6, 7, 8)
$a, $b, $c, $d, $e, $f, $g, $h = $tuple
$a | Should -Be 1
$b | Should -Be 2
$c | Should -Be 3
$d | Should -Be 4
$e | Should -Be 5
$f | Should -Be 6
$g | Should -Be 7
$h | Should -Be 8
}

It 'ValueTuple can be assigned to multiple variables' {
$vtuple = [ValueTuple]::Create("x", "y", "z")
$a, $b, $c = $vtuple
$a | Should -BeExactly "x"
$b | Should -BeExactly "y"
$c | Should -BeExactly "z"
}

It 'ITuple with more elements than variables assigns remaining to last variable' {
$tuple = [Tuple]::Create(10, 20, 30)
$first, $rest = $tuple
$first | Should -Be 10
$rest | Should -Be @(20, 30)
}

It 'ITuple with fewer elements than variables assigns null to extras' {
$tuple = [Tuple]::Create(100, 200)
$x, $y, $z = $tuple
$x | Should -Be 100
$y | Should -Be 200
$z | Should -BeNullOrEmpty
}

It 'Math.DivRem result can be assigned to multiple variables' {
$quotient, $remainder = [Math]::DivRem(17, 5)
$quotient | Should -Be 3
$remainder | Should -Be 2
}

It 'DictionaryEntry can be assigned to multiple variables' {
$de = [System.Collections.DictionaryEntry]::new("testKey", "testValue")
$key, $value = $de
$key | Should -BeExactly "testKey"
$value | Should -BeExactly "testValue"
}

It 'KeyValuePair can be assigned to multiple variables' {
$kvp = [System.Collections.Generic.KeyValuePair[string, int]]::new("count", 42)
$k, $v = $kvp
$k | Should -BeExactly "count"
$v | Should -Be 42
}

It 'DictionaryEntry with more variables than elements assigns null to extras' {
$de = [System.Collections.DictionaryEntry]::new("key", "value")
$a, $b, $c = $de
$a | Should -BeExactly "key"
$b | Should -BeExactly "value"
$c | Should -BeNullOrEmpty
}

It 'Hashtable enumeration produces deconstructable DictionaryEntry' {
$ht = @{ name = "test" }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the feature work for PSCustomObject?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, PSCustomObject is not supported. It doesn't implement ITuple, IList, or have a Deconstruct method.

I intentionally didn't add support because PSCustomObject properties are name-based, not position-based. Order-based deconstruction would be fragile:

$person = [PSCustomObject]@{ name = "John"; age = 30 }
$name, $age = $person  # Works

# Later, add a property...
$person = [PSCustomObject]@{ id = 1; name = "John"; age = 30 }
$name, $age = $person  # Silently breaks: $name = 1, $age = "John"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name-based matching (like JavaScript's const { name, age } = person) would be safer, but I believe that would require a different approach and new syntax—beyond the scope of this PR.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it seems we have such issue for named arguments and could enhance it to the area.

foreach ($entry in $ht.GetEnumerator()) {
$k, $v = $entry
$k | Should -BeExactly "name"
$v | Should -BeExactly "test"
}
}

It 'Deconstruct method should only be called once during array assignment' {
Add-Type -TypeDefinition @'
public class DeconstructCounter
{
public static int CallCount = 0;
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }

public DeconstructCounter(string a, string b, string c)
{
A = a;
B = b;
C = c;
}

public void Deconstruct(out string a, out string b, out string c)
{
CallCount++;
a = A;
b = B;
c = C;
}
}
'@
[DeconstructCounter]::CallCount = 0
$obj = [DeconstructCounter]::new("x", "y", "z")

# This assignment should call Deconstruct only once
# even though there are more deconstructed values (3) than variables (2)
$first, $rest = $obj

$first | Should -BeExactly "x"
$rest | Should -Be @("y", "z")
[DeconstructCounter]::CallCount | Should -Be 1 -Because "Deconstruct should only be called once"
}
}