Ensure null-coalescing LHS is evaluated only once (#12667)

This commit is contained in:
Robert Holt 2020-05-16 09:36:15 -07:00 committed by GitHub
parent 270eabc6c4
commit 3dfd95a09f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 10 deletions

View file

@ -982,19 +982,23 @@ namespace System.Management.Automation.Language
{
return left;
}
else if (leftType == typeof(AutomationNull))
{
return right;
}
else
{
Expression lhs = left.Cast(typeof(object));
Expression rhs = right.Cast(typeof(object));
ParameterExpression lhsStoreVar = Expression.Variable(typeof(object));
var blockParameters = new ParameterExpression[] { lhsStoreVar };
var blockStatements = new Expression[]
{
Expression.Assign(lhsStoreVar, left.Cast(typeof(object))),
Expression.Condition(
Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhsStoreVar),
right.Cast(typeof(object)),
lhsStoreVar),
};
return Expression.Condition(
Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhs),
rhs,
lhs);
return Expression.Block(
typeof(object),
blockParameters,
blockStatements);
}
}

View file

@ -172,6 +172,18 @@ Describe 'NullCoalesceOperations' -Tags 'CI' {
It 'Lhs is $?' {
{$???$false} | Should -BeTrue
}
It 'Should only evaluate LHS once when it IS null' {
$testState = [pscustomobject]@{ Value = 0 }
(& { [void]$testState.Value++ }) ?? 'Nothing' | Should -BeExactly 'Nothing'
$testState.Value | Should -Be 1
}
It 'Should only evaluate LHS once when it is NOT null' {
$testState = [pscustomobject]@{ Value = 0 }
(& { 'Test'; [void]$testState.Value++ }) ?? 'Nothing' | Should -BeExactly 'Test'
$testState.Value | Should -Be 1
}
}
Context 'Null Coalesce ?? operator precedence' {