Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix inference issues around convert to object #21125

Merged
merged 6 commits into from
Jun 13, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -11,6 +11,7 @@
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
Expand Down Expand Up @@ -161,6 +162,25 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
var left = TryRemoveImplicitConvert(binaryExpression.Left);
var right = TryRemoveImplicitConvert(binaryExpression.Right);

// Remove convert-to-object nodes if both sides have them, or if the other side is null constant
if (TryUnwrapConvertToObject(left, out var leftOperand))
{
if (TryUnwrapConvertToObject(right, out var rightOperand))
roji marked this conversation as resolved.
Show resolved Hide resolved
{
left = leftOperand;
right = rightOperand;
}
else if (right.IsNullConstantExpression())
{
left = leftOperand;
}
}
else if (TryUnwrapConvertToObject(right, out var rightOperand)
&& left.IsNullConstantExpression())
{
right = rightOperand;
}

var visitedLeft = Visit(left);
var visitedRight = Visit(right);

Expand Down Expand Up @@ -193,6 +213,53 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
sqlLeft,
sqlRight,
null);

static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked))
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}

var convertedType = unaryExpression.Type.UnwrapNullableType();

if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}

return expression;
}

static bool TryUnwrapConvertToObject(Expression expression, out Expression operand)
{
if (expression is UnaryExpression convertExpression
&& (convertExpression.NodeType == ExpressionType.Convert
|| convertExpression.NodeType == ExpressionType.ConvertChecked)
&& expression.Type == typeof(object))
{
if (!TryUnwrapConvertToObject(convertExpression.Operand, out operand))
roji marked this conversation as resolved.
Show resolved Hide resolved
{
operand = convertExpression.Operand;
}
return true;
}

operand = null;
return false;
}
}

/// <summary>
Expand Down Expand Up @@ -593,35 +660,6 @@ ObjectArrayProjectionExpression objectArrayProjectionExpression
};
}

private static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked))
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}

var convertedType = unaryExpression.Type.UnwrapNullableType();

if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}

return expression;
}

private bool TryRewriteContainsEntity(Expression source, Expression item, out Expression result)
{
result = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Utilities;
Expand Down Expand Up @@ -341,6 +342,25 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
var left = TryRemoveImplicitConvert(binaryExpression.Left);
var right = TryRemoveImplicitConvert(binaryExpression.Right);

// Remove convert-to-object nodes if both sides have them, or if the other side is null constant
if (TryUnwrapConvertToObject(left, out var leftOperand))
{
if (TryUnwrapConvertToObject(right, out var rightOperand))
{
left = leftOperand;
right = rightOperand;
}
else if (right.IsNullConstantExpression())
{
left = leftOperand;
}
}
else if (TryUnwrapConvertToObject(right, out var rightOperand)
&& left.IsNullConstantExpression())
{
right = rightOperand;
}

var visitedLeft = Visit(left);
var visitedRight = Visit(right);

Expand Down Expand Up @@ -370,6 +390,53 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
sqlLeft,
sqlRight,
null);

static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked))
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}

var convertedType = expression.Type.UnwrapNullableType();

if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}

return expression;
}

static bool TryUnwrapConvertToObject(Expression expression, out Expression operand)
{
if (expression is UnaryExpression convertExpression
&& (convertExpression.NodeType == ExpressionType.Convert
|| convertExpression.NodeType == ExpressionType.ConvertChecked)
&& expression.Type == typeof(object))
{
if (!TryUnwrapConvertToObject(convertExpression.Operand, out operand))
{
operand = convertExpression.Operand;
}
return true;
}

operand = null;
return false;
}
}

/// <inheritdoc />
Expand Down Expand Up @@ -884,37 +951,6 @@ private static Expression GetPredicateOnGrouping(
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}

private static Expression TryRemoveImplicitConvert(Expression expression)
Copy link
Member

Choose a reason for hiding this comment

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

Any reason to move this to local function? This is not specific to BinaryExpression.

Copy link
Member Author

Choose a reason for hiding this comment

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

Wasn't used anywhere else so I did it... We can always move it out if it's needed no?

Copy link
Member

Choose a reason for hiding this comment

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

Then we need to remember that we had method like this hiding here.
Local methods which are valid in a context of a particular method makes sense but not used elsewhere hence local could be bit non-productive.

cc: @dotnet/efcore ?

Copy link
Member Author

Choose a reason for hiding this comment

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

No need to bother everyone, I'll just move it out if that's what you want.

Copy link
Member

Choose a reason for hiding this comment

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

Found a usecase, there RemoveObjectConvert in VisitMethodCall too. You can DRY with TryUnwrapConvertToObject

Copy link
Member Author

Choose a reason for hiding this comment

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

In VisitBinary we need to know if we unwrapped or not (hence Try*), but in VisitMethodCall we don't (so it returns the unwrapped)... So DRYing would make VisitMethodCall clunkier (calling Try* and testing the result). Let's leave things the way they are, the code fragment is really small...

However I did DRY out RemoveObjectConvert in Relational which is used by both VisitMethodCall and ConvertObjectArrayEqualityComparison.

{
if (expression is UnaryExpression unaryExpression)
{
if (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked)
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}

var convertedType = unaryExpression.Type.UnwrapNullableType();

if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}
}

return expression;
}

private static Expression ConvertObjectArrayEqualityComparison(BinaryExpression binaryExpression)
{
var leftExpressions = ((NewArrayExpression)binaryExpression.Left).Expressions;
Expand Down
10 changes: 0 additions & 10 deletions src/EFCore/Extensions/Internal/ExpressionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,6 @@ namespace Microsoft.EntityFrameworkCore.Internal
/// </summary>
public static class ExpressionExtensions
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static bool IsNullConstantExpression([NotNull] this Expression expression)
=> RemoveConvert(expression) is ConstantExpression constantExpression
&& constantExpression.Value == null;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
24 changes: 24 additions & 0 deletions src/Shared/ExpressionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,25 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Diagnostics;
using JetBrains.Annotations;

// ReSharper disable once CheckNamespace
namespace System.Linq.Expressions
{
[DebuggerStepThrough]
internal static class ExpressionExtensions
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static bool IsNullConstantExpression([NotNull] this Expression expression)
=> RemoveConvert(expression) is ConstantExpression constantExpression
&& constantExpression.Value == null;


public static LambdaExpression UnwrapLambdaFromQuote(this Expression expression)
=> (LambdaExpression)(expression is UnaryExpression unary && expression.NodeType == ExpressionType.Quote
? unary.Operand
Expand All @@ -32,5 +44,17 @@ public static Expression UnwrapTypeConversion(this Expression expression, out Ty

return expression;
}

private static Expression RemoveConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (expression.NodeType == ExpressionType.Convert
|| expression.NodeType == ExpressionType.ConvertChecked))
{
return RemoveConvert(unaryExpression.Operand);
}

return expression;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1779,6 +1779,25 @@ public virtual Task Where_compare_null(bool async)
ss => ss.Set<Customer>().Where(c => c.City == null && c.Country == "UK"));
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Where_compare_null_with_cast_to_object(bool async)
{
return AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => (object)c.City == null));
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Where_compare_with_both_cast_to_object(bool async)
{
return AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => (object)c.City == (object)"London"),
entryCount: 6);
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task Where_projection(bool async)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public NorthwindWhereQuerySqlServerTest(NorthwindQuerySqlServerFixture<NoopModel
: base(fixture)
{
ClearLog();
//Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}

protected override bool CanExecuteQueryString => true;
Expand Down Expand Up @@ -1513,6 +1513,26 @@ FROM [Customers] AS [c]
WHERE [c].[City] IS NULL AND ([c].[Country] = N'UK')");
}

public override async Task Where_compare_null_with_cast_to_object(bool async)
{
await base.Where_compare_null_with_cast_to_object(async);

AssertSql(
@"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[City] IS NULL");
}

public override async Task Where_compare_with_both_cast_to_object(bool async)
{
await base.Where_compare_with_both_cast_to_object(async);

AssertSql(
@"SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[City] = N'London'");
}

public override async Task Where_Is_on_same_type(bool async)
{
await base.Where_Is_on_same_type(async);
Expand Down