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

LanguageNormalizingExpressionVisitor for VB.NET string comparisons #19681

Merged
merged 1 commit into from
Jan 29, 2020
Merged
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
120 changes: 120 additions & 0 deletions src/EFCore/Query/Internal/LanguageNormalizingExpressionVisitor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Microsoft.EntityFrameworkCore.Query.Internal
{
/// <summary>
/// Normalizes certain language-specific aspects of the expression trees produced by languages other
/// than C#, e.g. Visual Basic.
/// </summary>
public class LanguageNormalizingExpressionVisitor : ExpressionVisitor
{
private static readonly MethodInfo _stringCompareWithComparisonMethod
= typeof(string).GetRuntimeMethod(
nameof(string.Compare),
new[] { typeof(string), typeof(string), typeof(StringComparison) });

private static readonly MethodInfo _stringCompareWithoutComparisonMethod
= typeof(string).GetRuntimeMethod(
nameof(string.Compare),
new[] { typeof(string), typeof(string) });

private static readonly MethodInfo _stringEqualsMethod
= typeof(string).GetRuntimeMethod(
nameof(string.Equals),
new[] { typeof(string), typeof(string), typeof(StringComparison) });

protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
var visited = (MethodCallExpression)base.VisitMethodCall(methodCallExpression);

// In VB.NET, comparison operators between strings (equality, greater-than, less-than) yield
// calls to a VB-specific CompareString method. Normalize that to string.Compare.
if (visited.Method.Name == "CompareString"
&& visited.Method.DeclaringType?.Name == "Operators"
&& visited.Method.DeclaringType?.Namespace == "Microsoft.VisualBasic.CompilerServices"
&& visited.Object == null
&& visited.Arguments.Count == 3
&& visited.Arguments[2] is ConstantExpression textCompareConstantExpression)
{
return (bool)textCompareConstantExpression.Value
? Expression.Call(
_stringCompareWithComparisonMethod,
visited.Arguments[0],
visited.Arguments[1],
Expression.Constant(StringComparison.OrdinalIgnoreCase))
: Expression.Call(
_stringCompareWithoutComparisonMethod,
visited.Arguments[0],
visited.Arguments[1]);
}

return visited;
}

protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
var visitedLeft = Visit(binaryExpression.Left);
var visitedRight = Visit(binaryExpression.Right);

// In VB.NET, str1 = str2 yields CompareString(str1, str2, false) == 0.
// Rewrite this is as a regular equality node.
if (binaryExpression.NodeType == ExpressionType.Equal
|| binaryExpression.NodeType == ExpressionType.NotEqual)
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we handle >, >=, <, and <= too? Or does the compiler never generate those

Copy link
Member Author

@roji roji Jan 28, 2020

Choose a reason for hiding this comment

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

Or does the compiler never generate those

Not that I know of. In C#, string > string doesn't compile, and in VB.NET it compiles to CompareString(s1, s2, false) > 0; we do translate that above to string.Compare(s1, s2), and it turns out EF Core does translate that, so we get:

SELECT [b].[Id], [b].[Name]
FROM [Blogs] AS [b]
WHERE CASE
    WHEN N'hello' = [b].[Name] THEN 0
    WHEN N'hello' > [b].[Name] THEN 1
    WHEN N'hello' < [b].[Name] THEN -1
END > 0

Copy link
Member Author

Choose a reason for hiding this comment

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

Note: opened #19733 to do better with that.

Copy link
Member

Choose a reason for hiding this comment

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

This should have converted to string.Compare in C# rather than trying to convert to equality.

Copy link
Member Author

Choose a reason for hiding this comment

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

Any particular reason?

Copy link
Member

Choose a reason for hiding this comment

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

causes fragmentation in set of optimizations.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm sure I'm just being slow or dumb, but could you take a minute and explain exactly what you mean? Fragmentation where, which set of optimizations...

{
var (compareStringExpression, otherExpression) =
IsStringCompare(visitedLeft)
? ((MethodCallExpression)visitedLeft, visitedRight)
: IsStringCompare(visitedRight)
? ((MethodCallExpression)visitedRight, visitedLeft)
: (null, null);

if (compareStringExpression?.Method == _stringCompareWithoutComparisonMethod)
{
compareStringExpression = Expression.Call(
_stringCompareWithComparisonMethod,
compareStringExpression.Arguments[0],
compareStringExpression.Arguments[1],
Expression.Constant(StringComparison.Ordinal));
}

if (compareStringExpression != null
&& (compareStringExpression.Arguments[2] as ConstantExpression)?.Value is StringComparison stringComparison
&& otherExpression is ConstantExpression otherConstantExpression
&& (int)otherConstantExpression.Value == 0)
{
switch (stringComparison)
{
case StringComparison.Ordinal:
return Expression.MakeBinary(
binaryExpression.NodeType,
compareStringExpression.Arguments[0],
compareStringExpression.Arguments[1]);

case StringComparison.OrdinalIgnoreCase:
var stringEqualsExpression = Expression.Call(
_stringEqualsMethod,
compareStringExpression.Arguments[0],
compareStringExpression.Arguments[1],
Expression.Constant(StringComparison.OrdinalIgnoreCase)
);
return binaryExpression.NodeType == ExpressionType.Equal
? (Expression)stringEqualsExpression
: Expression.Not(stringEqualsExpression);
}
}
}

return binaryExpression.Update(visitedLeft, binaryExpression.Conversion, visitedRight);

static bool IsStringCompare(Expression expression)
=> expression is MethodCallExpression methodCallExpression
&& (methodCallExpression.Method == _stringCompareWithComparisonMethod
|| methodCallExpression.Method == _stringCompareWithoutComparisonMethod);
}
}
}
1 change: 1 addition & 0 deletions src/EFCore/Query/QueryTranslationPreprocessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public virtual Expression Process([NotNull] Expression query)
query = new EnumerableToQueryableMethodConvertingExpressionVisitor().Visit(query);
query = new QueryMetadataExtractingExpressionVisitor(_queryCompilationContext).Visit(query);
query = new InvocationExpressionRemovingExpressionVisitor().Visit(query);
query = new LanguageNormalizingExpressionVisitor().Visit(query);
query = new AllAnyToContainsRewritingExpressionVisitor().Visit(query);
query = new GroupJoinFlatteningExpressionVisitor().Visit(query);
query = new NullCheckRemovingExpressionVisitor().Visit(query);
Expand Down